Manual Pinescript
Manual Pinescript
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
openhighlowvolumetimehl2hlc3hlcc4ohlc4bid
bar_index
TYPE
series int
EXAMPLE
//@version=6
indicator("bar_index")
plot(bar_index)
REMARKS
Note that bar indexing starts from 0 on the first historical bar.
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
last_bar_indexbarstate.isfirstbarstate.islastbarstate.isrealtime
barstate.isconfirmed
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.
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
barstate.isfirstbarstate.islastbarstate.ishistorybarstate.isrealtimebarstate.isnewbarstate.islastcon
firmedhistory
barstate.isfirst
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
barstate.islastbarstate.ishistorybarstate.isrealtimebarstate.isnewbarstate.isconfirmedbarstate.isl
astconfirmedhistory
barstate.ishistory
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
barstate.isfirstbarstate.islastbarstate.isrealtimebarstate.isnewbarstate.isconfirmedbarstate.islastc
onfirmedhistory
barstate.islast
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
barstate.isfirstbarstate.ishistorybarstate.isrealtimebarstate.isnewbarstate.isconfirmedbarstate.isl
astconfirmedhistory
barstate.islastconfirmedhistory
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
barstate.isfirstbarstate.islastbarstate.ishistorybarstate.isrealtimebarstate.isnew
barstate.isnew
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
barstate.isfirstbarstate.islastbarstate.ishistorybarstate.isrealtimebarstate.isconfirmedbarstate.isla
stconfirmedhistory
barstate.isrealtime
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
barstate.isfirstbarstate.islastbarstate.ishistorybarstate.isnewbarstate.isconfirmedbarstate.islastco
nfirmedhistory
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
openhighlowvolumetimehl2hlc3hlcc4ohlc4ask
box.all
Returns an array filled with all the current boxes drawn by the script.
TYPE
array<box>
EXAMPLE
//@version=6
indicator("box.all")
a_allBoxes = box.all
if array.size(a_allBoxes) > 0
for i = 0 to array.size(a_allBoxes) - 1
box.delete(array.get(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
box.newline.alllabel.alltable.all
chart.bg_color
TYPE
input color
SEE ALSO
chart.fg_color
chart.fg_color
TYPE
input color
SEE ALSO
chart.bg_color
chart.is_heikinashi
TYPE
simple bool
RETURNS
SEE ALSO
chart.is_renkochart.is_linebreakchart.is_kagichart.is_pnfchart.is_range
chart.is_kagi
TYPE
simple bool
RETURNS
SEE ALSO
chart.is_renkochart.is_linebreakchart.is_heikinashichart.is_pnfchart.is_range
chart.is_linebreak
TYPE
simple bool
RETURNS
SEE ALSO
chart.is_renkochart.is_heikinashichart.is_kagichart.is_pnfchart.is_range
chart.is_pnf
TYPE
simple bool
RETURNS
Returns true if the chart type is Point & figure, false otherwise.
SEE ALSO
chart.is_renkochart.is_linebreakchart.is_kagichart.is_heikinashichart.is_range
chart.is_range
TYPE
simple bool
RETURNS
SEE ALSO
chart.is_renkochart.is_linebreakchart.is_kagichart.is_pnfchart.is_heikinashi
chart.is_renko
TYPE
simple bool
RETURNS
SEE ALSO
chart.is_heikinashichart.is_linebreakchart.is_kagichart.is_pnfchart.is_range
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.is_renkochart.is_linebreakchart.is_kagichart.is_pnfchart.is_rangechart.is_heikinashi
chart.left_visible_bar_time
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
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
openhighlowvolumetimehl2hlc3hlcc4ohlc4askbid
dayofmonth
TYPE
series int
REMARKS
Note that this variable returns the day 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 day of the trading day.
SEE ALSO
dayofmonthtimeyearmonthweekofyeardayofweekhourminutesecond
dayofweek
TYPE
series int
REMARKS
Note that this variable returns the day 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 day of the trading day.
You can
use dayofweek.sunday, dayofweek.monday, dayofweek.tuesday, dayofweek.wednesd
ay, dayofweek.thursday, dayofweek.friday and dayofweek.saturday variables for
comparisons.
SEE ALSO
dayofweektimeyearmonthweekofyeardayofmonthhourminutesecond
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
request.earnings
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
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
request.earnings
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
request.earnings
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
request.earnings
high
TYPE
series float
REMARKS
Previous values may be accessed with square brackets operator [], e.g. high[1],
high[2].
SEE ALSO
openlowclosevolumetimehl2hlc3hlcc4ohlc4askbid
hl2
TYPE
series float
SEE ALSO
openhighlowclosevolumetimehlc3hlcc4ohlc4askbid
hlc3
TYPE
series float
SEE ALSO
openhighlowclosevolumetimehl2hlcc4ohlc4askbid
hlcc4
TYPE
series float
SEE ALSO
openhighlowclosevolumetimehl2hlc3ohlc4askbid
hour
TYPE
series int
SEE ALSO
hourtimeyearmonthweekofyeardayofmonthdayofweekminutesecond
label.all
Returns an array filled with all the current labels drawn by the script.
TYPE
array<label>
EXAMPLE
//@version=6
indicator("label.all")
label.new(bar_index, close)
a_allLabels = label.all
if array.size(a_allLabels) > 0
for i = 0 to array.size(a_allLabels) - 1
label.delete(array.get(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
label.newline.allbox.alltable.all
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
// The 'last_bar_index' will change when new real-time bars appear, so we declare 'lastbar' with the 'var' k
eyword.
// Check if the current bar_index is 'lastBarsFilterInput' removed from the last bar on the chart, or the cha
rt is traded in real-time.
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
bar_indexlast_bar_timebarstate.ishistorybarstate.isrealtime
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
timetimenowtimestamplast_bar_index
line.all
Returns an array filled with all the current lines drawn by the script.
TYPE
array<line>
EXAMPLE
//@version=6
indicator("line.all")
a_allLines = line.all
if array.size(a_allLines) > 0
for i = 0 to array.size(a_allLines) - 1
line.delete(array.get(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
line.newlabel.allbox.alltable.all
linefill.all
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
TYPE
series float
REMARKS
Previous values may be accessed with square brackets operator [], e.g. low[1], low[2].
SEE ALSO
openhighclosevolumetimehl2hlc3hlcc4ohlc4askbid
minute
TYPE
series int
SEE ALSO
minutetimeyearmonthweekofyeardayofmonthdayofweekhoursecond
month
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
monthtimeyearweekofyeardayofmonthdayofweekhourminutesecond
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.
// CORRECT ALTERNATIVE
float a = na
if bar_index >= 10
a := close
plot(a)
// INCORRECT
// The next line, if uncommented, will cause a compilation error, because direct comparison with `na` is n
ot allowed.
// CORRECT
// 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
nanzfixnan
ohlc4
TYPE
series float
SEE ALSO
openhighlowclosevolumetimehl2hlc3hlcc4
open
TYPE
series float
REMARKS
Previous values may be accessed with square brackets operator [], e.g. open[1],
open[2].
SEE ALSO
highlowclosevolumetimehl2hlc3hlcc4ohlc4askbid
polyline.all
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
TYPE
series int
SEE ALSO
secondtimeyearmonthweekofyeardayofmonthdayofweekhourminute
session.isfirstbar
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
// Place a long order at the `close` of the trading session's first bar.
strategy.entry("Long", strategy.long)
// Close the long position at the `close` of the trading session's last bar.
SEE ALSO
session.isfirstbar_regularsession.islastbarsession.islastbar_regular
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
// Place a long order at the `close` of the trading session's first bar.
// Close the long position at the `close` of the trading session's last bar.
SEE ALSO
session.isfirstbarsession.islastbar
session.islastbar
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
// 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.
strategy.entry("Long", strategy.long)
// Close 'Long' position at the close of the last bar of the trading session
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.
SEE ALSO
session.isfirstbarsession.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
// Place a long order at the `close` of the trading session's first bar.
strategy.entry("Long", strategy.long)
// Close the long position at the `close` of the trading session's last bar.
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.
SEE ALSO
session.isfirstbarsession.islastbarsession.isfirstbar_regular
session.ismarket
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
session.ispremarketsession.ispostmarket
session.ispostmarket
Returns true if the current bar is a part of the post-market, false otherwise. On non-
intraday charts always returns false.
TYPE
series bool
SEE ALSO
session.ismarketsession.ispremarket
session.ispremarket
Returns true if the current bar is a part of the pre-market, false otherwise. On non-
intraday charts always returns false.
TYPE
series bool
SEE ALSO
session.ismarketsession.ispostmarket
strategy.account_currency
Returns the currency used to calculate results, which can be set in the strategy's
properties.
TYPE
simple string
SEE ALSO
strategystrategy.convert_to_accountstrategy.convert_to_symbol
strategy.avg_losing_trade
Returns the average amount of money lost per losing trade. Calculated as the sum of
losses divided by the number of losing trades.
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
strategy.closedtrades
Number of trades, which were closed for the whole trading range.
TYPE
series int
SEE ALSO
strategy.position_sizestrategy.opentradesstrategy.wintradesstrategy.losstradesstrategy.eventrad
es
strategy.closedtrades.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
strategy.position_sizestrategy.opentradesstrategy.wintradesstrategy.losstradesstrategy.eventrad
es
strategy.equity
TYPE
series float
SEE ALSO
strategy.netprofitstrategy.openprofitstrategy.position_size
strategy.eventrades
TYPE
series int
SEE ALSO
strategy.position_sizestrategy.opentradesstrategy.closedtradesstrategy.wintradesstrategy.losstra
des
strategy.grossloss
TYPE
series float
SEE ALSO
strategy.netprofitstrategy.grossprofit
strategy.grossloss_percent
The total value of all completed losing trades, expressed as a percentage of the initial
capital.
TYPE
series float
SEE ALSO
strategy.grossloss
strategy.grossprofit
TYPE
series float
SEE ALSO
strategy.netprofitstrategy.grossloss
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
strategy.grossprofit
strategy.initial_capital
TYPE
series float
SEE ALSO
strategy
strategy.losstrades
TYPE
series int
SEE ALSO
strategy.position_sizestrategy.opentradesstrategy.closedtradesstrategy.wintradesstrategy.eventr
ades
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
if ta.crossover(maFast, maSlow)
strategy.entry("Long", strategy.long)
if ta.crossunder(maFast, maSlow)
strategy.entry("Short", strategy.short)
// exit when we're 10% away from a margin call, to prevent it.
strategy.close("Long")
strategy.close("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
TYPE
series float
SEE ALSO
strategy.position_sizestrategy.max_contracts_held_longstrategy.max_contracts_held_short
strategy.max_contracts_held_long
TYPE
series float
SEE ALSO
strategy.position_sizestrategy.max_contracts_held_allstrategy.max_contracts_held_short
strategy.max_contracts_held_short
TYPE
series float
SEE ALSO
strategy.position_sizestrategy.max_contracts_held_allstrategy.max_contracts_held_long
strategy.max_drawdown
TYPE
series float
SEE ALSO
strategy.netprofitstrategy.equitystrategy.max_runup
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
TYPE
series float
SEE ALSO
strategy.netprofitstrategy.equitystrategy.max_drawdown
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
strategy.netprofit
TYPE
series float
SEE ALSO
strategy.openprofitstrategy.position_sizestrategy.grossprofitstrategy.grossloss
strategy.netprofit_percent
The total value of all completed trades, expressed as a percentage of the initial
capital.
TYPE
series float
SEE ALSO
strategy.netprofit
strategy.openprofit
TYPE
series float
SEE ALSO
strategy.netprofitstrategy.position_size
strategy.openprofit_percent
The current unrealized profit or loss for all open positions, expressed as a percentage
and calculated by formula: openPL / realizedEquity * 100.
TYPE
series float
SEE ALSO
strategy.openprofit
strategy.opentrades
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
strategy.opentrades.capital_held
TYPE
series float
EXAMPLE
//@version=6
strategy(
if barstate.isfirst
strategy.entry("Short", strategy.short)
// Highlight the chart background if the position is completely closed by margin calls.
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
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
strategy.wintrades
TYPE
series int
SEE ALSO
strategy.position_sizestrategy.opentradesstrategy.closedtradesstrategy.losstradesstrategy.eventr
ades
syminfo.basecurrency
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
syminfo.currencysyminfo.ticker
syminfo.country
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
syminfo.currency
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.basecurrencysyminfo.tickercurrency.USDcurrency.EUR
syminfo.description
TYPE
simple string
SEE ALSO
syminfo.tickersyminfo.prefix
syminfo.employees
TYPE
simple int
EXAMPLE
//@version=6
indicator("syminfo simple")
//@variable A table containing information about a company's employees, shareholders, and shares.
if barstate.islastconfirmedhistory
SEE ALSO
syminfo.shareholderssyminfo.shares_outstanding_floatsyminfo.shares_outstanding_total
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
syminfo.industry
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
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 syminfo.tickerid, this
variable's value does not change when used in the expression argument of
a request.*() function call.
TYPE
simple string
SEE ALSO
ticker.newtimeframe.main_periodsyminfo.tickeridsyminfo.tickertimeframe.periodtimeframe.multi
pliersyminfo.root
syminfo.mincontract
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
syminfo.minticksyminfo.pointvalue
syminfo.minmove
TYPE
simple int
SEE ALSO
ticker.newsyminfo.tickertimeframe.periodtimeframe.multipliersyminfo.root
syminfo.mintick
simple float
SEE ALSO
syminfo.pointvaluesyminfo.mincontract
syminfo.pointvalue
TYPE
simple float
SEE ALSO
syminfo.minticksyminfo.mincontract
syminfo.prefix
TYPE
simple string
EXAMPLE
//@version=6
indicator("syminfo.prefix")
if barstate.islastconfirmedhistory
SEE ALSO
syminfo.tickersyminfo.tickerid
syminfo.pricescale
simple int
SEE ALSO
ticker.newsyminfo.tickertimeframe.periodtimeframe.multipliersyminfo.root
syminfo.recommendations_buy
The number of analysts who gave the current symbol a "Buy" rating.
TYPE
series int
EXAMPLE
//@version=6
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
// Recommendation strings
SEE ALSO
syminfo.recommendations_buy_strongsyminfo.recommendations_datesyminfo.recommendation
s_holdsyminfo.recommendations_totalsyminfo.recommendations_sellsyminfo.recommendations_
sell_strong
syminfo.recommendations_buy_strong
The number of analysts who gave the current symbol a "Strong Buy" rating.
TYPE
series int
EXAMPLE
//@version=6
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
// Recommendation strings
SEE ALSO
syminfo.recommendations_buysyminfo.recommendations_datesyminfo.recommendations_holds
yminfo.recommendations_totalsyminfo.recommendations_sellsyminfo.recommendations_sell_str
ong
syminfo.recommendations_date
The starting date of the last set of recommendations for the current symbol.
TYPE
series int
EXAMPLE
//@version=6
//@variable The time value one year from the date of the last analyst recommendations.
// Recommendation strings
SEE ALSO
syminfo.recommendations_buysyminfo.recommendations_buy_strongsyminfo.recommendations
_holdsyminfo.recommendations_totalsyminfo.recommendations_sellsyminfo.recommendations_s
ell_strong
syminfo.recommendations_hold
The number of analysts who gave the current symbol a "Hold" rating.
TYPE
series int
EXAMPLE
//@version=6
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
// Recommendation strings
SEE ALSO
syminfo.recommendations_buysyminfo.recommendations_buy_strongsyminfo.recommendations
_datesyminfo.recommendations_totalsyminfo.recommendations_sellsyminfo.recommendations_s
ell_strong
syminfo.recommendations_sell
The number of analysts who gave the current symbol a "Sell" rating.
TYPE
series int
EXAMPLE
//@version=6
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
// Recommendation strings
SEE ALSO
syminfo.recommendations_buysyminfo.recommendations_buy_strongsyminfo.recommendations
_datesyminfo.recommendations_holdsyminfo.recommendations_totalsyminfo.recommendations
_sell_strong
syminfo.recommendations_sell_strong
The number of analysts who gave the current symbol a "Strong Sell" rating.
TYPE
series int
EXAMPLE
//@version=6
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
// Recommendation strings
SEE ALSO
syminfo.recommendations_buysyminfo.recommendations_buy_strongsyminfo.recommendations
_datesyminfo.recommendations_holdsyminfo.recommendations_totalsyminfo.recommendations
_sell
syminfo.recommendations_total
TYPE
series int
EXAMPLE
//@version=6
//@variable The time value one year from the date of the last analyst recommendations.
// Recommendation strings
SEE ALSO
syminfo.recommendations_buysyminfo.recommendations_buy_strongsyminfo.recommendations
_datesyminfo.recommendations_holdsyminfo.recommendations_sellsyminfo.recommendations_s
ell_strong
syminfo.root
Root for derivatives like futures contract. For other symbols returns the same value
as syminfo.ticker.
TYPE
simple string
EXAMPLE
//@version=6
indicator("syminfo.root")
// If the current chart symbol is continuous futures ('ES1!'), it would display 'ES'.
if barstate.islastconfirmedhistory
SEE ALSO
syminfo.tickersyminfo.tickerid
syminfo.sector
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
syminfo.session
TYPE
simple string
SEE ALSO
session.regularsession.extended
syminfo.shareholders
TYPE
simple int
EXAMPLE
//@version=6
indicator("syminfo simple")
//@variable A table containing information about a company's employees, shareholders, and shares.
if barstate.islastconfirmedhistory
SEE ALSO
syminfo.employeessyminfo.shares_outstanding_floatsyminfo.shares_outstanding_total
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.
if barstate.islastconfirmedhistory
SEE ALSO
syminfo.employeessyminfo.shareholderssyminfo.shares_outstanding_total
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.
if barstate.islastconfirmedhistory
SEE ALSO
syminfo.employeessyminfo.shareholderssyminfo.shares_outstanding_float
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 barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
//@variable A line connecting the current `close` to the highest yearly price estimate.
//@variable A line connecting the current `close` to the lowest yearly price estimate.
//@variable A line connecting the current `close` to the median yearly price estimate.
//@variable A line connecting the current `close` to the average yearly price estimate.
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_datesyminfo.target_price_estimatessyminfo.target_price_highsyminfo.targe
t_price_lowsyminfo.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 barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
//@variable A line connecting the current `close` to the highest yearly price estimate.
//@variable A line connecting the current `close` to the lowest yearly price estimate.
//@variable A line connecting the current `close` to the median yearly price estimate.
//@variable A line connecting the current `close` to the average yearly price estimate.
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_averagesyminfo.target_price_estimatessyminfo.target_price_highsyminfo.ta
rget_price_lowsyminfo.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 barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
//@variable A line connecting the current `close` to the highest yearly price estimate.
//@variable A line connecting the current `close` to the lowest yearly price estimate.
//@variable A line connecting the current `close` to the median yearly price estimate.
//@variable A line connecting the current `close` to the average yearly price estimate.
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_averagesyminfo.target_price_datesyminfo.target_price_highsyminfo.target_
price_lowsyminfo.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 barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
//@variable A line connecting the current `close` to the highest yearly price estimate.
//@variable A line connecting the current `close` to the lowest yearly price estimate.
//@variable A line connecting the current `close` to the median yearly price estimate.
//@variable A line connecting the current `close` to the average yearly price estimate.
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_averagesyminfo.target_price_datesyminfo.target_price_estimatessyminfo.ta
rget_price_lowsyminfo.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 barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
//@variable A line connecting the current `close` to the highest yearly price estimate.
//@variable A line connecting the current `close` to the lowest yearly price estimate.
//@variable A line connecting the current `close` to the median yearly price estimate.
//@variable A line connecting the current `close` to the average yearly price estimate.
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_averagesyminfo.target_price_datesyminfo.target_price_estimatessyminfo.ta
rget_price_highsyminfo.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 barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
//@variable A line connecting the current `close` to the highest yearly price estimate.
//@variable A line connecting the current `close` to the lowest yearly price estimate.
//@variable A line connecting the current `close` to the median yearly price estimate.
//@variable A line connecting the current `close` to the average yearly price estimate.
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_averagesyminfo.target_price_datesyminfo.target_price_estimatessyminfo.ta
rget_price_highsyminfo.target_price_low
syminfo.ticker
simple string
SEE ALSO
syminfo.tickeridtimeframe.periodtimeframe.multipliersyminfo.root
syminfo.tickerid
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 ticker.standard 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
ticker.newsyminfo.main_tickeridtimeframe.main_periodsyminfo.tickertimeframe.periodtimeframe
.multipliersyminfo.root
syminfo.timezone
Timezone of the exchange of the chart main series. Possible values see in timestamp.
TYPE
simple string
SEE ALSO
timestamp
syminfo.type
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
syminfo.ticker
syminfo.volumetype
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
syminfo.type
ta.accdist
Accumulation/distribution index.
TYPE
series float
ta.iii
TYPE
series float
EXAMPLE
//@version=6
plot(ta.iii, color=color.yellow)
f_iii() =>
plot(f_iii())
ta.nvi
TYPE
series float
EXAMPLE
//@version=6
plot(ta.nvi, color=color.yellow)
f_nvi() =>
ta_nvi := prevNvi
else
ta_nvi := (volume < nz(volume[1], 0.0)) ? prevNvi + ((close - close[1]) / close[1]) * prevNvi : prevN
vi
result = ta_nvi
plot(f_nvi())
ta.obv
On Balance Volume.
TYPE
series float
EXAMPLE
//@version=6
plot(ta.obv, color=color.yellow)
f_obv() =>
ta.cum(math.sign(ta.change(close)) * volume)
plot(f_obv())
ta.pvi
TYPE
series float
EXAMPLE
//@version=6
plot(ta.pvi, color=color.yellow)
f_pvi() =>
ta_pvi := prevPvi
else
ta_pvi := (volume > nz(volume[1], 0.0)) ? prevPvi + ((close - close[1]) / close[1]) * prevPvi : prevPvi
result = ta_pvi
plot(f_pvi())
ta.pvt
Price-Volume Trend.
TYPE
series float
EXAMPLE
//@version=6
indicator("Price-Volume Trend")
plot(ta.pvt, color=color.yellow)
f_pvt() =>
plot(f_pvt())
ta.tr
TYPE
series float
SEE ALSO
ta.trta.atr
ta.vwap
TYPE
series float
SEE ALSO
ta.vwap
ta.wad
Williams Accumulation/Distribution.
TYPE
series float
EXAMPLE
//@version=6
indicator("Williams Accumulation/Distribution")
plot(ta.wad, color=color.yellow)
f_wad() =>
mom = ta.change(close)
ta.cum(gain)
plot(f_wad())
ta.wvad
TYPE
series float
EXAMPLE
//@version=6
plot(ta.wvad, color=color.yellow)
f_wvad() =>
plot(f_wvad())
table.all
Returns an array filled with all the current tables drawn by the script.
TYPE
array<table>
EXAMPLE
//@version=6
indicator("table.all")
a_allTables = table.all
if array.size(a_allTables) > 0
for i = 0 to array.size(a_allTables) - 1
table.delete(array.get(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
table.newline.alllabel.allbox.all
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
timetime_closetimenowyearmonthweekofyeardayofmonthdayofweekhourminutesecond
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 non-standard price-
based chart types (Renko, Line break, Kagi, Point & Figure, and Range), this variable
returns na on the chart's realtime bars.
TYPE
series int
SEE ALSO
timetimenowyearmonthweekofyeardayofmonthdayofweekhourminutesecond
time_tradingday
The beginning time 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
REMARKS
The variable is useful for overnight sessions, where the current day's session can
start on the previous calendar day (e.g., on FXCM:EURUSD the Monday session will
start on Sunday, 17:00 in the exchange timezone). Unlike time, which would return
the timestamp for Sunday at 17:00 for the Monday daily bar, time_tradingday will
return the timestamp for Monday, 00:00 UTC.
When used on timeframes higher than 1D, time_tradingday returns the trading
day of the last day inside the bar (e.g. on 1W, it will return the last trading day of the
week).
SEE ALSO
timetime_close
timeframe.isdaily
TYPE
simple bool
SEE ALSO
timeframe.isdwmtimeframe.isintradaytimeframe.isminutestimeframe.issecondstimeframe.isticks
timeframe.isweeklytimeframe.ismonthly
timeframe.isdwm
TYPE
simple bool
SEE ALSO
timeframe.isintradaytimeframe.isminutestimeframe.issecondstimeframe.istickstimeframe.isdailyt
imeframe.isweeklytimeframe.ismonthly
timeframe.isintraday
TYPE
simple bool
SEE ALSO
timeframe.isminutestimeframe.issecondstimeframe.istickstimeframe.isdwmtimeframe.isdailytim
eframe.isweeklytimeframe.ismonthly
timeframe.isminutes
TYPE
simple bool
SEE ALSO
timeframe.isdwmtimeframe.isintradaytimeframe.issecondstimeframe.istickstimeframe.isdailytim
eframe.isweeklytimeframe.ismonthly
timeframe.ismonthly
TYPE
simple bool
SEE ALSO
timeframe.isdwmtimeframe.isintradaytimeframe.isminutestimeframe.issecondstimeframe.isticks
timeframe.isdailytimeframe.isweekly
timeframe.isseconds
TYPE
simple bool
SEE ALSO
timeframe.isdwmtimeframe.isintradaytimeframe.isminutestimeframe.istickstimeframe.isdailytim
eframe.isweeklytimeframe.ismonthly
timeframe.isticks
TYPE
simple bool
SEE ALSO
timeframe.isdwmtimeframe.isintradaytimeframe.isminutestimeframe.issecondstimeframe.isdaily
timeframe.isweeklytimeframe.ismonthly
timeframe.isweekly
TYPE
simple bool
SEE ALSO
timeframe.isdwmtimeframe.isintradaytimeframe.isminutestimeframe.issecondstimeframe.isticks
timeframe.isdailytimeframe.ismonthly
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 timeframe.period, 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
timeframe.periodsyminfo.main_tickeridsyminfo.tickersyminfo.tickeridtimeframe.multiplier
timeframe.multiplier
TYPE
simple int
SEE ALSO
syminfo.tickersyminfo.tickeridtimeframe.period
timeframe.period
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
timeframe.main_periodsyminfo.main_tickeridsyminfo.tickersyminfo.tickeridtimeframe.multiplier
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
timestamptimetime_closeyearmonthweekofyeardayofmonthdayofweekhourminutesecond
volume
TYPE
series float
REMARKS
Previous values may be accessed with square brackets operator [], e.g. volume[1],
volume[2].
SEE ALSO
openhighlowclosetimehl2hlc3hlcc4ohlc4askbid
weekofyear
TYPE
series int
REMARKS
Note that this variable returns the week 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 week of the trading day.
SEE ALSO
weekofyeartimeyearmonthdayofmonthdayofweekhourminutesecond
year
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
yeartimemonthweekofyeardayofmonthdayofweekhourminutesecond
Constants
adjustment.dividends
Constant for dividends adjustment type (dividends adjustment is applied).
TYPE
const string
SEE ALSO
adjustment.noneadjustment.splitsticker.new
adjustment.none
TYPE
const string
SEE ALSO
adjustment.splitsadjustment.dividendsticker.new
adjustment.splits
TYPE
const string
SEE ALSO
adjustment.noneadjustment.dividendsticker.new
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
backadjustment.inherit
const backadjustment
SEE ALSO
ticker.newticker.modifybackadjustment.onbackadjustment.off
backadjustment.off
TYPE
const backadjustment
SEE ALSO
ticker.newticker.modifybackadjustment.onbackadjustment.inherit
backadjustment.on
TYPE
const backadjustment
SEE ALSO
ticker.newticker.modifybackadjustment.inheritbackadjustment.off
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
request.securitybarmerge.gaps_on
barmerge.gaps_on
Merge strategy for requested data. Data is merged with possible gaps (na values).
TYPE
const barmerge_gaps
SEE ALSO
request.securitybarmerge.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
request.securitybarmerge.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
request.securitybarmerge.lookahead_off
color.aqua
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.gree
ncolor.limecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.orange
color.black
TYPE
const color
SEE ALSO
color.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.greencolor.lime
color.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.blue
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.gree
ncolor.limecolor.olivecolor.yellowcolor.navycolor.tealcolor.aquacolor.orange
color.fuchsia
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.greencolor.limec
olor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.gray
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.greencolor.lim
ecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.green
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.lime
color.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.lime
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.gree
ncolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.maroon
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.redcolor.purplecolor.fuchsiacolor.greencolor.limeco
lor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.navy
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.gree
ncolor.limecolor.olivecolor.yellowcolor.bluecolor.tealcolor.aquacolor.orange
color.olive
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.gree
ncolor.limecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.orange
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.gree
ncolor.limecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aqua
color.purple
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.fuchsiacolor.greencolor.limec
olor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.red
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.purplecolor.fuchsiacolor.greencolor.li
mecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.silver
TYPE
const color
SEE ALSO
color.blackcolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.greencolor.lime
color.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.teal
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.gree
ncolor.limecolor.olivecolor.yellowcolor.navycolor.bluecolor.aquacolor.orange
color.white
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.marooncolor.redcolor.purplecolor.fuchsiacolor.greencolor.lime
color.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.yellow
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.gree
ncolor.limecolor.olivecolor.navycolor.bluecolor.tealcolor.aquacolor.orange
currency.AUD
Australian dollar.
TYPE
const string
SEE ALSO
strategy
currency.BTC
Bitcoin.
TYPE
const string
SEE ALSO
strategy
currency.CAD
Canadian dollar.
TYPE
const string
SEE ALSO
strategy
currency.CHF
Swiss franc.
TYPE
const string
SEE ALSO
strategy
currency.ETH
Ethereum.
TYPE
const string
SEE ALSO
strategy
currency.EUR
Euro.
TYPE
const string
SEE ALSO
strategy
currency.GBP
Pound sterling.
TYPE
const string
SEE ALSO
strategy
currency.HKD
TYPE
const string
SEE ALSO
strategy
currency.INR
Indian rupee.
TYPE
const string
SEE ALSO
strategy
currency.JPY
Japanese yen.
TYPE
const string
SEE ALSO
strategy
currency.KRW
TYPE
const string
SEE ALSO
strategy
currency.MYR
Malaysian ringgit.
TYPE
const string
SEE ALSO
strategy
currency.NOK
Norwegian krone.
TYPE
const string
SEE ALSO
strategy
currency.NONE
Unspecified currency.
TYPE
const string
SEE ALSO
strategy
currency.NZD
TYPE
const string
SEE ALSO
strategy
currency.RUB
Russian ruble.
TYPE
const string
SEE ALSO
strategy
currency.SEK
Swedish krona.
TYPE
const string
SEE ALSO
strategy
currency.SGD
Singapore dollar.
TYPE
const string
SEE ALSO
strategy
currency.TRY
Turkish lira.
TYPE
const string
SEE ALSO
strategy
currency.USD
TYPE
const string
SEE ALSO
strategy
currency.USDT
Tether.
TYPE
const string
SEE ALSO
strategy
currency.ZAR
TYPE
const string
SEE ALSO
strategy
dayofweek.friday
TYPE
const int
SEE ALSO
dayofweek.sundaydayofweek.mondaydayofweek.tuesdaydayofweek.wednesdaydayofweek.thurs
daydayofweek.saturday
dayofweek.monday
TYPE
const int
SEE ALSO
dayofweek.sundaydayofweek.tuesdaydayofweek.wednesdaydayofweek.thursdaydayofweek.frida
ydayofweek.saturday
dayofweek.saturday
TYPE
const int
SEE ALSO
dayofweek.sundaydayofweek.mondaydayofweek.tuesdaydayofweek.wednesdaydayofweek.thurs
daydayofweek.friday
dayofweek.sunday
const int
SEE ALSO
dayofweek.mondaydayofweek.tuesdaydayofweek.wednesdaydayofweek.thursdaydayofweek.frid
aydayofweek.saturday
dayofweek.thursday
TYPE
const int
SEE ALSO
dayofweek.sundaydayofweek.mondaydayofweek.tuesdaydayofweek.wednesdaydayofweek.friday
dayofweek.saturday
dayofweek.tuesday
TYPE
const int
SEE ALSO
dayofweek.sundaydayofweek.mondaydayofweek.wednesdaydayofweek.thursdaydayofweek.frida
ydayofweek.saturday
dayofweek.wednesday
TYPE
const int
SEE ALSO
dayofweek.sundaydayofweek.mondaydayofweek.tuesdaydayofweek.thursdaydayofweek.fridayda
yofweek.saturday
display.all
TYPE
const plot_simple_display
SEE ALSO
plotplotshapeplotcharplotarrowplotbarplotcandle
display.data_window
TYPE
const plot_display
SEE ALSO
plotplotshapeplotcharplotarrowplotbarplotcandle
display.none
TYPE
const plot_simple_display
SEE ALSO
plotplotshapeplotcharplotarrowplotbarplotcandle
display.pane
A named constant for use with the display parameter of plot*() functions.
Displays plotted values in the chart pane used by the script.
TYPE
const plot_display
SEE ALSO
plotplotshapeplotcharplotarrowplotbarplotcandle
display.price_scale
A named constant for use with the display parameter of plot*() functions.
Displays the plot’s label and value on the price scale if the chart's settings allow it.
TYPE
const plot_display
SEE ALSO
plotplotshapeplotcharplotarrowplotbarplotcandle
display.status_line
TYPE
const plot_display
SEE ALSO
plotplotshapeplotcharplotarrowplotbarplotcandle
dividends.gross
const string
SEE ALSO
request.dividends
dividends.net
TYPE
const string
SEE ALSO
request.dividends
earnings.actual
A named constant for the request.earnings function. Is used to request the earnings
value as it was reported.
TYPE
const string
SEE ALSO
request.earnings
earnings.estimate
A named constant for the request.earnings function. Is used to request the estimated
earnings value.
TYPE
const string
SEE ALSO
request.earnings
earnings.standardized
TYPE
const string
SEE ALSO
request.earnings
extend.both
TYPE
const string
SEE ALSO
line.newline.set_extendextend.noneextend.leftextend.right
extend.left
TYPE
const string
SEE ALSO
line.newline.set_extendextend.noneextend.rightextend.both
extend.none
TYPE
const string
SEE ALSO
line.newline.set_extendextend.leftextend.rightextend.both
extend.right
TYPE
const string
SEE ALSO
line.newline.set_extendextend.noneextend.leftextend.both
false
REMARKS
See the User Manual for comparison operators and logical operators.
SEE ALSO
bool
font.family_default
TYPE
const string
SEE ALSO
box.newbox.set_text_font_familylabel.newlabel.set_text_font_familytable.celltable.cell_set_text_fo
nt_familyfont.family_monospace
font.family_monospace
TYPE
const string
SEE ALSO
box.newbox.set_text_font_familylabel.newlabel.set_text_font_familytable.celltable.cell_set_text_fo
nt_familyfont.family_default
format.inherit
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
indicatorformat.priceformat.volumeformat.percent
format.mintick
TYPE
const string
SEE ALSO
indicatorformat.inheritformat.priceformat.volume
format.percent
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
indicatorformat.inheritformat.priceformat.volume
format.price
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 format.price, default precision value is set. You can use the precision
argument of indicator function to change the precision value.
SEE ALSO
indicatorformat.inheritformat.volumeformat.percent
format.volume
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
indicatorformat.inheritformat.priceformat.percent
hline.style_dashed
const hline_style
SEE ALSO
hline.style_solidhline.style_dotted
hline.style_dotted
TYPE
const hline_style
SEE ALSO
hline.style_solidhline.style_dashed
hline.style_solid
TYPE
const hline_style
SEE ALSO
hline.style_dottedhline.style_dashed
label.style_arrowdown
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.sty
le_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.style_label_lower
_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightlabel.style
_label_centerlabel.style_squarelabel.style_diamond
label.style_arrowup
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowdownlabel
.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.style_label_lo
wer_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightlabel.
style_label_centerlabel.style_squarelabel.style_diamond
label.style_circle
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_arrowuplabel.style_arrowdownla
bel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.style_label
_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightlab
el.style_label_centerlabel.style_squarelabel.style_diamond
label.style_cross
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_triangleupl
abel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.style_arrowdownl
abel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.style_labe
l_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightlab
el.style_label_centerlabel.style_squarelabel.style_diamond
label.style_diamond
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.sty
le_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightl
abel.style_label_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_
upper_rightlabel.style_label_centerlabel.style_square
label.style_flag
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_circlelabel.style_arrowuplabel.style_arrowdownl
abel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.style_labe
l_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightlab
el.style_label_centerlabel.style_squarelabel.style_diamond
label.style_label_center
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.sty
le_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightl
abel.style_label_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_
upper_rightlabel.style_squarelabel.style_diamond
label.style_label_down
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.sty
le_arrowdownlabel.style_label_uplabel.style_label_leftlabel.style_label_rightlabel.style_label_lower
_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightlabel.style
_label_centerlabel.style_squarelabel.style_diamond
label.style_label_left
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.sty
le_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_rightlabel.style_label_low
er_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightlabel.st
yle_label_centerlabel.style_squarelabel.style_diamond
label.style_label_lower_left
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.sty
le_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightl
abel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightlabel.style_lab
el_centerlabel.style_squarelabel.style_diamond
label.style_label_lower_right
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.sty
le_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightl
abel.style_label_lower_leftlabel.style_label_upper_leftlabel.style_label_upper_rightlabel.style_label
_centerlabel.style_squarelabel.style_diamond
label.style_label_right
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.sty
le_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_lowe
r_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightlabel.styl
e_label_centerlabel.style_squarelabel.style_diamond
label.style_label_up
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.sty
le_arrowdownlabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.style_label_lo
wer_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightlabel.
style_label_centerlabel.style_squarelabel.style_diamond
label.style_label_upper_left
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.sty
le_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightl
abel.style_label_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_rightlabel.style_labe
l_centerlabel.style_squarelabel.style_diamond
label.style_label_upper_right
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.sty
le_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightl
abel.style_label_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_
centerlabel.style_squarelabel.style_diamond
label.style_none
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_xcrosslabel.style_crosslabel.style_triangleupl
abel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.style_arrowdownl
abel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.style_labe
l_centerlabel.style_squarelabel.style_diamond
label.style_square
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.sty
le_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightl
abel.style_label_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_
upper_rightlabel.style_label_centerlabel.style_diamond
label.style_text_outline
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.sty
le_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightl
abel.style_label_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_
upper_rightlabel.style_label_centerlabel.style_squarelabel.style_diamond
label.style_triangledown
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangleuplabel.style_flaglabel.style_circlelabel.style_arrowuplabel.style_arrowdownlabel.style
_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.style_label_lower_l
eftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightlabel.style_l
abel_centerlabel.style_squarelabel.style_diamond
label.style_triangleup
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel.s
tyle_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.style_arrowdownlabel.st
yle_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.style_label_lowe
r_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightlabel.styl
e_label_centerlabel.style_squarelabel.style_diamond
label.style_xcross
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_crosslabel.style_triangleupla
bel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.style_arrowdownla
bel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.style_label
_centerlabel.style_squarelabel.style_diamond
line.style_arrow_both
Line style for line.new and line.set_style functions. Solid line with arrows on both
points.
TYPE
const string
SEE ALSO
line.newline.set_styleline.style_solidline.style_dottedline.style_dashedline.style_arrow_leftline.style
_arrow_right
line.style_arrow_left
Line style for line.new and line.set_style functions. Solid line with arrow on the first
point.
TYPE
const string
SEE ALSO
line.newline.set_styleline.style_solidline.style_dottedline.style_dashedline.style_arrow_rightline.sty
le_arrow_both
line.style_arrow_right
Line style for line.new and line.set_style functions. Solid line with arrow on the second
point.
TYPE
const string
SEE ALSO
line.newline.set_styleline.style_solidline.style_dottedline.style_dashedline.style_arrow_leftline.style
_arrow_both
line.style_dashed
TYPE
const string
SEE ALSO
line.newline.set_styleline.style_solidline.style_dottedline.style_arrow_leftline.style_arrow_rightline.
style_arrow_both
line.style_dotted
const string
SEE ALSO
line.newline.set_styleline.style_solidline.style_dashedline.style_arrow_leftline.style_arrow_rightline
.style_arrow_both
line.style_solid
TYPE
const string
SEE ALSO
line.newline.set_styleline.style_dottedline.style_dashedline.style_arrow_leftline.style_arrow_rightli
ne.style_arrow_both
location.abovebar
Location value for plotshape, plotchar functions. Shape is plotted above main series
bars.
TYPE
const string
SEE ALSO
plotshapeplotcharlocation.belowbarlocation.toplocation.bottomlocation.absolute
location.absolute
Location value for plotshape, plotchar functions. Shape is plotted on chart using
indicator value as a price coordinate.
TYPE
const string
SEE ALSO
plotshapeplotcharlocation.abovebarlocation.belowbarlocation.toplocation.bottom
location.belowbar
Location value for plotshape, plotchar functions. Shape is plotted below main series
bars.
TYPE
const string
SEE ALSO
plotshapeplotcharlocation.abovebarlocation.toplocation.bottomlocation.absolute
location.bottom
Location value for plotshape, plotchar functions. Shape is plotted near the bottom
chart border.
TYPE
const string
SEE ALSO
plotshapeplotcharlocation.abovebarlocation.belowbarlocation.toplocation.absolute
location.top
Location value for plotshape, plotchar functions. Shape is plotted near the top chart
border.
TYPE
const string
SEE ALSO
plotshapeplotcharlocation.abovebarlocation.belowbarlocation.bottomlocation.absolute
math.e
TYPE
const float
SEE ALSO
math.phimath.pimath.rphi
math.phi
TYPE
const float
SEE ALSO
math.emath.pimath.rphi
math.pi
TYPE
const float
SEE ALSO
math.emath.phimath.rphi
math.rphi
TYPE
const float
SEE ALSO
math.emath.pimath.phi
order.ascending
Determines the sort order of the array from the smallest to the largest value.
TYPE
const sort_order
SEE ALSO
array.new_floatarray.sort
order.descending
Determines the sort order of the array from the largest to the smallest value.
TYPE
const sort_order
SEE ALSO
array.new_floatarray.sort
plot.style_area
TYPE
const plot_style
SEE ALSO
plotplot.style_steplinebrplot.style_lineplot.style_linebrplot.style_steplineplot.style_stepline_diamo
ndplot.style_histogramplot.style_areabrplot.style_crossplot.style_columnsplot.style_circles
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
plotplot.style_steplinebrplot.style_lineplot.style_linebrplot.style_steplineplot.style_stepline_diamo
ndplot.style_histogramplot.style_crossplot.style_areaplot.style_columnsplot.style_circles
plot.style_circles
const plot_style
SEE ALSO
plotplot.style_steplinebrplot.style_lineplot.style_linebrplot.style_steplineplot.style_stepline_diamo
ndplot.style_histogramplot.style_crossplot.style_areaplot.style_areabrplot.style_columns
plot.style_columns
TYPE
const plot_style
SEE ALSO
plotplot.style_steplinebrplot.style_lineplot.style_linebrplot.style_steplineplot.style_stepline_diamo
ndplot.style_histogramplot.style_crossplot.style_areaplot.style_areabrplot.style_circles
plot.style_cross
TYPE
const plot_style
SEE ALSO
plotplot.style_steplinebrplot.style_lineplot.style_linebrplot.style_steplineplot.style_stepline_diamo
ndplot.style_histogramplot.style_areaplot.style_areabrplot.style_columnsplot.style_circles
plot.style_histogram
TYPE
const plot_style
SEE ALSO
plotplot.style_steplinebrplot.style_lineplot.style_linebrplot.style_steplineplot.style_stepline_diamo
ndplot.style_crossplot.style_areaplot.style_areabrplot.style_columnsplot.style_circles
plot.style_line
TYPE
const plot_style
SEE ALSO
plotplot.style_steplinebrplot.style_linebrplot.style_steplineplot.style_stepline_diamondplot.style_hi
stogramplot.style_crossplot.style_areaplot.style_areabrplot.style_columnsplot.style_circles
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
plotplot.style_steplinebrplot.style_lineplot.style_steplineplot.style_stepline_diamondplot.style_hist
ogramplot.style_crossplot.style_areaplot.style_areabrplot.style_columnsplot.style_circles
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
plotplot.style_lineplot.style_steplinebrplot.style_stepline_diamondplot.style_linebrplot.style_histo
gramplot.style_crossplot.style_areaplot.style_areabrplot.style_columnsplot.style_circles
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
plotplot.style_steplinebrplot.style_lineplot.style_linebrplot.style_histogramplot.style_crossplot.styl
e_areaplot.style_areabrplot.style_columnsplot.style_circles
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
plotplot.style_circlesplot.style_lineplot.style_linebrplot.style_steplineplot.style_stepline_diamondpl
ot.style_histogramplot.style_crossplot.style_areaplot.style_areabrplot.style_columns
position.bottom_center
TYPE
const string
SEE ALSO
table.newtable.celltable.set_positionposition.top_leftposition.top_centerposition.top_rightpositio
n.middle_leftposition.middle_centerposition.middle_rightposition.bottom_left
position.bottom_left
TYPE
const string
SEE ALSO
table.newtable.celltable.set_positionposition.top_leftposition.top_centerposition.top_rightpositio
n.middle_leftposition.middle_centerposition.middle_rightposition.bottom_center
position.bottom_right
TYPE
const string
SEE ALSO
table.newtable.celltable.set_positionposition.top_leftposition.top_centerposition.top_rightpositio
n.middle_leftposition.middle_centerposition.middle_rightposition.bottom_leftposition.bottom_ce
nter
position.middle_center
TYPE
const string
SEE ALSO
table.newtable.celltable.set_positionposition.top_leftposition.top_centerposition.top_rightpositio
n.middle_leftposition.middle_rightposition.bottom_leftposition.bottom_center
position.middle_left
const string
SEE ALSO
table.newtable.celltable.set_positionposition.top_leftposition.top_centerposition.top_rightpositio
n.middle_centerposition.middle_rightposition.bottom_leftposition.bottom_center
position.middle_right
TYPE
const string
SEE ALSO
table.newtable.celltable.set_positionposition.top_leftposition.top_centerposition.top_rightpositio
n.middle_leftposition.middle_centerposition.bottom_leftposition.bottom_center
position.top_center
TYPE
const string
SEE ALSO
table.newtable.celltable.set_positionposition.top_leftposition.top_rightposition.middle_leftpositio
n.middle_centerposition.middle_rightposition.bottom_leftposition.bottom_center
position.top_left
TYPE
const string
SEE ALSO
table.newtable.celltable.set_positionposition.top_centerposition.top_rightposition.middle_leftposi
tion.middle_centerposition.middle_rightposition.bottom_leftposition.bottom_center
position.top_right
TYPE
const string
SEE ALSO
table.newtable.celltable.set_positionposition.top_leftposition.top_centerposition.middle_leftpositi
on.middle_centerposition.middle_rightposition.bottom_leftposition.bottom_center
scale.left
Scale value for indicator function. Indicator is added to the left price scale.
TYPE
const scale_type
SEE ALSO
indicator
scale.none
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
scale.right
Scale value for indicator function. Indicator is added to the right price scale.
TYPE
const scale_type
SEE ALSO
indicator
session.extended
TYPE
const string
SEE ALSO
session.regularsyminfo.session
session.regular
TYPE
const string
SEE ALSO
session.extendedsyminfo.session
settlement_as_close.inherit
TYPE
const settlement
SEE ALSO
ticker.newticker.modifysettlement_as_close.onsettlement_as_close.off
settlement_as_close.off
TYPE
const settlement
SEE ALSO
ticker.newticker.modifysettlement_as_close.onsettlement_as_close.inherit
settlement_as_close.on
TYPE
const settlement
SEE ALSO
ticker.newticker.modifysettlement_as_close.inheritsettlement_as_close.off
shape.arrowdown
TYPE
const string
SEE ALSO
plotshape
shape.arrowup
TYPE
const string
SEE ALSO
plotshape
shape.circle
TYPE
const string
SEE ALSO
plotshape
shape.cross
TYPE
const string
SEE ALSO
plotshape
shape.diamond
TYPE
const string
SEE ALSO
plotshape
shape.flag
TYPE
const string
SEE ALSO
plotshape
shape.labeldown
TYPE
const string
SEE ALSO
plotshape
shape.labelup
TYPE
const string
SEE ALSO
plotshape
shape.square
TYPE
const string
SEE ALSO
plotshape
shape.triangledown
TYPE
const string
SEE ALSO
plotshape
shape.triangleup
TYPE
const string
SEE ALSO
plotshape
shape.xcross
TYPE
const string
SEE ALSO
plotshape
size.auto
Size value for plotshape, plotchar functions. The size of the shape automatically
adapts to the size of the bars.
TYPE
const string
SEE ALSO
plotshapeplotcharlabel.set_sizesize.tinysize.smallsize.normalsize.largesize.huge
size.huge
Size value for plotshape, plotchar functions. The size of the shape constantly huge.
TYPE
const string
SEE ALSO
plotshapeplotcharlabel.set_sizesize.autosize.tinysize.smallsize.normalsize.large
size.large
Size value for plotshape, plotchar functions. The size of the shape constantly large.
TYPE
const string
SEE ALSO
plotshapeplotcharlabel.set_sizesize.autosize.tinysize.smallsize.normalsize.huge
size.normal
Size value for plotshape, plotchar functions. The size of the shape constantly normal.
TYPE
const string
SEE ALSO
plotshapeplotcharlabel.set_sizesize.autosize.tinysize.smallsize.largesize.huge
size.small
Size value for plotshape, plotchar functions. The size of the shape constantly small.
TYPE
const string
SEE ALSO
plotshapeplotcharlabel.set_sizesize.autosize.tinysize.normalsize.largesize.huge
size.tiny
Size value for plotshape, plotchar functions. The size of the shape constantly tiny.
TYPE
const string
SEE ALSO
plotshapeplotcharlabel.set_sizesize.autosize.smallsize.normalsize.largesize.huge
splits.denominator
A named constant for the request.splits function. Is used to request the denominator
(the number below the line in a fraction) of a splits.
TYPE
const string
SEE ALSO
request.splits
splits.numerator
A named constant for the request.splits function. Is used to request the numerator
(the number above the line in a fraction) of a splits.
TYPE
const string
SEE ALSO
request.splits
strategy.cash
TYPE
const string
EXAMPLE
//@version=6
// As ‘qty’ is not defined, the previously defined values for the `default_qty_type` and `default_qty_val
ue` parameters are used to enter trades, namely 50 units of cash in the currency of `strategy.account_cur
rency`.
// `qty` is calculated as (default_qty_value)/(close price). If current price is $5, then qty = 50/5 = 10.
strategy.entry("EN", strategy.long)
if bar_index == 2
strategy.close("EN")
SEE ALSO
strategy
strategy.commission.cash_per_contract
Commission type for an order. Money displayed in the account currency per contract.
TYPE
const string
SEE ALSO
strategy
strategy.commission.cash_per_order
Commission type for an order. Money displayed in the account currency per order.
TYPE
const string
SEE ALSO
strategy
strategy.commission.percent
TYPE
const string
SEE ALSO
strategy
strategy.direction.all
TYPE
const string
SEE ALSO
strategy.risk.allow_entry_in
strategy.direction.long
TYPE
const string
SEE ALSO
strategy.risk.allow_entry_in
strategy.direction.short
TYPE
const string
SEE ALSO
strategy.risk.allow_entry_in
strategy.fixed
TYPE
const string
EXAMPLE
//@version=6
if bar_index == 0
// As ‘qty’ is not defined, the previously defined values for the `default_qty_type` and `default_qty_val
ue` parameters are used to enter trades, namely 50 contracts.
// qty = 50
strategy.entry("EN", strategy.long)
if bar_index == 2
strategy.close("EN")
SEE ALSO
strategy
strategy.long
TYPE
const strategy_direction
SEE ALSO
strategy.entrystrategy.exitstrategy.order
strategy.oca.cancel
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 strategy.order calls with the same oca_* arguments, the strategy cannot fully
or partially cancel either one.
SEE ALSO
strategy.entrystrategy.exitstrategy.order
strategy.oca.none
TYPE
const string
SEE ALSO
strategy.entrystrategy.exitstrategy.order
strategy.oca.reduce
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 strategy.order calls with the same oca_* arguments, the strategy cannot fully
or partially cancel either one.
Orders from strategy.exit automatically use this OCA type, and they belong to the
same OCA group by default.
SEE ALSO
strategy.entrystrategy.exitstrategy.order
strategy.percent_of_equity
TYPE
const string
EXAMPLE
//@version=6
// As ‘qty’ is not defined, the previously defined values for the `default_qty_type` and `default_qty_value` p
arameters are used to enter trades, namely 100% of available equity.
if bar_index == 0
strategy.entry("EN", strategy.long)
if bar_index == 2
strategy.close("EN")
plot(strategy.equity)
// The ‘qty’ parameter is set to 10. Entering position with fixed size of 10 contracts and entry market pric
e = (10 * close).
if bar_index == 4
if bar_index == 6
strategy.close("EN")
SEE ALSO
strategy
strategy.short
TYPE
const strategy_direction
SEE ALSO
strategy.entrystrategy.exitstrategy.order
text.align_bottom
TYPE
const string
SEE ALSO
table.celltable.cell_set_text_valigntext.align_centertext.align_lefttext.align_right
text.align_center
Text alignment
for box.new, box.set_text_halign, box.set_text_valign, label.new and label.set_textalig
n functions.
TYPE
const string
SEE ALSO
label.newlabel.set_styletext.align_lefttext.align_right
text.align_left
const string
SEE ALSO
label.newlabel.set_styletext.align_centertext.align_right
text.align_right
TYPE
const string
SEE ALSO
label.newlabel.set_styletext.align_centertext.align_left
text.align_top
TYPE
const string
SEE ALSO
table.celltable.cell_set_text_valigntext.align_centertext.align_lefttext.align_right
text.format_bold
TYPE
const text_format
SEE ALSO
label.newbox.newtable.cell
text.format_italic
TYPE
const text_format
SEE ALSO
label.newbox.newtable.cell
text.format_none
TYPE
const text_format
SEE ALSO
label.newbox.newtable.cell
text.wrap_auto
TYPE
const string
SEE ALSO
box.newbox.set_textbox.set_text_wrap
text.wrap_none
TYPE
const string
SEE ALSO
box.newbox.set_textbox.set_text_wrap
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 = xloc.bar_index, the drawing object treats each
x-coordinate as a bar_index value.
TYPE
const string
SEE ALSO
xloc.bar_timeline.newlabel.newbox.newpolyline.newline.set_xloclabel.set_xloc
xloc.bar_time
A constant that specifies how functions that create and modify Pine drawings
interpret x-coordinates. If xloc = xloc.bar_time, the drawing object treats each
x-coordinate as a UNIX timestamp, expressed in milliseconds.
TYPE
const string
SEE ALSO
xloc.bar_indexline.newlabel.newbox.newpolyline.newline.set_xloclabel.set_xlocxloc.bar_index
yloc.abovebar
TYPE
const string
SEE ALSO
label.newlabel.set_ylocyloc.priceyloc.belowbar
yloc.belowbar
TYPE
const string
SEE ALSO
label.newlabel.set_ylocyloc.priceyloc.abovebar
yloc.price
TYPE
const string
SEE ALSO
label.newlabel.set_ylocyloc.abovebaryloc.belowbar
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
ma = ta.sma(close, 14)
if xUp
// Trigger the alert the first time a cross occurs during the real-time bar.
alert("Price (" + str.tostring(close) + ") crossed over MA (" + str.tostring(ma) + ").", alert.freq_once_per_
bar)
plot(ma)
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.
message (const string) Message to display when alert fires. Optional argument.
EXAMPLE
//@version=6
indicator("alertcondition", overlay=true)
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
array.abs()
2 overloads
Returns an array containing the absolute value of each element in the original array.
array.abs(id) → array<float>
array.abs(id) → array<int>
ARGUMENTS
SEE ALSO
array.new_floatarray.insertarray.slicearray.reverseorder.ascendingorder.descending
array.avg()
2 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.avg example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.avg(a))
RETURNS
SEE ALSO
array.new_floatarray.maxarray.minarray.stdev
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 = array.from(5, -2, 0, 9, 1)
array.sort(a) // [-2, 0, 1, 5, 9]
position = array.binary_search(a, 0) // 1
plot(position)
REMARKS
SEE ALSO
array.new_floatarray.insertarray.slicearray.reverseorder.ascendingorder.descending
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
EXAMPLE
//@version=6
indicator("array.binary_search_leftmost")
a = array.from(5, -2, 0, 9, 1)
array.sort(a) // [-2, 0, 1, 5, 9]
position = array.binary_search_leftmost(a, 3) // 2
plot(position)
EXAMPLE
//@version=6
a = array.from(4, 5, 5, 5)
position = array.binary_search_leftmost(a, 5)
plot(position) // Plots 1
REMARKS
SEE ALSO
array.new_floatarray.insertarray.slicearray.reverseorder.ascendingorder.descending
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 = array.from(5, -2, 0, 9, 1)
array.sort(a) // [-2, 0, 1, 5, 9]
position = array.binary_search_rightmost(a, 3) // 3
plot(position)
EXAMPLE
//@version=6
a = array.from(4, 5, 5, 5)
position = array.binary_search_rightmost(a, 5)
plot(position) // Plots 3
REMARKS
SEE ALSO
array.new_floatarray.insertarray.slicearray.reverseorder.ascendingorder.descending
array.clear()
SYNTAX
array.clear(id) → void
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.clear example")
a = array.new_float(5,high)
array.clear(a)
array.push(a, close)
plot(array.get(a,0))
plot(array.size(a))
SEE ALSO
array.new_floatarray.insertarray.pusharray.removearray.pop
array.concat()
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("array.concat example")
a = array.new_float(0,0)
b = array.new_float(0,0)
for i = 0 to 4
array.push(a, high[i])
array.push(b, low[i])
c = array.concat(a,b)
plot(array.size(a))
plot(array.size(b))
plot(array.size(c))
RETURNS
The first array with merged elements from the second array.
SEE ALSO
array.new_floatarray.insertarray.slice
array.copy()
SYNTAX
array.copy(id) → array<type>
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.copy example")
length = 5
a = array.new_float(length, close)
b = array.copy(a)
a := array.new_float(length, open)
plot(array.sum(a) / length)
plot(array.sum(b) / length)
RETURNS
A copy of an array.
SEE ALSO
array.new_floatarray.getarray.slicearray.sort
array.covariance()
SYNTAX
ARGUMENTS
biased (series bool) Determines which estimate should be used. Optional. The
default is true.
EXAMPLE
//@version=6
indicator("array.covariance example")
a = array.new_float(0)
b = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
array.push(b, open[i])
plot(array.covariance(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.
SEE ALSO
array.new_floatarray.maxarray.stdevarray.avgarray.variance
array.every()
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
array.somearray.get
array.fill()
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("array.fill example")
a = array.new_float(10)
array.fill(a, close)
plot(array.sum(a))
SEE ALSO
array.new_floatarray.setarray.slice
array.first()
Returns the array's first element. Throws a runtime error if the array is empty.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.first example")
plot(array.first(arr))
SEE ALSO
array.lastarray.get
array.from()
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.
ARGUMENTS
EXAMPLE
//@version=6
arr = array.from("Hello", "World!") // arr (array<string>) will contain 2 elements: {Hello}, {World!}.
plot(close)
RETURNS
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.
array.get()
The function returns the value of the element at the specified index.
SYNTAX
ARGUMENTS
index (series int) The index of the element whose value is to be returned.
EXAMPLE
//@version=6
indicator("array.get example")
a = array.new_float(0)
for i = 0 to 9
plot(array.get(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 array.size() - 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 array.size(). 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
array.new_floatarray.setarray.slicearray.sort
array.includes()
The function returns true if the value was found in an array, false otherwise.
SYNTAX
ARGUMENTS
value (series <type of the array's elements>) The value to search in the array.
EXAMPLE
//@version=6
indicator("array.includes example")
a = array.new_float(5,high)
p = close
if array.includes(a, high)
p := open
plot(p)
RETURNS
SEE ALSO
array.new_floatarray.indexofarray.shiftarray.removearray.insert
array.indexof()
The function returns the index of the first occurrence of the value, or -1 if the value is
not found.
SYNTAX
value (series <type of the array's elements>) The value to search in the array.
EXAMPLE
//@version=6
indicator("array.indexof example")
a = array.new_float(5,high)
plot(index)
RETURNS
SEE ALSO
array.lastindexofarray.getarray.lastindexofarray.removearray.insert
array.insert()
The function changes the contents of an array by adding new elements in place.
SYNTAX
ARGUMENTS
value (series <type of the array's elements>) The value to add to the array.
EXAMPLE
//@version=6
indicator("array.insert example")
a = array.new_float(5, close)
array.insert(a, 0, open)
plot(array.get(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 array.size() - 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 array.size(). 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
array.new_floatarray.setarray.pusharray.removearray.poparray.unshift
array.join()
The function creates and returns a new string by concatenating all the elements of an
array, separated by the specified separator string.
SYNTAX
ARGUMENTS
separator (series string) The string used to separate each array element.
EXAMPLE
//@version=6
indicator("array.join example")
a = array.new_float(5, 5)
SEE ALSO
array.new_floatarray.setarray.insertarray.removearray.poparray.unshift
array.last()
Returns the array's last element. Throws a runtime error if the array is empty.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.last example")
plot(array.last(arr))
SEE ALSO
array.firstarray.get
array.lastindexof()
The function returns the index of the last occurrence of the value, or -1 if the value is
not found.
SYNTAX
ARGUMENTS
value (series <type of the array's elements>) The value to search in the array.
EXAMPLE
//@version=6
indicator("array.lastindexof example")
a = array.new_float(5,high)
plot(index)
RETURNS
The index of an element.
SEE ALSO
array.new_floatarray.setarray.pusharray.removearray.insert
array.max()
4 overloads
The function returns the greatest value, or the nth greatest value in a given array.
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.max")
a = array.from(5, -2, 0, 9, 1)
thirdHighest = array.max(a, 2) // 1
plot(thirdHighest)
RETURNS
SEE ALSO
array.new_floatarray.minarray.sum
array.median()
2 overloads
The function returns the median of an array's elements.
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.median example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.median(a))
RETURNS
SEE ALSO
array.medianarray.avgarray.variancearray.min
array.min()
4 overloads
The function returns the smallest value, or the nth smallest value in a given array.
EXAMPLE
//@version=6
indicator("array.min")
a = array.from(5, -2, 0, 9, 1)
secondLowest = array.min(a, 1) // 0
plot(secondLowest)
RETURNS
SEE ALSO
array.new_floatarray.maxarray.sum
array.mode()
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("array.mode example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.mode(a))
RETURNS
The most frequently occurring value from the id array. If none exists, returns the
smallest value instead.
SEE ALSO
array.new_floatta.modematrix.modearray.avgarray.variancearray.min
array.new_bool()
SYNTAX
ARGUMENTS
initial_value (series bool) Initial value of all array elements. Optional. The default is
'false'.
EXAMPLE
//@version=6
indicator("array.new_bool example")
length = 5
RETURNS
REMARKS
SEE ALSO
array.new_floatarray.getarray.slicearray.sort
array.new_box()
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()
plot(1)
RETURNS
REMARKS
SEE ALSO
array.new_floatarray.getarray.slice
array.new_color()
SYNTAX
initial_value (series color) Initial value of all array elements. Optional. The default is
'na'.
EXAMPLE
//@version=6
indicator("array.new_color example")
length = 5
a = array.new_color(length, color.red)
RETURNS
REMARKS
SEE ALSO
array.new_floatarray.getarray.slicearray.sort
array.new_float()
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(array.sum(a) / length)
RETURNS
REMARKS
SEE ALSO
array.new_colorarray.new_boolarray.getarray.slicearray.sort
array.new_int()
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(array.sum(a) / length)
RETURNS
The ID of an array object which may be used in other array.*() functions.
REMARKS
SEE ALSO
array.new_floatarray.getarray.slicearray.sort
array.new_label()
SYNTAX
ARGUMENTS
initial_value (series label) Initial value of all array elements. Optional. The default is
'na'.
EXAMPLE
//@version=6
string labelText = na
color labelColor = na
string labelStyle = na
// Set the label attributes for rising bars.
labelText := "Rising"
labelColor := color.green
labelStyle := label.style_label_down
labelText := "Falling"
labelColor := color.red
labelStyle := label.style_label_up
// Add a new label to the `labelArray` when the chart bar closed at a new value.
if close != open
// Remove the first element and delete its label when the size of the `labelArray` exceeds the `labelCount`.
label.delete(labelArray.shift())
RETURNS
REMARKS
SEE ALSO
array.new_floatarray.getarray.slice
array.new_line()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.new_line example")
var a = array.new_line()
if array.size(a) > 15
ln = array.shift(a)
line.delete(ln)
RETURNS
REMARKS
SEE ALSO
array.new_floatarray.getarray.slice
array.new_linefill()
SYNTAX
ARGUMENTS
RETURNS
array.new_string()
SYNTAX
ARGUMENTS
initial_value (series string) Initial value of all array elements. Optional. The default is
'na'.
EXAMPLE
//@version=6
indicator("array.new_string example")
length = 5
a = array.new_string(length, "text")
RETURNS
REMARKS
SEE ALSO
array.new_floatarray.getarray.slice
array.new_table()
SYNTAX
array.new_table(size, initial_value) → array<table>
ARGUMENTS
initial_value (series table) Initial value of all array elements. Optional. The default is
'na'.
EXAMPLE
//@version=6
indicator("table array")
tables = array.new_table()
plot(1)
RETURNS
REMARKS
SEE ALSO
array.new_floatarray.getarray.slice
array.new<type>()
SYNTAX
ARGUMENTS
initial_value (<array_type>) Initial value of all array elements. Optional. The default
is 'na'.
EXAMPLE
//@version=6
indicator("array.new<string> example")
EXAMPLE
//@version=6
indicator("array.new<color> example")
a = array.new<color>()
array.push(a, color.red)
array.push(a, color.green)
EXAMPLE
//@version=6
indicator("array.new<float> example")
length = 5
if array.size(a) == length
array.remove(a, 0)
array.push(a, close)
EXAMPLE
//@version=6
indicator("array.new<line> example")
var a = array.new<line>()
if array.size(a) > 15
ln = array.shift(a)
line.delete(ln)
RETURNS
If you want to initialize an array and specify all its elements at the same time, then
use the function array.from.
SEE ALSO
array.fromarray.pusharray.getarray.sizearray.removearray.shiftarray.sum
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 you're measuring. Linear
interpolation estimates the value between two ranks.
SEE ALSO
array.new_floatarray.insertarray.slicearray.reverseorder.ascendingorder.descending
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
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 you're measuring.
SEE ALSO
array.new_floatarray.insertarray.slicearray.reverseorder.ascendingorder.descending
array.percentrank()
2 overloads
ARGUMENTS
index (series int) The index of the element for which the percentile rank should be
calculated.
REMARKS
Percentile rank is the percentage of how many elements in the array are less than or
equal to the reference value.
SEE ALSO
array.new_floatarray.insertarray.slicearray.reverseorder.ascendingorder.descending
array.pop()
The function removes the last element from an array and returns its value.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.pop example")
a = array.new_float(5,high)
removedEl = array.pop(a)
plot(array.size(a))
plot(removedEl)
RETURNS
SEE ALSO
array.new_floatarray.setarray.pusharray.removearray.insertarray.shift
array.push()
SYNTAX
value (series <type of the array's elements>) The value of the element added to
the end of the array.
EXAMPLE
//@version=6
indicator("array.push example")
a = array.new_float(5, 0)
array.push(a, open)
plot(array.get(a, 5))
SEE ALSO
array.new_floatarray.setarray.insertarray.removearray.poparray.unshift
array.range()
2 overloads
The function returns the difference between the min and max values from a given
array.
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.range example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.range(a))
RETURNS
The difference between the min and max values in the array.
SEE ALSO
array.new_floatarray.minarray.maxarray.sum
array.remove()
The function changes the contents of an array by removing the element with the
specified index.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.remove example")
a = array.new_float(5,high)
removedEl = array.remove(a, 0)
plot(array.size(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 array.size() - 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 array.size(). 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
array.new_floatarray.setarray.pusharray.insertarray.poparray.shift
array.reverse()
The function reverses an array. The first array element becomes the last, and the last
array element becomes the first.
SYNTAX
array.reverse(id) → void
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.reverse example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.get(a, 0))
array.reverse(a)
plot(array.get(a, 0))
SEE ALSO
array.new_floatarray.sortarray.pusharray.setarray.avg
array.set()
The function sets the value of the element at the specified index.
SYNTAX
ARGUMENTS
id (any array type) An array object.
value (series <type of the array's elements>) The new value to be set.
EXAMPLE
//@version=6
indicator("array.set example")
a = array.new_float(10)
for i = 0 to 9
array.set(a, i, close[i])
plot(array.sum(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 array.size() - 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 array.size(). 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
array.new_floatarray.getarray.slice
array.shift()
The function removes an array's first element and returns its value.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.shift example")
a = array.new_float(5,high)
removedEl = array.shift(a)
plot(array.size(a))
plot(removedEl)
RETURNS
SEE ALSO
array.unshiftarray.setarray.pusharray.removearray.includes
array.size()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.size example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
slice = array.slice(a, 0, 5)
array.push(slice, open)
plot(array.size(a))
plot(array.size(slice))
RETURNS
The number of elements in the array.
SEE ALSO
array.new_floatarray.sumarray.slicearray.sort
array.slice()
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("array.slice example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
slice = array.slice(a, 0, 5)
plot(array.sum(a) / 10)
plot(array.sum(slice) / 5)
RETURNS
SEE ALSO
array.new_floatarray.getarray.slicearray.sort
array.some()
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
array.everyarray.get
array.sort()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.sort example")
a = array.new_float(0,0)
for i = 0 to 5
array.push(a, high[i])
array.sort(a, order.descending)
if barstate.islast
SEE ALSO
array.new_floatarray.insertarray.slicearray.reverseorder.ascendingorder.descending
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 = array.from(5, -2, 0, 9, 1)
indexOfSmallestValue = array.get(sortedIndices, 0) // 1
plot(smallestValue)
SEE ALSO
array.new_floatarray.insertarray.slicearray.reverseorder.ascendingorder.descending
array.standardize()
2 overloads
array.standardize(id) → array<float>
array.standardize(id) → array<int>
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.standardize example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
b = array.standardize(a)
plot(array.min(b))
plot(array.max(b))
RETURNS
SEE ALSO
array.maxarray.minarray.modearray.avgarray.variancearray.stdev
array.stdev()
2 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.stdev example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.stdev(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.
SEE ALSO
array.new_floatarray.maxarray.minarray.avg
array.sum()
2 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.sum example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.sum(a))
RETURNS
SEE ALSO
array.new_floatarray.maxarray.min
array.unshift()
SYNTAX
ARGUMENTS
value (series <type of the array's elements>) The value to add to the start of the
array.
EXAMPLE
//@version=6
indicator("array.unshift example")
a = array.new_float(5, 0)
array.unshift(a, open)
plot(array.get(a, 0))
SEE ALSO
array.shiftarray.setarray.insertarray.removearray.indexof
array.variance()
2 overloads
The function returns the variance of an array's elements.
ARGUMENTS
biased (series bool) Determines which estimate should be used. Optional. The
default is true.
EXAMPLE
//@version=6
indicator("array.variance example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.variance(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.
SEE ALSO
array.new_floatarray.stdevarray.minarray.avgarray.covariance
barcolor()
SYNTAX
barcolor(color, offset, editable, show_last, title, display) → void
ARGUMENTS
color (series color) Color of bars. You can use constants like 'red' or '#ff001a' as well
as complex expressions like 'close >= open ? color.green : color.red'. 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
SEE ALSO
bgcolorplotfill
bgcolor()
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 ? color.green : color.red'.
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.
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
SEE ALSO
barcolorplotfill
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.
x (simple int/float/bool) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
floatintcolorstringlinelabel
box()
Casts na to box.
SYNTAX
ARGUMENTS
x (series box) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
floatintboolcolorstringlinelabel
box.copy()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
LOOKBACK = 50
highest = ta.highest(LOOKBACK)
lowest = ta.lowest(LOOKBACK)
if barstate.islastconfirmedhistory
SEE ALSO
box.newbox.delete
box.delete()
Deletes the specified box object. If it has already been deleted, does nothing.
SYNTAX
box.delete(id) → void
ARGUMENTS
SEE ALSO
box.new
box.get_bottom()
SYNTAX
ARGUMENTS
id (series box) A box object.
RETURNS
SEE ALSO
box.newbox.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
box.newbox.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
SEE ALSO
box.newbox.set_right
box.get_top()
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
box.newbox.set_top
box.new()
2 overloads
box.new(left, top, right, bottom, 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
ARGUMENTS
top_left (chart.point) A chart.point object that specifies the top-left corner location
of the box.
border_color (series color) Color of the four borders. Optional. The default
is color.blue.
border_width (series int) Width of the four borders, in pixels. Optional. The default
is 1 pixel.
extend (series string) When extend.none is used, the horizontal borders start at the
left border and end at the right border. With extend.left or extend.right, the
horizontal borders are extended indefinitely to the left or right of the box,
respectively. With extend.both, the horizontal borders are extended on both sides.
Optional. The default value is extend.none.
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 color.blue.
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 size.* built-in constant strings. The constant strings
and their equivalent integer values
are: size.auto (0), size.tiny (8), size.small (10), size.normal (14), size.large (20), size.hug
e (36). The default value is size.auto or 0.
text_color (series color) The color of the text. Optional. The default is color.black.
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.
EXAMPLE
//@version=6
indicator("box.new")
box.set_bgcolor(b, color.green)
RETURNS
The ID of a box object which may be used in box.set_*() and box.get_*() functions.
SEE ALSO
box.deletebox.get_leftbox.get_topbox.get_rightbox.get_bottombox.set_top_left_pointbox.set_left
box.set_topbox.set_bottom_right_pointbox.set_rightbox.set_bottombox.set_border_colorbox.set_
bgcolorbox.set_border_widthbox.set_border_stylebox.set_extendbox.set_textbox.set_text_formatt
ing
box.set_bgcolor()
SYNTAX
ARGUMENTS
SEE ALSO
box.new
box.set_border_color()
SYNTAX
ARGUMENTS
SEE ALSO
box.new
box.set_border_style()
SYNTAX
box.set_border_style(id, style) → void
ARGUMENTS
SEE ALSO
box.newline.style_solid
box.set_border_width()
SYNTAX
ARGUMENTS
SEE ALSO
box.new
box.set_bottom()
SYNTAX
ARGUMENTS
SEE ALSO
box.newbox.get_bottom
box.set_bottom_right_point()
SYNTAX
ARGUMENTS
box.set_extend()
Sets extending type of the border of this box object. When extend.none is used, the
horizontal borders start at the left border and end at the right border.
With extend.left or extend.right, the horizontal borders are extended indefinitely to
the left or right of the box, respectively. With extend.both, the horizontal borders are
extended on both sides.
SYNTAX
ARGUMENTS
SEE ALSO
box.newextend.none
box.set_left()
SYNTAX
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
box.newbox.get_left
box.set_lefttop()
SYNTAX
ARGUMENTS
left (series int) Bar index or bar time of the left border.
SEE ALSO
box.newbox.get_leftbox.get_top
box.set_right()
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
box.newbox.get_right
box.set_rightbottom()
SYNTAX
ARGUMENTS
right (series int) Bar index or bar time of the right border.
SEE ALSO
box.newbox.get_rightbox.get_bottom
box.set_text()
SYNTAX
ARGUMENTS
SEE ALSO
box.set_text_colorbox.set_text_sizebox.set_text_valignbox.set_text_halignbox.set_text_formatting
box.set_text_color()
The function sets the color of the text inside the box.
SYNTAX
box.set_text_color(id, text_color) → void
ARGUMENTS
SEE ALSO
box.set_textbox.set_text_sizebox.set_text_valignbox.set_text_halign
box.set_text_font_family()
The function sets the font family of the text inside the box.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
if barstate.islastconfirmedhistory
box.set_text_font_family(b, font.family_monospace)
SEE ALSO
box.newfont.family_defaultfont.family_monospace
box.set_text_formatting()
SYNTAX
box.set_text_formatting(id, text_formatting) → void
ARGUMENTS
SEE ALSO
box.set_text_colorbox.set_text_sizebox.set_text_valignbox.set_text_halignbox.set_text
box.set_text_halign()
SYNTAX
ARGUMENTS
SEE ALSO
box.set_textbox.set_text_sizebox.set_text_valignbox.set_text_color
box.set_text_size()
SYNTAX
ARGUMENTS
SEE ALSO
box.set_textbox.set_text_colorbox.set_text_valignbox.set_text_halign
box.set_text_valign()
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_textbox.set_text_sizebox.set_text_colorbox.set_text_halign
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_textbox.set_text_sizebox.set_text_valignbox.set_text_halignbox.set_text_color
box.set_top()
SYNTAX
ARGUMENTS
SEE ALSO
box.newbox.get_top
box.set_top_left_point()
SYNTAX
ARGUMENTS
chart.point.copy()
SYNTAX
chart.point.copy(id) → chart.point
ARGUMENTS
chart.point.from_index()
Returns a chart.point object with index as its x-coordinate and price as its y-
coordinate.
SYNTAX
ARGUMENTS
index (series int) The x-coordinate of the point, expressed as a bar index value.
REMARKS
The time field values of chart.point instances returned from this function will be na,
meaning drawing objects with xloc values set to xloc.bar_time will not work with
them.
chart.point.from_time()
Returns a chart.point 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 chart.point instances returned from this function will be na,
meaning drawing objects with xloc values set to xloc.bar_index will not work
with them.
chart.point.new()
Creates a new chart.point 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
It's important to note that this function does not verify that
the time and index values refer to the same bar.
SEE ALSO
polyline.new
chart.point.now()
SYNTAX
chart.point.now(price) → chart.point
ARGUMENTS
price (series int/float) The y-coordinate of the point. Optional. The default is close.
REMARKS
The chart.point 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
floatintboolstringlinelabel
color.b()
4 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("color.b", overlay=true)
plot(color.b(color.blue))
RETURNS
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, color.yellow, color.lime)
plot(close, color=color1)
plot(ta.rsi(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(color.green))
RETURNS
ARGUMENTS
transp (const int/float) Possible values are from 0 (not transparent) to 100
(invisible).
EXAMPLE
//@version=6
indicator("color.new", overlay=true)
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
EXAMPLE
//@version=6
indicator("color.r", overlay=true)
plot(color.r(color.red))
RETURNS
color.rgb()
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("color.rgb", overlay=true)
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(color.new(color.red, 50)))
RETURNS
dayofmonth()
2 overloads
ARGUMENTS
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 day 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 day of the trading day.
SEE ALSO
dayofmonthtimeyearmonthdayofweekhourminutesecond
dayofweek()
2 overloads
ARGUMENTS
RETURNS
REMARKS
Note that this function returns the day 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 day of the trading day.
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1
January 1970.
SEE ALSO
dayofweektimeyearmonthdayofmonthhourminutesecond
fill()
3 overloads
fill(plot1, plot2, top_value, bottom_value, top_color, bottom_color, title, display, fillgaps, editable) → void
ARGUMENTS
title (const string) Title of the created fill object. Optional argument.
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.
EXAMPLE
//@version=6
h1 = hline(20)
h2 = hline(10)
EXAMPLE
//@version=6
p1 = plot(open)
p2 = plot(close)
EXAMPLE
//@version=6
topVal = input.int(100)
botVal = input.int(0)
topCol = input.color(color.red)
botCol = input.color(color.blue)
SEE ALSO
plotbarcolorbgcolorhlinecolor.new
fixnan()
3 overloads
For a given series replaces NaN values with previous nearest non-NaN value.
ARGUMENTS
RETURNS
SEE ALSO
nananz
float()
4 overloads
Casts na to float
ARGUMENTS
x (const int/float) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
intboolcolorstringlinelabel
hline()
SYNTAX
ARGUMENTS
price (input int/float) Price value at which the object will be rendered. Required
argument.
color (input color) Color of the rendered line. Must be a constant value (not an
expression). Optional argument.
EXAMPLE
//@version=6
indicator("input.hline", overlay=true)
// You may fill the background between any two hlines with a fill() function:
h1 = hline(20)
h2 = hline(10)
RETURNS
SEE ALSO
fill
hour()
2 overloads
ARGUMENTS
RETURNS
REMARKS
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1
January 1970.
SEE ALSO
hourtimeyearmonthdayofmonthdayofweekminutesecond
indicator()
This declaration statement designates the script as an indicator and sets a number of
indicator-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 indicator will be displayed over the chart. If false, it
will be added in a separate pane. Optional. The default is false.
format (const string) Specifies the formatting of the script's displayed values.
Possible values: format.inherit, format.price, format.volume, format.percent.
Optional. The default is format.inherit.
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 format.inherit and precision is specified, the format will instead
be set to format.price. When the function's format parameter uses format.volume,
the precision parameter will not affect the result, as the decimal precision rules
defined by format.volume 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: scale.right, scale.left, scale.none. The scale.none value can only be applied in
combination with overlay = true. Optional. By default, the script uses the same
scale as the chart.
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.
timeframe_gaps (const bool) Specifies how the indicator's values are displayed on
chart bars when the timeframe is higher than the chart's. If true, a value only
appears on a chart bar when the higher timeframe value becomes available,
otherwise na is returned (thus a "gap" occurs). With false, what would otherwise be
gaps are filled with the latest known value returned, avoiding na values. When
specified, a "Wait for timeframe closes" checkbox will be included in the "Calculation"
section of the script's "Settings/Inputs" tab. Optional. The default is true.
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. The count is approximate; more drawings than the specified count may
be displayed. Optional. The default is 50.
max_labels_count (const int) The number of last label drawings displayed. Possible
values: 1-500. The count is approximate; more drawings than the specified count may
be displayed. Optional. The default is 50.
max_boxes_count (const int) The number of last box drawings displayed. Possible
values: 1-500. The count is approximate; more drawings than the specified count may
be displayed. 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.
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) Controls whether the script's plots and drawings in the
main chart pane appear behind the chart display (if true), or in front of it (if false).
Optional. The default is true.
EXAMPLE
//@version=6
plot(close)
REMARKS
SEE ALSO
strategylibrary
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
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: display.none, display.data_window, display.status_line, display.all. Optional.
The default depends on the type of the value passed
to defval: display.none for bool and color values, display.all for everything else.
EXAMPLE
//@version=6
indicator("input", overlay=true)
plot(ta.sma(i_src, i_len))
hline(i_border)
plot(close, color=i_col)
label.delete(l[1])
RETURNS
REMARKS
Result of input function always should be assigned to a variable, see examples above.
SEE ALSO
input.boolinput.colorinput.intinput.floatinput.stringinput.symbolinput.timeframeinput.text_areai
nput.sessioninput.sourceinput.time
input.bool()
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
input.bool(defval, title, tooltip, inline, group, confirm, display) → 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: display.none, display.data_window, display.status_line, display.all. Optional.
The default is display.none.
EXAMPLE
//@version=6
indicator("input.bool", overlay=true)
RETURNS
REMARKS
Result of input.bool function always should be assigned to a variable, see examples
above.
SEE ALSO
input.intinput.floatinput.stringinput.text_areainput.symbolinput.timeframeinput.sessioninput.sou
rceinput.colorinput.timeinput
input.color()
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
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: display.none, display.data_window, display.status_line, display.all. Optional.
The default is display.none.
EXAMPLE
//@version=6
indicator("input.color", overlay=true)
plot(close, color=i_col)
RETURNS
REMARKS
SEE ALSO
input.boolinput.intinput.floatinput.stringinput.text_areainput.symbolinput.timeframeinput.sessio
ninput.sourceinput.timeinput
input.enum()
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
input.enum(defval, title, options, tooltip, inline, group, confirm, display) → 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.
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: display.none, display.data_window, display.status_line, display.all. Optional.
The default is display.all.
EXAMPLE
//@version=6
//@field exch Has an empty string as the title to represent the chart timezone.
enum tz
utc = "UTC"
exch = ""
ny = "America/New_York"
chi = "America/Chicago"
lon = "Europe/London"
tok = "Asia/Tokyo"
//@variable The session string.
//@variable The selected timezone. The input's dropdown contains the fields in the `tz` enum.
inSession := true
RETURNS
REMARKS
All fields included in the defval and options arguments must belong to the same
enum.
SEE ALSO
input.text_areainput.boolinput.intinput.floatinput.symbolinput.timeframeinput.sessioninput.sour
ceinput.colorinput.timeinput
input.float()
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.
input.float(defval, title, options, tooltip, inline, group, confirm, display) → input float
input.float(defval, title, minval, maxval, step, tooltip, inline, group, confirm, display) → 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, maxval 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: display.none, display.data_window, display.status_line, display.all. Optional.
The default is display.all.
EXAMPLE
//@version=6
indicator("input.float", overlay=true)
RETURNS
Value of input variable.
REMARKS
SEE ALSO
input.boolinput.intinput.stringinput.text_areainput.symbolinput.timeframeinput.sessioninput.sou
rceinput.colorinput.timeinput
input.int()
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.
input.int(defval, title, options, tooltip, inline, group, confirm, display) → input int
input.int(defval, title, minval, maxval, step, tooltip, inline, group, confirm, display) → input int
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 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: display.none, display.data_window, display.status_line, display.all. Optional.
The default is display.all.
EXAMPLE
//@version=6
indicator("input.int", overlay=true)
plot(ta.sma(close, i_len1))
plot(ta.sma(close, i_len2))
RETURNS
REMARKS
SEE ALSO
input.boolinput.floatinput.stringinput.text_areainput.symbolinput.timeframeinput.sessioninput.s
ourceinput.colorinput.timeinput
input.price()
SYNTAX
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) If true, the interactive input mode is enabled and the selection
is done by clicking on the chart when the indicator is added to the chart, or by
selecting the indicator and moving the selection after that. Optional. 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: display.none, display.data_window, display.status_line, display.all. Optional.
The default is display.all.
EXAMPLE
//@version=6
indicator("input.price", overlay=true)
plot(price1)
plot(price2)
RETURNS
REMARKS
When using interactive mode, a time input can be combined with a price input if both
function calls use the same argument for their inline parameter.
SEE ALSO
input.boolinput.intinput.floatinput.stringinput.text_areainput.symbolinput.resolutioninput.sessio
ninput.sourceinput.colorinput
input.session()
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
input.session(defval, title, options, tooltip, inline, group, confirm, display) → 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: display.none, display.data_window, display.status_line, display.all. Optional.
The default is display.all.
EXAMPLE
//@version=6
indicator("input.session", overlay=true)
t = time(timeframe.period, i_sess)
RETURNS
REMARKS
SEE ALSO
input.boolinput.intinput.floatinput.stringinput.text_areainput.symbolinput.timeframeinput.source
input.colorinput.timeinput
input.source()
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
ARGUMENTS
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: display.none, display.data_window, display.status_line, display.all. Optional.
The default is display.all.
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("input.source", overlay=true)
plot(i_src)
RETURNS
REMARKS
SEE ALSO
input.boolinput.intinput.floatinput.stringinput.text_areainput.symbolinput.timeframeinput.sessio
ninput.colorinput.timeinput
input.string()
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
input.string(defval, title, options, tooltip, inline, group, confirm, display) → 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: display.none, display.data_window, display.status_line, display.all. Optional.
The default is display.all.
EXAMPLE
//@version=6
indicator("input.string", overlay=true)
label.delete(l[1])
RETURNS
REMARKS
SEE ALSO
input.text_areainput.boolinput.intinput.floatinput.symbolinput.timeframeinput.sessioninput.sour
ceinput.colorinput.timeinput
input.symbol()
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
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: display.none, display.data_window, display.status_line, display.all. Optional.
The default is display.all.
EXAMPLE
//@version=6
indicator("input.symbol", overlay=true)
plot(s)
RETURNS
REMARKS
SEE ALSO
input.boolinput.intinput.floatinput.stringinput.text_areainput.timeframeinput.sessioninput.sourc
einput.colorinput.timeinput
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: display.none, display.data_window, display.status_line, display.all. Optional.
The default is display.none.
EXAMPLE
//@version=6
indicator("input.text_area")
plot(close)
RETURNS
REMARKS
SEE ALSO
input.stringinput.boolinput.intinput.floatinput.symbolinput.timeframeinput.sessioninput.sourcei
nput.colorinput.timeinput
input.time()
Adds a time input to the script's "Settings/Inputs" tab. This function adds two input
widgets on the same line: one for the date and one for the time. The function returns
a date/time value in UNIX format. Using confirm = true activates the interactive
input mode where a point in time is selected by clicking on the chart.
SYNTAX
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) If true, the interactive input mode is enabled and the selection
is done by clicking on the chart when the indicator is added to the chart, or by
selecting the indicator and moving the selection after that. Optional. 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: display.none, display.data_window, display.status_line, display.all. Optional.
The default is display.none.
EXAMPLE
//@version=6
indicator("input.time", overlay=true)
label.delete(l[1])
RETURNS
REMARKS
When using interactive mode, a price input can be combined with a time input if both
function calls use the same argument for their inline parameter.
SEE ALSO
input.boolinput.intinput.floatinput.stringinput.text_areainput.symbolinput.timeframeinput.sessio
ninput.sourceinput.colorinput
input.timeframe()
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
input.timeframe(defval, title, options, tooltip, inline, group, confirm, display) → 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: display.none, display.data_window, display.status_line, display.all. Optional.
The default is display.all.
EXAMPLE
//@version=6
indicator("input.timeframe", overlay=true)
plot(s)
RETURNS
REMARKS
SEE ALSO
input.boolinput.intinput.floatinput.stringinput.text_areainput.symbolinput.sessioninput.sourcein
put.colorinput.timeinput
int()
4 overloads
ARGUMENTS
x (const int/float) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
floatboolcolorstringlinelabel
label()
Casts na to label
SYNTAX
ARGUMENTS
x (series label) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
floatintboolcolorstringline
label.copy()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator('Last 100 bars highest/lowest', overlay = true)
LOOKBACK = 100
highest = ta.highest(LOOKBACK)
highestBars = ta.highestbars(LOOKBACK)
lowest = ta.lowest(LOOKBACK)
lowestBars = ta.lowestbars(LOOKBACK)
if barstate.islastconfirmedhistory
label.set_text(labelLow, str.tostring(lowest))
label.set_color(labelLow, color.red)
label.set_style(labelLow, label.style_label_up)
RETURNS
New label ID object which may be passed to label.setXXX and label.getXXX functions.
SEE ALSO
label.newlabel.delete
label.delete()
Deletes the specified label object. If it has already been deleted, does nothing.
SYNTAX
label.delete(id) → void
ARGUMENTS
SEE ALSO
label.new
label.get_text()
SYNTAX
label.get_text(id) → series string
ARGUMENTS
EXAMPLE
//@version=6
indicator("label.get_text")
a = label.get_text(my_label)
RETURNS
SEE ALSO
label.new
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")
a = label.get_x(my_label)
SEE ALSO
label.new
label.get_y()
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
label.new
label.new()
2 overloads
label.new(point, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family,
force_overlay, text_formatting) → series label
label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family, force_overlay,
text_formatting) → series label
ARGUMENTS
size (series int/string) Optional. 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: size.auto (0), size.tiny (~7), size.small (~10), size.normal (12), size.large (18), size.h
uge (24). The default value is size.normal, which represents the numeric size of 12.
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.
EXAMPLE
//@version=6
indicator("label.new")
label.set_x(label1, 0)
label.set_color(label1, color.red)
label.set_size(label1, size.large)
RETURNS
SEE ALSO
label.deletelabel.set_xlabel.set_ylabel.set_xylabel.set_xloclabel.set_yloclabel.set_colorlabel.set_tex
tcolorlabel.set_stylelabel.set_sizelabel.set_textalignlabel.set_tooltiplabel.set_textlabel.set_text_for
matting
label.set_color()
SYNTAX
ARGUMENTS
SEE ALSO
label.new
label.set_point()
ARGUMENTS
label.set_size()
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: size.auto (0), size.tiny (~7), size.small (~10), size.normal (12), size.large (18), size.h
uge (24). The default value is size.normal, which represents the numeric size of 12.
SEE ALSO
size.autosize.tinysize.smallsize.normalsize.largesize.hugelabel.new
label.set_style()
SYNTAX
ARGUMENTS
SEE ALSO
label.new
label.set_text()
SYNTAX
ARGUMENTS
SEE ALSO
label.newlabel.set_text_formatting
label.set_text_font_family()
The function sets the font family of the text inside the label.
SYNTAX
ARGUMENTS
//@version=6
if barstate.islastconfirmedhistory
label.set_text_font_family(l, font.family_monospace)
SEE ALSO
label.newfont.family_defaultfont.family_monospace
label.set_text_formatting()
SYNTAX
ARGUMENTS
SEE ALSO
label.newlabel.set_text
label.set_textalign()
SYNTAX
ARGUMENTS
SEE ALSO
text.align_lefttext.align_centertext.align_rightlabel.new
label.set_textcolor()
SYNTAX
ARGUMENTS
SEE ALSO
label.new
label.set_tooltip()
SYNTAX
ARGUMENTS
SEE ALSO
label.new
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
label.new
label.set_xloc()
SYNTAX
ARGUMENTS
x (series int) New bar index or bar time of the label position.
SEE ALSO
xloc.bar_indexxloc.bar_timelabel.new
label.set_xy()
SYNTAX
label.set_xy(id, x, y) → void
ARGUMENTS
id (series label) Label object.
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
label.new
label.set_y()
SYNTAX
label.set_y(id, y) → void
ARGUMENTS
SEE ALSO
label.new
label.set_yloc()
SYNTAX
ARGUMENTS
SEE ALSO
yloc.priceyloc.abovebaryloc.belowbarlabel.new
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 library will be added over the chart. If false, it will be
added in a separate pane. Optional. The default is false.
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
plot(sinh(0))
SEE ALSO
indicatorstrategy
line()
Casts na to line
SYNTAX
ARGUMENTS
x (series line) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
floatintboolcolorstringlabel
line.copy()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
LOOKBACK = 100
highest = ta.highest(LOOKBACK)
lowest = ta.lowest(LOOKBACK)
if barstate.islastconfirmedhistory
line.set_y1(lineBottom, lowest)
line.set_y2(lineBottom, lowest)
line.set_color(lineBottom, color.red)
RETURNS
New line ID object which may be passed to line.setXXX and line.getXXX functions.
SEE ALSO
line.newline.delete
line.delete()
Deletes the specified line object. If it has already been deleted, does nothing.
SYNTAX
line.delete(id) → void
ARGUMENTS
SEE ALSO
line.new
line.get_price()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("GetPrice", overlay=true)
var line l = na
if bar_index == 10
RETURNS
REMARKS
This function can only be called for lines created using 'xloc.bar_index'. If you try to
call it for a line created with 'xloc.bar_time', it will generate an error.
SEE ALSO
line.new
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")
a = line.get_x1(my_line)
RETURNS
SEE ALSO
line.new
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
line.new
line.get_y1()
SYNTAX
ARGUMENTS
RETURNS
Price value.
SEE ALSO
line.new
line.get_y2()
ARGUMENTS
RETURNS
Price value.
SEE ALSO
line.new
line.new()
2 overloads
line.new(first_point, second_point, xloc, extend, color, style, width, force_overlay) → series line
line.new(x1, y1, x2, y2, xloc, extend, color, style, width, force_overlay) → series line
ARGUMENTS
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("line.new")
line.set_x2(line1, 0)
line.set_color(line2, color.green)
line.set_width(line2, 5)
RETURNS
SEE ALSO
line.deleteline.set_x1line.set_y1line.set_xy1line.set_x2line.set_y2line.set_xy2line.set_xlocline.set_c
olorline.set_extendline.set_styleline.set_width
line.set_color()
SYNTAX
ARGUMENTS
line.new
line.set_extend()
SYNTAX
ARGUMENTS
SEE ALSO
extend.noneextend.rightextend.leftextend.bothline.new
line.set_first_point()
SYNTAX
ARGUMENTS
line.set_second_point()
SYNTAX
line.set_second_point(id, point) → void
ARGUMENTS
line.set_style()
SYNTAX
ARGUMENTS
SEE ALSO
line.style_solidline.style_dottedline.style_dashedline.style_arrow_leftline.style_arrow_rightline.styl
e_arrow_bothline.new
line.set_width()
SYNTAX
ARGUMENTS
SEE ALSO
line.new
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
line.new
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
line.new
line.set_xloc()
SYNTAX
SEE ALSO
xloc.bar_indexxloc.bar_timeline.new
line.set_xy1()
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
line.new
line.set_xy2()
SYNTAX
line.set_xy2(id, x, y) → void
ARGUMENTS
SEE ALSO
line.new
line.set_y1()
SYNTAX
line.set_y1(id, y) → void
ARGUMENTS
SEE ALSO
line.new
line.set_y2()
SYNTAX
line.set_y2(id, y) → void
ARGUMENTS
SEE ALSO
line.new
linefill()
Casts na to linefill.
SYNTAX
ARGUMENTS
x (series linefill) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
floatintboolcolorstringlinelabel
linefill.delete()
Deletes the specified linefill object. If it has already been deleted, does nothing.
SYNTAX
linefill.delete(id) → void
ARGUMENTS
linefill.get_line1()
SYNTAX
ARGUMENTS
linefill.get_line2()
SYNTAX
linefill.get_line2(id) → series line
ARGUMENTS
linefill.new()
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
color (series color) The color used to fill the space between the lines.
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 extend.right 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
log.error()
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.
log.error(message) → void
ARGUMENTS
EXAMPLE
//@version=6
if (longCondition)
log.info("Exit orders have been placed: Take-profit at {0}, Stop-loss at {1}", close, limitLevel)
if strategy.opentrades > 10
log.warning("{0} positions opened in the same direction in a row. Try adjusting `bracketTickSizeInpu
t`", strategy.opentrades)
last10Perc = strategy.initial_capital / 10 > strategy.equity
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 str.format 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.
log.info()
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.
log.info(message) → void
EXAMPLE
//@version=6
if (longCondition)
log.info("Exit orders have been placed: Take-profit at {0}, Stop-loss at {1}", close, limitLevel)
if strategy.opentrades > 10
log.warning("{0} positions opened in the same direction in a row. Try adjusting `bracketTickSizeInpu
t`", strategy.opentrades)
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 str.format 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.
log.warning()
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.
log.warning(message) → void
ARGUMENTS
EXAMPLE
//@version=6
if (longCondition)
log.info("Exit orders have been placed: Take-profit at {0}, Stop-loss at {1}", close, limitLevel)
if strategy.opentrades > 10
log.warning("{0} positions opened in the same direction in a row. Try adjusting `bracketTickSizeInpu
t`", strategy.opentrades)
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 str.format 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.
map.clear()
SYNTAX
map.clear(id) → void
ARGUMENTS
EXAMPLE
//@version=6
indicator("map.clear example")
oddMap.put(1, true)
oddMap.put(2, false)
oddMap.put(3, true)
map.clear(oddMap)
plot(oddMap.size())
SEE ALSO
map.new<type,type>map.put_allmap.keysmap.valuesmap.remove
map.contains()
Returns true if the key was found in the id map, false otherwise.
SYNTAX
ARGUMENTS
key (series <type of the map's elements>) The key to search in the map.
EXAMPLE
//@version=6
indicator("map.includes example")
a = map.new<string, float>()
a.put("open", open)
p = close
if map.contains(a, "open")
p := a.get("open")
plot(p)
SEE ALSO
map.new<type,type>map.putmap.keysmap.valuesmap.size
map.copy()
SYNTAX
EXAMPLE
//@version=6
indicator("map.copy example")
a = map.new<string, int>()
a.put("example", 1)
b = map.copy(a)
a := map.new<string, int>()
a.put("example", 2)
plot(a.get("example"))
plot(b.get("example"))
RETURNS
SEE ALSO
map.new<type,type>map.putmap.keysmap.valuesmap.getmap.size
map.get()
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("map.get example")
a = map.new<int, int>()
size = 10
for i = 0 to size
a.put(i, size-i)
plot(map.get(a, 1))
SEE ALSO
map.new<type,type>map.putmap.keysmap.valuesmap.contains
map.keys()
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
map.keys(id) → array<type>
ARGUMENTS
EXAMPLE
//@version=6
indicator("map.keys example")
a = map.new<string, float>()
a.put("open", open)
a.put("high", high)
a.put("low", low)
a.put("close", close)
keys = map.keys(a)
ohlc = 0.0
ohlc += a.get(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
map.new<type,type>map.putmap.getmap.valuesmap.size
map.new<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
a = map.new<string, int>()
a.put("example", 1)
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
map.putmap.keysmap.valuesmap.getarray.new<type>
map.put()
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("map.put example")
a = map.new<string, float>()
currFirst = a.get("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.new<type,type>map.put_allmap.keysmap.valuesmap.remove
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 = map.new<string, float>()
b = map.new<string, float>()
a.put("first", 10)
a.put("second", 15)
b.put("third", 20)
map.put_all(a, b)
plot(a.get("third"))
SEE ALSO
map.new<type,type>map.putmap.keysmap.valuesmap.remove
map.remove()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("map.remove example")
a = map.new<string, color>()
a.put("firstColor", color.green)
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
map.new<type,type>map.putmap.keysmap.valuesmap.clear
map.size()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("map.size example")
a = map.new<int, int>()
size = 10
for i = 0 to size
a.put(i, size-i)
plot(map.size(a))
SEE ALSO
map.new<type,type>map.putmap.keysmap.valuesmap.get
map.values()
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
map.values(id) → array<type>
ARGUMENTS
EXAMPLE
//@version=6
indicator("map.values example")
a = map.new<string, float>()
a.put("open", open)
a.put("high", high)
a.put("low", low)
a.put("close", close)
values = map.values(a)
ohlc = 0.0
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
map.new<type,type>map.putmap.getmap.keysmap.size
math.abs()
8 overloads
Absolute value of number is number if number >= 0, or -number otherwise.
ARGUMENTS
RETURNS
math.acos()
4 overloads
The acos function returns the arccosine (in radians) of number such that cos(acos(y))
= y for y in range [-1, 1].
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].
math.asin()
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].
math.atan()
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].
math.avg()
2 overloads
ARGUMENTS
RETURNS
Average.
SEE ALSO
math.sumta.cumta.sma
math.ceil()
4 overloads
Rounds the specified number up to the smallest whole number ("int" value) that is
greater than or equal to it.
SYNTAX & OVERLOADS
ARGUMENTS
RETURNS
The smallest "int" value that is greater than or equal to the number.
SEE ALSO
math.floormath.round
math.cos()
4 overloads
ARGUMENTS
RETURNS
The exp function of number is e raised to the power of number, where e is Euler's
number.
ARGUMENTS
RETURNS
SEE ALSO
math.pow
math.floor()
4 overloads
Rounds the specified number down to the largest whole number ("int" value) that is
less than or equal to it.
RETURNS
The largest "int" value that is less than or equal to the number.
SEE ALSO
math.ceilmath.round
math.log()
4 overloads
Natural logarithm of any number > 0 is the unique y such that e^y = number.
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.
SYNTAX & OVERLOADS
ARGUMENTS
RETURNS
SEE ALSO
math.log
math.max()
8 overloads
number0, number1, ... (const int) A sequence of numbers to use in the calculation.
EXAMPLE
//@version=6
indicator("math.max", overlay=true)
plot(math.max(close, open))
RETURNS
SEE ALSO
math.min
math.min()
8 overloads
ARGUMENTS
number0, number1, ... (const int) A sequence of numbers to use in the calculation.
EXAMPLE
//@version=6
indicator("math.min", overlay=true)
plot(math.min(close, open))
RETURNS
SEE ALSO
math.max
math.pow()
4 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("math.pow", overlay=true)
plot(math.pow(close, 2))
RETURNS
SEE ALSO
math.sqrtmath.exp
math.random()
SYNTAX
ARGUMENTS
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.
math.round()
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
math.ceilmath.floor
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 syminfo.mintick, without the remainder, with ties rounding up.
ARGUMENTS
number (simple int/float) The value to be rounded.
RETURNS
REMARKS
SEE ALSO
math.ceilmath.floor
math.sign()
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
math.sin()
4 overloads
ARGUMENTS
RETURNS
math.sqrt()
4 overloads
Square root of any number >= 0 is the unique y >= 0 such that y^2 = number.
ARGUMENTS
RETURNS
SEE ALSO
math.pow
math.sum()
SYNTAX
ARGUMENTS
RETURNS
REMARKS
SEE ALSO
ta.cumfor
math.tan()
4 overloads
RETURNS
math.todegrees()
SYNTAX
ARGUMENTS
RETURNS
math.toradians()
SYNTAX
ARGUMENTS
RETURNS
The function adds a column at the column index of the id matrix. The column can
consist of na values, or an array can be used to provide values.
ARGUMENTS
column (series int) The index of the column after which the new column will be
inserted. Optional. The default value is matrix.columns.
EXAMPLE
//@version=6
m = matrix.new<int>(2, 3, 0)
matrix.add_col(m)
if barstate.islastconfirmedhistory
table.cell(t, 0, 1, str.tostring(m))
EXAMPLE
//@version=6
var m = matrix.new<int>()
var a = array.from(1, 3)
// Add the `a` array as the first column of the empty matrix.
matrix.add_col(m, 0, a)
table.cell(t, 0, 1, str.tostring(m))
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.new<type>matrix.getmatrix.setmatrix.columnsmatrix.rowsmatrix.add_row
matrix.add_row()
2 overloads
The function adds a row at the row index of the id matrix. The row can consist
of na values, or an array can be used to provide values.
ARGUMENTS
EXAMPLE
//@version=6
m = matrix.new<int>(2, 3, 0)
matrix.add_row(m)
if barstate.islastconfirmedhistory
table.cell(t, 0, 1, str.tostring(m))
EXAMPLE
//@version=6
if barstate.islastconfirmedhistory
var m = matrix.new<int>()
var a = array.from(1, 2)
// Add the `a` array as the first row of the empty matrix.
matrix.add_row(m, 0, a)
table.cell(t, 0, 1, str.tostring(m))
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
matrix.new<type>matrix.getmatrix.setmatrix.columnsmatrix.rowsmatrix.add_col
matrix.avg()
2 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.avg()` Example")
matrix.set(m, 0, 0, 1)
matrix.set(m, 0, 1, 2)
matrix.set(m, 1, 0, 3)
matrix.set(m, 1, 1, 4)
var x = matrix.avg(m)
RETURNS
The average value from the id matrix.
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.columnsmatrix.rows
matrix.col()
The function creates a one-dimensional array from the elements of a matrix column.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
m = matrix.new<float>(2, 3, hlc3)
// Return an array with the values of the first column of matrix `m`.
a = matrix.col(m, 0)
plot(array.get(a, 0))
RETURNS
REMARKS
SEE ALSO
matrix.new<type>matrix.getarray.getmatrix.colmatrix.columns
matrix.columns()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.columns()` Example")
var m = matrix.new<int>(2, 6, 0)
var x = matrix.columns(m)
if barstate.islastconfirmedhistory
RETURNS
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.colmatrix.rowmatrix.rows
matrix.concat()
SYNTAX
ARGUMENTS
id1 (any matrix type) Matrix object to concatenate into.
id2 (any matrix type) Matrix object whose elements will be appended to id1.
EXAMPLE
//@version=6
indicator("`matrix.concat()` Example")
m1 = matrix.new<int>(2, 4, 0)
m2 = matrix.new<int>(2, 4, 1)
matrix.concat(m1, m2)
if barstate.islastconfirmedhistory
table.cell(t, 0, 1, str.tostring(m1))
RETURNS
REMARKS
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.columnsmatrix.rows
matrix.copy()
SYNTAX
matrix.copy(id) → matrix<type>
ARGUMENTS
id (any matrix type) A matrix object to copy.
EXAMPLE
//@version=6
indicator("`matrix.copy()` Example")
if barstate.islastconfirmedhistory
var m1 = matrix.new<float>(2, 3, 1)
var m2 = matrix.copy(m1)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, str.tostring(m2))
RETURNS
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.columnsmatrix.rows
matrix.det()
2 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.det` Example")
matrix.set(m, 0, 0, 3)
matrix.set(m, 0, 1, 7)
matrix.set(m, 1, 0, 1)
matrix.set(m, 1, 1, -4)
var x = matrix.det(m)
RETURNS
REMARKS
SEE ALSO
matrix.new<type>matrix.setmatrix.is_square
matrix.diff()
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
if barstate.islastconfirmedhistory
var m1 = matrix.new<float>(2, 3, 5)
var m2 = matrix.new<float>(2, 3, 4)
// Create a new matrix containing the difference between matrices `m1` and `m2`.
table.cell(t, 0, 1, str.tostring(m3))
EXAMPLE
//@version=6
if barstate.islastconfirmedhistory
var m1 = matrix.new<float>(2, 3, 4)
// Create a new matrix containing the difference between the `m1` matrix and the "int" value `1`.
var m2 = matrix.diff(m1, 1)
table.cell(t, 0, 1, str.tostring(m2))
RETURNS
A new matrix object containing the difference between id2 and id1.
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.columnsmatrix.rows
matrix.eigenvalues()
2 overloads
matrix.eigenvalues(id) → array<float>
matrix.eigenvalues(id) → array<int>
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.eigenvalues()` Example")
if barstate.islastconfirmedhistory
matrix.set(m1, 0, 1, 4)
matrix.set(m1, 1, 0, 6)
matrix.set(m1, 1, 1, 8)
tr = matrix.eigenvalues(m1)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, str.tostring(tr))
RETURNS
REMARKS
SEE ALSO
matrix.new<type>matrix.setmatrix.eigenvectors
matrix.eigenvectors()
2 overloads
matrix.eigenvectors(id) → matrix<float>
matrix.eigenvectors(id) → matrix<int>
ARGUMENTS
id (matrix<int/float>) A matrix object.
EXAMPLE
//@version=6
indicator("`matrix.eigenvectors()` Example")
if barstate.islastconfirmedhistory
var m1 = matrix.new<int>(2, 2, 1)
matrix.set(m1, 0, 0, 2)
matrix.set(m1, 0, 1, 4)
matrix.set(m1, 1, 0, 6)
matrix.set(m1, 1, 1, 8)
m2 = matrix.eigenvectors(m1)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, str.tostring(m2))
RETURNS
REMARKS
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.eigenvalues
matrix.elements_count()
SYNTAX
ARGUMENTS
SEE ALSO
matrix.new<type>matrix.columnsmatrix.rows
matrix.fill()
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 matrix.rows.
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 matrix.columns.
EXAMPLE
//@version=6
indicator("`matrix.fill()` Example")
m = matrix.new<float>(4, 5, 0)
// Fill the intersection of rows 1 to 2 and columns 2 to 3 of the matrix with `hl2` values.
matrix.fill(m, hl2, 0, 2, 1, 3)
if barstate.islastconfirmedhistory
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.columnsmatrix.rows
matrix.get()
The function returns the element with the specified index of the matrix.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
m = matrix.new<float>(2, 3, hl2)
x = matrix.get(m, 0, 0)
plot(x)
RETURNS
The value of the element at the row and column index of the id matrix.
REMARKS
SEE ALSO
matrix.new<type>matrix.setmatrix.columnsmatrix.rows
matrix.inv()
2 overloads
matrix.inv(id) → matrix<float>
matrix.inv(id) → matrix<int>
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.inv()` Example")
if barstate.islastconfirmedhistory
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
var m2 = matrix.inv(m1)
// Display matrix elements.
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, str.tostring(m2))
RETURNS
REMARKS
SEE ALSO
matrix.new<type>matrix.setmatrix.pinvmatrix.copystr.tostring
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.new<type>matrix.setmatrix.is_squarematrix.is_identitymatrix.is_diagonal
matrix.is_antisymmetric()
SYNTAX
ARGUMENTS
RETURNS
REMARKS
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.is_square
matrix.is_binary()
The function determines if the matrix is binary (when all elements of the matrix are 0
or 1).
SYNTAX
ARGUMENTS
RETURNS
matrix.new<type>matrix.getmatrix.set
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.new<type>matrix.setmatrix.is_squarematrix.is_identitymatrix.is_antidiagonal
matrix.is_identity()
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
matrix.new<type>matrix.is_squarematrix.is_diagonal
matrix.is_square()
The function determines if the matrix is square (it has the same number of rows and
columns).
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.columnsmatrix.rows
matrix.is_stochastic()
SYNTAX
ARGUMENTS
RETURNS
matrix.new<type>matrix.set
matrix.is_symmetric()
SYNTAX
ARGUMENTS
RETURNS
REMARKS
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.is_square
matrix.is_triangular()
The function determines if the matrix is triangular (if all elements above or below
the main diagonal are zero).
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
matrix.new<type>matrix.setmatrix.is_square
matrix.is_zero()
SYNTAX
ARGUMENTS
RETURNS
Returns true if all elements of the id matrix are zero, false otherwise.
SEE ALSO
matrix.new<type>matrix.getmatrix.set
matrix.kron()
2 overloads
The function returns the Kronecker product for the id1 and id2 matrices.
ARGUMENTS
//@version=6
indicator("`matrix.kron()` Example")
if barstate.islastconfirmedhistory
var m1 = matrix.new<float>(2, 2, 1)
var m2 = matrix.new<float>(2, 2, 2)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, "⊗")
table.cell(t, 2, 1, str.tostring(m2))
table.cell(t, 3, 1, "=")
table.cell(t, 4, 1, str.tostring(m3))
RETURNS
SEE ALSO
matrix.new<type>matrix.multstr.tostringtable.new
matrix.max()
2 overloads
The function returns the largest value from the matrix elements.
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.max()` Example")
matrix.set(m, 0, 0, 1)
matrix.set(m, 0, 1, 2)
matrix.set(m, 1, 0, 3)
matrix.set(m, 1, 1, 4)
var x = matrix.max(m)
RETURNS
SEE ALSO
matrix.new<type>matrix.minmatrix.avgmatrix.sort
matrix.median()
2 overloads
The function calculates the median ("the middle" value) of matrix elements.
ARGUMENTS
id (matrix<int/float>) A matrix object.
EXAMPLE
//@version=6
indicator("`matrix.median()` Example")
m = matrix.new<int>(2, 2, na)
matrix.set(m, 0, 0, 1)
matrix.set(m, 0, 1, 2)
matrix.set(m, 1, 0, 3)
matrix.set(m, 1, 1, 4)
x = matrix.median(m)
REMARKS
Note that na elements of the matrix are not considered when calculating the median.
SEE ALSO
matrix.new<type>matrix.modematrix.sortmatrix.avg
matrix.min()
2 overloads
The function returns the smallest value from the matrix elements.
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.min()` Example")
matrix.set(m, 0, 0, 1)
matrix.set(m, 0, 1, 2)
matrix.set(m, 1, 0, 3)
matrix.set(m, 1, 1, 4)
var x = matrix.min(m)
RETURNS
SEE ALSO
matrix.new<type>matrix.maxmatrix.avgmatrix.sort
matrix.mode()
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("`matrix.mode()` Example")
// Create a 2x2 matrix.
matrix.set(m, 0, 0, 0)
matrix.set(m, 0, 1, 0)
matrix.set(m, 1, 0, 1)
matrix.set(m, 1, 1, 1)
var x = matrix.mode(m)
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
matrix.new<type>matrix.setmatrix.medianmatrix.sortmatrix.avg
matrix.mult()
4 overloads
The function returns a new matrix resulting from the product between the
matrices id1 and id2, or between an id1 matrix and an id2 scalar (a numerical
value), or between an id1 matrix and an id2 vector (an array of values).
EXAMPLE
//@version=6
if barstate.islastconfirmedhistory
var m1 = matrix.new<float>(6, 2, 5)
// Note that it must have the same quantity of rows as there are columns in the first matrix.
var m2 = matrix.new<float>(2, 3, 4)
table.cell(t, 0, 1, str.tostring(m3))
EXAMPLE
//@version=6
if barstate.islastconfirmedhistory
var m1 = matrix.new<float>(2, 3, 4)
scalar = 5
var m2 = matrix.mult(m1, scalar)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, "x")
table.cell(t, 2, 0, "Scalar:")
table.cell(t, 2, 1, str.tostring(scalar))
table.cell(t, 3, 1, "=")
table.cell(t, 4, 1, str.tostring(m2))
EXAMPLE
//@version=6
if barstate.islastconfirmedhistory
var m1 = matrix.new<int>(2, 3, 4)
// Create a new matrix containing the product of the `m1` matrix and the `a` array.
var m3 = matrix.mult(m1, a)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, "x")
table.cell(t, 2, 0, "Value:")
table.cell(t, 4, 1, str.tostring(m3))
RETURNS
SEE ALSO
matrix.new<type>matrix.summatrix.diff
matrix.new<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.
EXAMPLE
//@version=6
var m = matrix.new<int>(2, 3, 0)
if barstate.islastconfirmedhistory
EXAMPLE
//@version=6
// Function to create a matrix whose rows are filled with array values.
m = matrix.new<float>(rows, columns)
if barstate.islastconfirmedhistory
EXAMPLE
//@version=6
matrixFromInputArea(stringOfValues) =>
row = 0
col = 0
col += 1
row += 1
matrix
var m = matrixFromInputArea(stringInput)
if barstate.islastconfirmedhistory
EXAMPLE
//@version=6
for i = 0 to rows - 1
for j = 0 to columns - 1
matrix.set(result, i, j, math.random())
result
var m = matrixRandom(2, 3)
if barstate.islastconfirmedhistory
RETURNS
SEE ALSO
matrix.setmatrix.fillmatrix.columnsmatrix.rowsarray.new<type>
matrix.pinv()
2 overloads
The function returns the pseudoinverse of a matrix.
matrix.pinv(id) → matrix<float>
matrix.pinv(id) → matrix<int>
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.pinv()` Example")
if barstate.islastconfirmedhistory
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
var m2 = matrix.pinv(m1)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, str.tostring(m2))
RETURNS
SEE ALSO
matrix.new<type>matrix.setmatrix.inv
matrix.pow()
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("`matrix.pow()` Example")
if barstate.islastconfirmedhistory
var m1 = matrix.new<int>(2, 2, 2)
var m2 = matrix.pow(m1, 3)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "Matrix³:")
table.cell(t, 1, 1, str.tostring(m2))
RETURNS
SEE ALSO
matrix.new<type>matrix.setmatrix.mult
matrix.rank()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.rank()` Example")
if barstate.islastconfirmedhistory
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
r = matrix.rank(m1)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, str.tostring(r))
RETURNS
SEE ALSO
matrix.new<type>matrix.setstr.tostring
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 matrix.columns.
EXAMPLE
//@version=6
matrix.set(matrixOrig, 0, 1, 2)
matrix.set(matrixOrig, 1, 0, 3)
matrix.set(matrixOrig, 1, 1, 4)
matrixCopy = matrix.copy(matrixOrig)
// Remove the first column from the `matrixCopy` matrix.
arr = matrix.remove_col(matrixCopy, 0)
if barstate.islastconfirmedhistory
table.cell(t, 0, 1, str.tostring(matrixOrig))
table.cell(t, 1, 1, str.tostring(arr))
table.cell(t, 2, 1, str.tostring(matrixCopy))
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.new<type>matrix.setmatrix.copymatrix.remove_row
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
ARGUMENTS
EXAMPLE
//@version=6
matrix.set(matrixOrig, 0, 1, 2)
matrix.set(matrixOrig, 1, 0, 3)
matrix.set(matrixOrig, 1, 1, 4)
matrixCopy = matrix.copy(matrixOrig)
arr = matrix.remove_row(matrixCopy, 0)
if barstate.islastconfirmedhistory
table.cell(t, 0, 1, str.tostring(matrixOrig))
table.cell(t, 1, 1, str.tostring(arr))
table.cell(t, 2, 1, str.tostring(matrixCopy))
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
matrix.new<type>matrix.setmatrix.copymatrix.remove_col
matrix.reshape()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.reshape()` Example")
if barstate.islastconfirmedhistory
var m1 = matrix.new<float>(2, 3)
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 0, 2, 3)
matrix.set(m1, 1, 0, 4)
matrix.set(m1, 1, 1, 5)
matrix.set(m1, 1, 2, 6)
var m2 = matrix.copy(m1)
matrix.reshape(m2, 3, 2)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, str.tostring(m2))
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.add_rowmatrix.add_col
matrix.reverse()
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
matrix.reverse(id) → void
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.reverse()` Example")
if barstate.islastconfirmedhistory
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
var m2 = matrix.copy(m1)
// Reverse the `m2` copy of the original matrix.
matrix.reverse(m2)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, str.tostring(m2))
SEE ALSO
matrix.new<type>matrix.setmatrix.columnsmatrix.rowsmatrix.reshape
matrix.row()
The function creates a one-dimensional array from the elements of a matrix row.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
m = matrix.new<float>(2, 3, hlc3)
// Return an array with the values of the first row of the matrix.
a = matrix.row(m, 0)
plot(array.get(a, 0))
RETURNS
An array ID containing the row values of the id matrix.
REMARKS
SEE ALSO
matrix.new<type>matrix.getarray.getmatrix.colmatrix.rows
matrix.rows()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.rows()` Example")
var m = matrix.new<int>(2, 6, 0)
var x = matrix.rows(m)
if barstate.islastconfirmedhistory
RETURNS
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.columnsmatrix.row
matrix.set()
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("`matrix.set()` Example")
m = matrix.new<int>(2, 3, 4)
// Replace the value of element at row 1 and column 2 with value `3`.
matrix.set(m, 0, 1, 3)
if barstate.islastconfirmedhistory
SEE ALSO
matrix.new<type>matrix.getmatrix.columnsmatrix.rows
matrix.sort()
The function rearranges the rows in the id matrix following the sorted order of the
values in the column.
SYNTAX
column (series int) Index of the column whose sorted values determine the new
order of rows. Optional. The default value is 0.
EXAMPLE
//@version=6
indicator("`matrix.sort()` Example")
if barstate.islastconfirmedhistory
matrix.set(m1, 0, 0, 3)
matrix.set(m1, 0, 1, 4)
matrix.set(m1, 1, 0, 1)
matrix.set(m1, 1, 1, 2)
var m2 = matrix.copy(m1)
// Sort the rows of `m2` using the default arguments (first column and ascending order).
matrix.sort(m2)
if barstate.islastconfirmedhistory
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, str.tostring(m2))
SEE ALSO
matrix.new<type>matrix.maxmatrix.minmatrix.avg
matrix.submatrix()
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 matrix.rows.
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 matrix.columns.
EXAMPLE
//@version=6
indicator("`matrix.submatrix()` Example")
if barstate.islastconfirmedhistory
var m1 = matrix.new<int>(2, 3, 0)
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 0, 2, 3)
matrix.set(m1, 1, 0, 4)
matrix.set(m1, 1, 1, 5)
matrix.set(m1, 1, 2, 6)
// Create a 2x2 submatrix of the `m1` matrix.
var m2 = matrix.submatrix(m1, 0, 2, 1, 3)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "Submatrix:")
table.cell(t, 1, 1, str.tostring(m2))
RETURNS
REMARKS
SEE ALSO
matrix.new<type>matrix.setmatrix.rowmatrix.colmatrix.reshape
matrix.sum()
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
//@version=6
if barstate.islastconfirmedhistory
var m1 = matrix.new<float>(2, 3, 5)
var m2 = matrix.new<float>(2, 3, 4)
table.cell(t, 0, 1, str.tostring(m3))
EXAMPLE
//@version=6
if barstate.islastconfirmedhistory
var m1 = matrix.new<float>(2, 3, 4)
// Create a new matrix containing the sum of the `m1` matrix with the "int" value `1`.
var m2 = matrix.sum(m1, 1)
table.cell(t, 0, 1, str.tostring(m2))
RETURNS
A new matrix object containing the sum of id2 and id1.
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.columnsmatrix.rows
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")
if barstate.islastconfirmedhistory
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
var m2 = matrix.copy(m1)
matrix.swap_columns(m2, 0, 1)
// Display using a table.
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, str.tostring(m2))
REMARKS
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.columnsmatrix.rows
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")
if barstate.islastconfirmedhistory
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
matrix.set(m1, 2, 0, 5)
matrix.set(m1, 2, 1, 6)
var m2 = matrix.copy(m1)
matrix.swap_rows(m2, 0, 1)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, str.tostring(m2))
REMARKS
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.columnsmatrix.swap_columns
matrix.trace()
2 overloads
The function calculates the trace of a matrix (the sum of the main diagonal's
elements).
ARGUMENTS
id (matrix<int/float>) A matrix object.
EXAMPLE
//@version=6
indicator("`matrix.trace()` Example")
if barstate.islastconfirmedhistory
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
tr = matrix.trace(m1)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, str.tostring(tr))
RETURNS
SEE ALSO
matrix.new<type>matrix.getmatrix.setmatrix.columnsmatrix.rows
matrix.transpose()
The function creates a new, transposed version of the id. This interchanges the row
and column index of each element.
SYNTAX
matrix.transpose(id) → matrix<type>
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.transpose()` Example")
if barstate.islastconfirmedhistory
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
var m2 = matrix.transpose(m1)
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, str.tostring(m2))
RETURNS
SEE ALSO
matrix.new<type>matrix.setmatrix.columnsmatrix.rowsmatrix.reshapematrix.reverse
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 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
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")
d = depth()
v = close_()
max_bars_back(v, 500)
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)’).
SEE ALSO
indicator
minute()
2 overloads
ARGUMENTS
RETURNS
REMARKS
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1
January 1970.
SEE ALSO
minutetimeyearmonthdayofmonthdayofweekhoursecond
month()
2 overloads
ARGUMENTS
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
monthtimeyeardayofmonthdayofweekhourminutesecond
na()
2 overloads
Tests if x is na.
ARGUMENTS
EXAMPLE
//@version=6
indicator("na")
// ALTERNATIVE
// `nz()` also tests `close[1]` for `na`. It returns `close[1]` if it is not `na`, and `close` if it is.
plot(nz(close[1], close))
RETURNS
SEE ALSO
nafixnannz
nz()
12 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("nz", overlay=true)
plot(nz(ta.sma(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
nanafixnan
plot()
SYNTAX
plot(series, title, color, linewidth, style, trackprice, histbase, offset, join, editable, show_last, display,
format, precision, force_overlay) → plot
ARGUMENTS
series (series int/float) Series of data to be plotted. Required argument.
color (series color) Color of the plot. You can use constants like 'color=color.red' or
'color=#ff001a' as well as complex expressions like 'color = close >= open ? color.green
: color.red'. Optional argument.
linewidth (input int) Width of the plotted line. Default value is 1. Not applicable to
every style.
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.
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: format.price, format.percent, format.volume.
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 format.volume, the precision parameter will not affect the result, as the
decimal precision rules defined by format.volume supersede other precision settings.
Optional. The default is the precision 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("plot")
// You may fill the background between any two plots with a fill() function:
p1 = plot(open)
p2 = plot(close)
RETURNS
SEE ALSO
plotshapeplotcharplotarrowbarcolorbgcolorfill
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,
format, 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.
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.
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: format.price, format.percent, format.volume.
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 format.volume, the precision parameter will not affect the result, as the
decimal precision rules defined by format.volume supersede other precision settings.
Optional. The default is the precision 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
REMARKS
SEE ALSO
plotplotshapeplotcharbarcolorbgcolor
plotbar()
SYNTAX
plotbar(open, high, low, close, title, color, editable, show_last, display, format, precision, force_overlay) →
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.
color (series color) Color of the ohlc bars. You can use constants like 'color=color.red'
or 'color=#ff001a' as well as complex expressions like 'color = close >= open ?
color.green : color.red'. 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.
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: format.price, format.percent, format.volume.
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 format.volume, the precision parameter will not affect the result, as the
decimal precision rules defined by format.volume supersede other precision settings.
Optional. The default is the precision 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
plotbar(open, high, low, close, title='Title', color = open < close ? color.green : color.red)
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()
SYNTAX
plotcandle(open, high, low, close, title, color, wickcolor, editable, show_last, bordercolor, display, format,
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=color.red'
or 'color=#ff001a' as well as complex expressions like 'color = close >= open ?
color.green : color.red'. 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.
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: format.price, format.percent, format.volume.
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 format.volume, the precision parameter will not affect the result, as the
decimal precision rules defined by format.volume supersede other precision settings.
Optional. The default is the precision 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
plotcandle(open, high, low, close, title='Title', color = open < close ? color.green : color.red, wickcolor=color
.black)
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
color (series color) Color of the shapes. You can use constants like 'color=color.red'
or 'color=#ff001a' as well as complex expressions like 'color = close >= open ?
color.green : color.red'. 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=color.red' or 'textcolor=#ff001a' as well as complex expressions like
'textcolor = close >= open ? color.green : color.red'. Optional argument.
editable (input bool) If true then plotchar 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.
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: format.price, format.percent, format.volume.
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 format.volume, the precision parameter will not affect the result, as the
decimal precision rules defined by format.volume supersede other precision settings.
Optional. The default is the precision 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
SEE ALSO
plotplotshapeplotarrowbarcolorbgcolor
plotshape()
SYNTAX
plotshape(series, title, style, location, color, offset, text, textcolor, editable, size, show_last, display, format,
precision, force_overlay) → void
ARGUMENTS
color (series color) Color of the shapes. You can use constants like 'color=color.red'
or 'color=#ff001a' as well as complex expressions like 'color = close >= open ?
color.green : color.red'. 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=color.red' or 'textcolor=#ff001a' as well as complex expressions like
'textcolor = close >= open ? color.green : color.red'. Optional argument.
editable (input bool) If true then plotshape 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.
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: format.price, format.percent, format.volume.
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 format.volume, the precision parameter will not affect the result, as the
decimal precision rules defined by format.volume supersede other precision settings.
Optional. The default is the precision 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
plotshape(data, style=shape.xcross)
REMARKS
SEE ALSO
plotplotcharplotarrowbarcolorbgcolor
polyline.delete()
Deletes the specified polyline object. It has no effect if the id doesn't exist.
SYNTAX
polyline.delete(id) → void
ARGUMENTS
polyline.new()
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
polyline.new(points, curved, closed, xloc, line_color, fill_color, line_style, line_width, force_overlay) → series
polyline
ARGUMENTS
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.
line_color (series color) The color of the line segments. Optional. The default
is color.blue.
fill_color (series color) The fill color of the polyline. Optional. The default is na.
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
//@variable If `true`, connects all points in the polyline with curved line segments.
//@variable If `true`, connects the first point in the polyline to the last point.
if barstate.islastconfirmedhistory
points.push(chart.point.from_time(p1x, p1y))
points.push(chart.point.from_time(p2x, p2y))
points.push(chart.point.from_time(p3x, p3y))
points.push(chart.point.from_time(p4x, p4y))
points.push(chart.point.from_time(p5x, p5y))
// Create a new polyline that connects each `chart.point` in the `points` array, starting from the first.
RETURNS
SEE ALSO
chart.point.new
request.currency_rate()
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 syminfo.currency or currency.USD.
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 syminfo.currency or currency.USD.
//@version=6
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.
request.dividends()
SYNTAX
ARGUMENTS
ticker (series string) Symbol. Note that the symbol should be passed with a prefix.
For example: "NASDAQ:AAPL" instead of "AAPL". Using syminfo.ticker will cause an
error. Use syminfo.tickerid instead.
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.
currency (series string) Currency into which the symbol's currency-related dividends
values (e.g. dividends.gross) 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., currency.USD or currency.USDT).
The default is syminfo.currency.
EXAMPLE
//@version=6
indicator("request.dividends")
s1 = request.dividends("NASDAQ:BELFA")
plot(s1)
plot(s2)
RETURNS
Requested series, or n/a if there is no dividends data for the specified symbol.
SEE ALSO
request.earningsrequest.splitsrequest.securitysyminfo.tickerid
request.earnings()
SYNTAX
ARGUMENTS
ticker (series string) Symbol. Note that the symbol should be passed with a prefix.
For example: "NASDAQ:AAPL" instead of "AAPL". Using syminfo.ticker will cause an
error. Use syminfo.tickerid instead.
field (series string) Input string. Possible values
include: earnings.actual, earnings.estimate, earnings.standardized. Default value
is earnings.actual.
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.
currency (series string) Currency into which the symbol's currency-related earnings
values (e.g. earnings.actual) 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., currency.USD or currency.USDT).
The default is syminfo.currency.
EXAMPLE
//@version=6
indicator("request.earnings")
s1 = request.earnings("NASDAQ:BELFA")
plot(s1)
plot(s2)
RETURNS
Requested series, or n/a if there is no earnings data for the specified symbol.
SEE ALSO
request.dividendsrequest.splitsrequest.securitysyminfo.tickerid
request.economic()
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.
EXAMPLE
//@version=6
indicator("US GDP")
e = request.economic("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
request.financial
request.financial()
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.
EXAMPLE
//@version=6
indicator("request.financial")
plot(f)
RETURNS
Requested series.
SEE ALSO
request.securitysyminfo.tickerid
request.quandl()
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.
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.
EXAMPLE
//@version=6
indicator("request.quandl")
f = request.quandl("CFTC/SB_FO_ALL", barmerge.gaps_off, 0)
plot(f)
RETURNS
Requested series.
REMARKS
You can learn more about how to find ticker and index values in our Help Center.
SEE ALSO
request.securitysyminfo.tickerid
request.security()
SYNTAX
request.security(symbol, timeframe, expression, gaps, lookahead, ignore_invalid_symbol, currency,
calc_bars_count) → series <type>
ARGUMENTS
symbol (series string) Symbol or ticker identifier of the requested data. Use an
empty string or syminfo.tickerid 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 timeframe.period 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.
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.
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., currency.USD or currency.USDT). The default is syminfo.currency.
calc_bars_count (simple int) If specified, the function will only request this number
of values from the end of the symbol's history and calculate expression as if these
values are the only available data, which might improve calculation speed in some
cases. Optional. The default is 100,000, which is the limit for all non-professional
TradingView plans.
EXAMPLE
//@version=6
plot(dailyClose)
// Returns the close of "AAPL" from the same timeframe as currently open on the chart.
plot(aaplClose)
EXAMPLE
//@version=6
// This sends the `sma` calculation for execution in the context of the "AAPL" symbol at a "240" (4 hours) ti
meframe.
plot(aaplSma)
// To avoid differences on historical and realtime bars, you can use this technique, which only returns a va
lue from the higher timeframe on the bar after it completes:
indexHighTF = barstate.isrealtime ? 1 : 0
indexCurrTF = barstate.isrealtime ? 0 : 1
// Returns the 1H close of "AAPL", extended session included. The value is dividend-adjusted.
plot(aaplExtAdj)
// The `max` variable is mutable, but we can pass it to `request.security()` because it is wrapped in a functi
on.
allTimeHigh(source) =>
// By using a tuple `expression`, we obtain several values with only one `request.security()` call.
[open1D, high1D, low1D, close1D, ema1D] = request.security(syminfo.tickerid, "1D", [open, high, low, clos
e, ta.ema(close, 10)])
plot(ema1D)
// Returns an array containing the OHLC values of the chart's symbol from the 1D timeframe.
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 request.security("AAPL", "", close, calc_bars_count = 3) after it
calls request.security("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 syminfo.tickerid. Similarly, the timeframe
of a request.() call can be inherited if the timeframe argument is an empty string
or timeframe.period. 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
syminfo.tickersyminfo.tickeridtimeframe.periodticker.newticker.modifyrequest.security_lower_tfre
quest.dividendsrequest.earningsrequest.splitsrequest.financial
request.security_lower_tf()
SYNTAX
ARGUMENTS
symbol (series string) Symbol or ticker identifier of the requested data. Use an
empty string or syminfo.tickerid 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 timeframe.period 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.
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., currency.USD or currency.USDT). The default is syminfo.currency.
calc_bars_count (simple int) If specified, the function will only request this number
of values from the end of the symbol's history and calculate expression as if these
values are the only available data, which might improve calculation speed in some
cases. Optional. The default is 100,000, which is the limit for all non-professional
TradingView plans.
EXAMPLE
//@version=6
if bar_index == last_bar_index - 1
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 request.security("AAPL", "", close, calc_bars_count = 3) after it
calls request.security("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 syminfo.tickerid. Similarly, the timeframe
of a request.() call can be inherited if the timeframe argument is an empty string
or timeframe.period. 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
request.securitysyminfo.tickersyminfo.tickeridtimeframe.periodticker.newrequest.dividendsreque
st.earningsrequest.splitsrequest.financial
request.seed()
SYNTAX
ARGUMENTS
symbol (series string) Name of the file in the GitHub repository containing the data.
The ".csv" file extension must not be included.
calc_bars_count (simple int) If specified, the function will only request this number
of values from the end of the symbol's history and calculate expression as if these
values are the only available data, which might improve calculation speed in some
cases. Optional. The default is 100,000, which is the limit for all non-professional
TradingView plans.
EXAMPLE
//@version=6
request.splits()
SYNTAX
ARGUMENTS
ticker (series string) Symbol. Note that the symbol should be passed with a prefix.
For example: "NASDAQ:AAPL" instead of "AAPL". Using syminfo.ticker will cause an
error. Use syminfo.tickerid instead.
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.
EXAMPLE
//@version=6
indicator("request.splits")
s1 = request.splits("NASDAQ:BELFA", splits.denominator)
plot(s1)
plot(s2)
RETURNS
Requested series, or n/a if there is no splits data for the specified symbol.
SEE ALSO
request.earningsrequest.dividendsrequest.securitysyminfo.tickerid
runtime.error()
When called, causes a runtime error with the error message specified in
the message argument.
SYNTAX
runtime.error(message) → void
ARGUMENTS
second()
2 overloads
ARGUMENTS
RETURNS
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1
January 1970.
SEE ALSO
secondtimeyearmonthdayofmonthdayofweekhourminute
str.contains()
3 overloads
Returns true if the source string contains the str substring, false otherwise.
ARGUMENTS
EXAMPLE
//@version=6
indicator("str.contains")
// If the current chart is a continuous futures chart, e.g “BTC1!”, then the function will return true, false ot
herwise.
plot(isFutures ? 1 : 0)
RETURNS
True if the str was found in the source string, false otherwise.
SEE ALSO
str.posstr.match
str.endswith()
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
str.startswith
str.format()
2 overloads
Converts the formatting string and value(s) into a formatted string. 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 str.format argument list.
EXAMPLE
//@version=6
indicator("str.format", overlay=true)
// The format specifier inside the curly braces accepts certain modifiers:
s7 = str.format("{0, number, integer} is equal to 1, but {1, number, integer} is equal to 2", 1.34, 1.52)
s9 = str.format("Expected return is {0, number, percent} - {1, number, percent}", 0.1, 0.2)
label.new(bar_index - 8, close, text=s9)
RETURNS
REMARKS
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.
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.
str.format_time()
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 syminfo.timezone.
EXAMPLE
//@version=6
indicator("str.format_time")
if timeframe.change("1D")
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.
str.length()
3 overloads
ARGUMENTS
RETURNS
str.lower()
3 overloads
ARGUMENTS
RETURNS
SEE ALSO
str.upper
str.match()
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("str.match")
if barstate.islastconfirmedhistory
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 theregex string needs to be escaped with additional
backslash, e.g. "\\d" stands for regular expression "\d".
SEE ALSO
str.containsstr.substring
str.pos()
3 overloads
Returns the position of the first occurrence of the str string in the source string, 'na'
otherwise.
ARGUMENTS
RETURNS
REMARKS
SEE ALSO
str.containsstr.matchstr.substring
str.repeat()
4 overloads
Constructs a new string containing the source string repeated repeat times with
the separator injected between each repeated instance.
ARGUMENTS
repeat (const int) Number of times to repeat the source string. Must be greater
than or equal to 0.
separator (const string) String to inject between repeated values. Optional. The
default is empty string.
EXAMPLE
//@version=6
indicator("str.repeat")
label.new(bar_index,close,repeat)
REMARKS
str.replace()
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("str.replace")
if barstate.islastconfirmedhistory
RETURNS
Processed string.
SEE ALSO
str.replace_allstr.match
str.replace_all()
2 overloads
Replaces each occurrence of the target string in the source string with the
replacement string.
ARGUMENTS
RETURNS
Processed string.
str.split()
Divides a string into an array of substrings and returns its array id.
SYNTAX
ARGUMENTS
RETURNS
str.startswith()
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
str.endswith
str.substring()
6 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.
EXAMPLE
//@version=6
sym= input.symbol("NASDAQ:AAPL")
if barstate.islastconfirmedhistory
RETURNS
REMARKS
SEE ALSO
str.containsstr.posstr.match
str.tonumber()
4 overloads
ARGUMENTS
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.
str.tostring()
4 overloads
ARGUMENTS
value (simple int/float) 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.
str.tostring(3.99, '#') will return "4".
To display trailing zeros, use '0' instead of '#'. For example, '#.000'.
When using format.mintick, the value will be rounded to the nearest number that can
be divided by syminfo.mintick without the remainder. The string is returned with
trailing zeros.
str.trim()
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("str.trim")
label.new(bar_index,close,trim)
REMARKS
Returns an empty string ("") if the result is empty after the trim or if the source is na.
str.upper()
3 overloads
ARGUMENTS
RETURNS
SEE ALSO
str.lower
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 strategy will be displayed over the chart. If false, it
will be added in a separate pane. Strategy-specific labels that display entries and exits
will be displayed over the main chart regardless of this setting. Optional. The default
is false.
format (const string) Specifies the formatting of the script's displayed values.
Possible values: format.inherit, format.price, format.volume, format.percent.
Optional. The default is format.inherit.
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 format.inherit and precision is specified, the format will instead
be set to format.price. When the function's format parameter uses format.volume,
the precision parameter will not affect the result, as the decimal precision rules
defined by format.volume supersede other precision settings. Optional. The default is
inherited from the precision of the chart's symbol.
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.
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.
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.
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 syminfo.mintick 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.
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 strategy.exit 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.
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) Controls whether the script's plots and drawings in the
main chart pane appear behind the chart display (if true), or in front of it (if false).
Optional. The default is true.
EXAMPLE
//@version=6
// Generate a full exit bracket (profit 10 points, loss 5 points per contract) from the entry named "Long".
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 strategy.closedtrades.*() functions return na for trades opened or closed
by removed orders. To retrieve the index of the oldest available closed trade, use
the strategy.closedtrades.first_index variable.
SEE ALSO
indicatorlibrary
strategy.cancel()
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
strategy.cancel(id) → void
ARGUMENTS
EXAMPLE
//@version=6
if conditionForBuy
strategy.entry("Long", strategy.long, 1, limit = low) // Enter long using limit order at low price of curr
ent bar if `conditionForBuy` is `true`.
if not conditionForBuy
strategy.cancel("Long") // Cancel the entry order with name "Long" if `conditionForBuy` is `false`.
strategy.cancel_all()
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
if conditionForBuy1
strategy.entry("Long entry 1", strategy.long, 1, limit = low) // Enter long using a limit order if `conditi
onForBuy1` is `true`.
if conditionForBuy2
strategy.entry("Long entry 2", strategy.long, 1, limit = lowest2) // Enter long using a limit order if `co
nditionForBuy2` is `true`.
if conditionForStopTrading
strategy.cancel_all() // Cancel both limit orders if `conditionForStopTrading` is `true`.
strategy.close()
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 strategy.exit 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.
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 {{strategy.order.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
// Place a market order to enter a long position when `sma14` crosses over `sma28`.
if ta.crossover(sma14, sma28)
// Place a market order to close the long trade when `sma14` crosses under `sma28`.
if ta.crossunder(sma14, sma28)
plot(strategy.position_size)
REMARKS
strategy.close_all()
2 overloads
This command always generates market orders. To exit from a position using price-
based orders (e.g., stop-loss orders), use the strategy.exit command.
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 {{strategy.order.alert_message}} placeholder, the alert message replaces
the placeholder with this text. The default is an empty string.
EXAMPLE
//@version=6
// Place a market order to enter a long trade every time `sma14` crosses over `sma28`.
if ta.crossover(sma14, sma28)
// Place a market order to close the entire position every 500 bars.
if bar_index % 500 == 0
strategy.close_all()
plot(strategy.position_size)
strategy.closedtrades.commission()
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 calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
plot(strategy.closedtrades.commission(strategy.closedtrades - 1))
SEE ALSO
strategystrategy.opentrades.commission
strategy.closedtrades.entry_bar_index()
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("strategy.closedtrades.entry_bar_index Example")
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Function that calculates the average amount of bars in a trade.
avgBarsPerTrade() =>
sumBarsPerTrade = 0
plot(avgBarsPerTrade())
SEE ALSO
strategy.closedtrades.exit_bar_indexstrategy.opentrades.entry_bar_index
strategy.closedtrades.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
if (longCondition)
if barstate.islastconfirmedhistory or barstate.isrealtime
SEE ALSO
strategystrategy.entrystrategy.closedtrades
strategy.closedtrades.entry_id()
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first
trade is zero.
EXAMPLE
//@version=6
if bar_index == 1
if bar_index == last_bar_index - 2
strategy.close_all()
if barstate.islastconfirmedhistory
RETURNS
REMARKS
The function returns na if trade_num is not in the range: 0 to strategy.closedtrades-1.
SEE ALSO
strategy.closedtrades.entry_bar_indexstrategy.closedtrades.entry_pricestrategy.closedtrades.entr
y_time
strategy.closedtrades.entry_price()
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 calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
entryPrice = strategy.closedtrades.entry_price(strategy.closedtrades - 1)
EXAMPLE
//@version=6
if bar_index == last_bar_index - 15
strategy.entry("Short", strategy.short)
strategy.close("Short")
profitPct = 0.0
entryP = strategy.closedtrades.entry_price(tradeNo)
exitP = strategy.closedtrades.exit_price(tradeNo)
plot(avgProfitPct)
SEE ALSO
strategy.closedtrades.entry_pricestrategy.closedtrades.exit_pricestrategy.closedtrades.sizestrateg
y.closedtrades
strategy.closedtrades.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
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
avgTradeDuration() =>
sumTradeDuration = 0
for i = 0 to strategy.closedtrades - 1
// Display average duration converted to seconds and formatted using 2 decimal points
if barstate.islastconfirmedhistory
SEE ALSO
strategy.opentrades.entry_timestrategy.closedtrades.exit_timetime
strategy.closedtrades.exit_bar_index()
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 calls to place a single short trade. We enter the trade at the first bar and exit the trade at 10 b
ars before the last chart bar.
if bar_index == 0
strategy.entry("Short", strategy.short)
if bar_index == last_bar_index - 10
strategy.close("Short")
EXAMPLE
//@version=6
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
avgBarsPerTrade() =>
sumBarsPerTrade = 0
plot(avgBarsPerTrade())
SEE ALSO
bar_indexlast_bar_index
strategy.closedtrades.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
if (longCondition)
strategy.entry("Long", strategy.long)
strategy.exit("Exit", stop = open * 0.95, limit = close * 1.05, trail_points = 100, trail_offset = 0, comme
nt_profit = "TP", comment_loss = "SL", comment_trailing = "TRAIL")
exitStats() =>
int slCount = 0
int tpCount = 0
int trailCount = 0
if strategy.closedtrades > 0
for i = 0 to strategy.closedtrades - 1
switch strategy.closedtrades.exit_comment(i)
if barstate.islastconfirmedhistory
SEE ALSO
strategystrategy.exitstrategy.closestrategy.closedtrades
strategy.closedtrades.exit_id()
SYNTAX
trade_num (series int) The trade number of the closed trade. The number of the first
trade is zero.
EXAMPLE
//@version=6
if bar_index == last_bar_index - 15
// 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 quanti
ty
if ta.change(strategy.opentrades) != 0
posSign = strategy.opentrades.size(strategy.opentrades - 1)
// When a new closed trade is detected then we place a label above the bar with the exit info
if ta.change(strategy.closedtrades) != 0
RETURNS
REMARKS
SEE ALSO
strategy.closedtrades.exit_bar_indexstrategy.closedtrades.exit_pricestrategy.closedtrades.exit_tim
e
strategy.closedtrades.exit_price()
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first
trade is zero.
EXAMPLE
//@version=6
if bar_index % 5 == 0
strategy.entry("Long", strategy.long)
strategy.close("Long")
exitPrice = strategy.closedtrades.exit_price(strategy.closedtrades - 1)
EXAMPLE
//@version=6
if bar_index == last_bar_index - 15
strategy.close("Long Entry")
strategy.entry("Short", strategy.short)
strategy.close("Short")
entryP = strategy.closedtrades.entry_price(tradeNo)
exitP = strategy.closedtrades.exit_price(tradeNo)
plot(avgProfitPct)
SEE ALSO
strategy.closedtrades.entry_price
strategy.closedtrades.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
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
avgTradeDuration() =>
sumTradeDuration = 0
for i = 0 to strategy.closedtrades - 1
sumTradeDuration += strategy.closedtrades.exit_time(i) - strategy.closedtrades.entry_time(i)
// Display average duration converted to seconds and formatted using 2 decimal points.
if barstate.islastconfirmedhistory
EXAMPLE
//@version=6
if bar_index == 0
strategy.entry("Long", strategy.long)
reopenPositionAfter(timeSec) =>
if strategy.closedtrades > 0
strategy.entry("Long", strategy.long)
reopenPositionAfter(120)
if ta.change(strategy.opentrades) != 0
SEE ALSO
strategy.closedtrades.entry_time
strategy.closedtrades.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("`strategy.closedtrades.max_drawdown` Example")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Get the biggest max trade drawdown value from all of the closed trades.
maxTradeDrawDown() =>
maxDrawdown = 0.0
result = maxDrawdown
REMARKS
SEE ALSO
strategy.opentrades.max_drawdownstrategy.max_drawdown
strategy.closedtrades.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
strategy.closedtrades.max_drawdownstrategy.max_drawdown
strategy.closedtrades.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("`strategy.closedtrades.max_runup` Example")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Get the biggest max trade runup value from all of the closed trades.
maxTradeRunUp() =>
maxRunup = 0.0
result = maxRunup
SEE ALSO
strategy.opentrades.max_runupstrategy.max_runup
strategy.closedtrades.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) * 100.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first
trade is zero.
SEE ALSO
strategy.closedtrades.max_runupstrategy.max_runup
strategy.closedtrades.profit()
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("`strategy.closedtrades.profit` Example")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate average gross profit by adding the difference between gross profit and commission.
avgGrossProfit() =>
sumGrossProfit = 0.0
SEE ALSO
strategy.opentrades.profitstrategy.closedtrades.commission
strategy.closedtrades.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
strategy.closedtrades.profit
strategy.closedtrades.size()
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 calls to enter long trades every 15 bars and exit long trades every 20 bars
if bar_index % 15 == 0
if bar_index % 20 == 0
strategy.close("Long")
EXAMPLE
//@version=6
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
profitPct = 0.0
entryP = strategy.closedtrades.entry_price(tradeNo)
exitP = strategy.closedtrades.exit_price(tradeNo)
plot(avgProfitPct)
SEE ALSO
strategy.opentrades.sizestrategy.position_sizestrategy.closedtradesstrategy.opentrades
strategy.convert_to_account()
Converts the value from the currency that the symbol on the chart is traded in
(syminfo.currency) to the currency used by the strategy (strategy.account_currency).
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
EXAMPLE
// Calculates the "Buy and hold return" using your account's currency.
//@version=6
dateInput = input.time(timestamp("20 Jul 2021 00:00 +0300"), "From Date", confirm = true)
buyAndHoldReturnPct(fromDate) =>
plot(buyAndHoldReturnPct(dateInput))
SEE ALSO
strategystrategy.convert_to_symbol
strategy.convert_to_symbol()
SYNTAX
EXAMPLE
//@version=6
// Calculate the max qty we can buy using current chart's currency.
calcContracts(accountMoney) =>
qt = calcContracts(300)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars using our custom qt
y.
if bar_index % 15 == 0
if bar_index % 20 == 0
strategy.close("Long")
SEE ALSO
strategystrategy.convert_to_account
strategy.default_entry_qty()
SYNTAX
ARGUMENTS
fill_price (series int/float) The fill price for which to calculate the default order
quantity.
EXAMPLE
//@version=6
if ta.change(direction) < 0
//@variable The expected default fill quantity at the `stopPrice`. This value may not reflect actual qty
of the filled order, because fill price may be different.
calculatedQty = strategy.default_entry_qty(stopPrice)
if ta.change(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 strategy.entry 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.
Order placement commands can override the default value by explicitly passing a
new qty value in the function call.
strategy.entry()
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 stop arguments, it creates a market order that executes
on the next tick. If the call specifies a limit value but no stop 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 strategy.order, 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 strategy.short 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
strategy.entry(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.
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: strategy.oca.cancel, strategy.oca.reduce, strategy.oca.none. The
default is strategy.oca.none.
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 {{strategy.order.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
// Place a market order to close the short trade and enter a long position when `sma14` crosses over `sma
28`.
if ta.crossover(sma14, sma28)
// Place a market order to close the long trade and enter a short position when `sma14` crosses under `s
ma28`.
if ta.crossunder(sma14, sma28)
EXAMPLE
//@version=6
//@variable The distance from the `close` price for each limit order.
//@function Draws a label and line at the specified `price` to visualize a limit order's level.
label.new(
l.set_x2(bar_index)
l.set_extend(extend.none)
if ta.crossover(sma14, sma28)
//@variable The limit price level. Its value is `limitOffsetInput` ticks below the current `close`.
// Place a long limit order to close the short trade and enter a long position at the `limitLevel`.
// Make new drawings for the long limit and stop extending the `shortLimit` line.
shortLimit.stopExtend()
if ta.crossunder(sma14, sma28)
//@variable The limit price level. Its value is `limitOffsetInput` ticks above the current `close`.
// Place a short limit order to close the long trade and enter a short position at the `limitLevel`.
// Make new drawings for the short limit and stop extending the `shortLimit` line.
longLimit.stopExtend()
strategy.exit()
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 strategy.close or strategy.close_all.
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 strategy.exit 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 strategy.close or strategy.order.
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
strategy.exit(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,
alert_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_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 strategy.exit calls. The
command ignores this parameter if the qty value is not na. The default is 100.
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_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 strategy.oca.reduce 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 {{strategy.order.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 {{strategy.order.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 {{strategy.order.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 {{strategy.order.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
// Inputs that define the profit and loss amount of each trade as a tick distance from the entry price.
// Place a take-profit and stop-loss order when the entry order fills.
strategy.exit("My Long Exit ID", "My Long Entry ID", profit = profitDistanceInput, loss = lossDistanceI
nput)
if ta.change(strategy.opentrades) == 1
if ta.change(strategy.closedtrades) == 1
takeProfit := na
stopLoss := na
EXAMPLE
//@version=6
//@variable The number of ticks the trailing stop follows behind the price as it reaches new peaks.
//@function Draws a label and line at the specified `price` to visualize a trailing stop order's activation lev
el.
label.new(
line.new(
l.set_x2(bar_index)
l.set_extend(extend.none)
// The activation line, active trailing stop price, and active trailing stop flag.
trailingStopPrice := na
isActive := false
strategy.exit(
"My Long Exit ID", "My Long Entry ID", trail_price = activationPrice, trail_offset = trailDistanceI
nput,
oca_name = "Exit"
activationLine := drawActivation(activationPrice)
if strategy.opentrades == 1
isActive := true
activationLine.stopExtend()
if isActive
// Close the trade with a market order if the trailing stop does not activate before the next 300th bar.
strategy.close_all("Market close")
// Reset the `trailingStopPrice` and `isActive` flags when the trade closes, and stop extending the `activatio
nLine`.
if ta.change(strategy.closedtrades) > 0
if not isActive
activationLine.stopExtend()
trailingStopPrice := na
isActive := false
REMARKS
A single call to the strategy.exit 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.
If a strategy.exit 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.
strategy.opentrades.commission()
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 calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
sumOpenGrossPL = 0.0
result = sumOpenGrossPL
plot(tradeOpenGrossPL())
SEE ALSO
strategystrategy.closedtrades.commission
strategy.opentrades.entry_bar_index()
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("`strategy.opentrades.entry_bar_index` Example")
barsSinceLastEntry() =>
if strategy.opentrades == 0
strategy.entry("Long", strategy.long)
if barsSinceLastEntry() >= 10
strategy.close("Long")
SEE ALSO
strategy.closedtrades.entry_bar_indexstrategy.closedtrades.exit_bar_index
strategy.opentrades.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
if (longCondition)
if barstate.islastconfirmedhistory or barstate.isrealtime
SEE ALSO
strategystrategy.entrystrategy.opentrades
strategy.opentrades.entry_id()
SYNTAX
strategy.opentrades.entry_id(trade_num) → series string
ARGUMENTS
trade_num (series int) The trade number of the open trade. The number of the first
trade is zero.
EXAMPLE
//@version=6
// 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.
// Strategy calls to enter a long or short position when the corresponding condition is met.
if longCondition
if shortCondition
if barstate.islastconfirmedhistory
RETURNS
REMARKS
SEE ALSO
strategy.opentrades.entry_bar_indexstrategy.opentrades.entry_pricestrategy.opentrades.entry_ti
me
strategy.opentrades.entry_price()
ARGUMENTS
trade_num (series int) The trade number of the open trade. The number of the first
trade is zero.
EXAMPLE
//@version=6
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
strategy.entry("Long", strategy.long)
currEntryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)
strategy.close("Long")
EXAMPLE
//@version=6
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
avgOpenPositionPrice() =>
sumOpenPositionPrice = 0.0
plot(avgOpenPositionPrice())
SEE ALSO
strategy.closedtrades.exit_price
strategy.opentrades.entry_time()
Returns the UNIX time of the open trade's entry, expressed in milliseconds.
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("strategy.opentrades.entry_time Example")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
timeSinceLastEntry()=>
SEE ALSO
strategy.closedtrades.entry_timestrategy.closedtrades.exit_time
strategy.opentrades.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 calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
EXAMPLE
// Calculates the max trade drawdown value for all open trades.
//@version=6
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Get the biggest max trade drawdown value from all of the open trades.
maxTradeDrawDown() =>
maxDrawdown = 0.0
result = maxDrawdown
SEE ALSO
strategy.closedtrades.max_drawdownstrategy.max_drawdown
strategy.opentrades.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
strategy.opentrades.max_drawdownstrategy.max_drawdown
strategy.opentrades.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("strategy.opentrades.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
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
EXAMPLE
// Calculates the max trade runup value for all open trades.
//@version=6
if bar_index % 30 == 0
strategy.entry("Long", strategy.long)
// Calculate biggest max trade runup value from all of the open trades.
maxOpenTradeRunUp() =>
maxRunup = 0.0
result = maxRunup
SEE ALSO
strategy.closedtrades.max_runupstrategy.max_drawdown
strategy.opentrades.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) * 100.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first
trade is zero.
SEE ALSO
strategy.opentrades.max_runupstrategy.max_runup
strategy.opentrades.profit()
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 calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
EXAMPLE
//@version=6
if bar_index % 2 == 0
tradeOpenPL() =>
sumProfit = 0.0
sumProfit += strategy.opentrades.profit(tradeNo)
result = sumProfit
SEE ALSO
strategy.closedtrades.profitstrategy.openprofitstrategy.netprofitstrategy.grossprofit
strategy.opentrades.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
strategy.opentrades.profit
strategy.opentrades.size()
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 calls to enter long trades every 15 bars and exit long trades every 20 bars
if bar_index % 15 == 0
if bar_index % 20 == 0
strategy.close("Long")
EXAMPLE
//@version=6
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
profitPct = 0.0
entryP = strategy.opentrades.entry_price(tradeNo)
exitP = close
plot(avgProfitPct)
SEE ALSO
strategy.closedtrades.sizestrategy.position_sizestrategy.opentradesstrategy.closedtrades
strategy.order()
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 stop arguments, it creates a market order that executes
on the next tick. If the call specifies a limit value but no stop 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 strategy.entry, 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 strategy.entry 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 strategy.short triggers the sale of five shares, which closes the
position.
SYNTAX
strategy.order(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: strategy.long for a long trade, strategy.short for a short one.
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: strategy.oca.cancel, strategy.oca.reduce, strategy.oca.none. The
default is strategy.oca.none.
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 {{strategy.order.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
// Place a market order to enter a long position when `sma14` crosses over `sma28`.
// Place a market order to sell the same quantity as the long trade when `sma14` crosses under `sma28`,
EXAMPLE
//@version=6
//@variable The distance from the long entry price for each short limit order.
//@function Draws a label and line at the specified `price` to visualize a limit order's level.
label.new(
bar_index, price, (isLong ? "Long " : "Short ") + (isStop ? "stop" : "limit") + " order created",
l.set_x2(bar_index)
l.set_extend(extend.none)
// Initialize two `line` variables to reference limit and stop line IDs.
// Calculate short limit and stop levels above and below the `entryPrice`.
// Place short limit and stop orders at the `profitLevel` and `lossLevel`.
if ta.change(strategy.closedtrades) > 0
profitLimit.stopExtend()
lossStop.stopExtend()
strategy.risk.allow_entry_in()
SYNTAX
strategy.risk.allow_entry_in(value) → void
ARGUMENTS
//@version=6
strategy("strategy.risk.allow_entry_in")
strategy.risk.allow_entry_in(strategy.direction.long)
strategy.entry("Long", strategy.long)
// Instead of opening a short position with 10 contracts, this command will close long entries.
strategy.risk.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
ARGUMENTS
count (simple int) A required parameter. The allowed number of consecutive days
with losses.
EXAMPLE
//@version=6
strategy.risk.max_cons_loss_days(3) // No orders will be placed after 3 days, if each day is with loss.
plot(strategy.position_size)
strategy.risk.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
type (simple string) A required parameter. The type of the value. Please specify one
of the following values: strategy.percent_of_equity or strategy.cash. 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
//@version=6
plot(strategy.position_size)
EXAMPLE
//@version=6
plot(strategy.position_size)
strategy.risk.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
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")
strategy.entry("buy", strategy.long)
strategy.entry("sell", strategy.short)
strategy.risk.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
type (simple string) A required parameter. The type of the value. Please specify one
of the following values: strategy.percent_of_equity or strategy.cash. 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
lossPct = input.float(10)
strategy.risk.max_intraday_loss(lossPct, strategy.percent_of_equity)
if bar_index == 0
strategy.entry("Short", strategy.short)
// Calculate change of the current equity from the beginning of the current day.
// Plot it
plot(eqChgPct)
hline(-lossPct)
EXAMPLE
// Sets the maximum intraday loss using the strategy's cash value.
//@version=6
// Input for maximum intraday loss in absolute cash value of the symbol.
absCashLoss = input.float(5)
strategy.risk.max_intraday_loss(absCashLoss, strategy.cash)
if bar_index == 0
strategy.entry("Short", strategy.short)
// Store the open price value from the beginning of the day.
hline(absCashLoss)
plot(priceChg)
SEE ALSO
strategystrategy.percent_of_equitystrategy.cash
strategy.risk.max_position_size()
The purpose of this rule is to determine maximum size of a market position. The rule
affects the following function: strategy.entry. 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 'strategy.risk.max_position_size'. If minimum
possible quantity still violates the rule, the order will not be placed.
SYNTAX
strategy.risk.max_position_size(contracts) → void
ARGUMENTS
EXAMPLE
//@version=6
strategy.risk.max_position_size(10)
strategy.entry("buy", strategy.long)
string()
4 overloads
Casts na to string
SYNTAX & OVERLOADS
ARGUMENTS
x (const string) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
floatintboolcolorlinelabel
syminfo.prefix()
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
i_sym = input.symbol("NASDAQ:AAPL")
pref = syminfo.prefix(i_sym)
tick = syminfo.ticker(i_sym)
plot(s)
RETURNS
REMARKS
SEE ALSO
syminfo.tickeridsyminfo.tickersyminfo.prefixsyminfo.tickerticker.new
syminfo.ticker()
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
i_sym = input.symbol("NASDAQ:AAPL")
pref = syminfo.prefix(i_sym)
tick = syminfo.ticker(i_sym)
RETURNS
REMARKS
SEE ALSO
syminfo.tickeridsyminfo.tickersyminfo.prefixsyminfo.prefixticker.new
ta.alma()
2 overloads
Arnaud Legoux Moving Average. It uses Gaussian distribution as weights for moving
average.
ARGUMENTS
sigma (simple int/float) Changes the smoothness of ALMA. The larger sigma the
smoother ALMA.
EXAMPLE
//@version=6
indicator("ta.alma", overlay=true)
m = offset * (windowsize - 1)
s = windowsize / sigma
norm = 0.0
sum = 0.0
for i = 0 to windowsize - 1
sum / norm
RETURNS
REMARKS
na values in the source series are included in calculations and will produce
an na result.
SEE ALSO
ta.smata.emata.rmata.wmata.vwmata.swma
ta.atr()
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("ta.atr")
plot(ta.atr(14))
pine_atr(length) =>
ta.rma(trueRange, length)
plot(pine_atr(14))
RETURNS
REMARKS
SEE ALSO
ta.trta.rma
ta.barssince()
Counts the number of bars since the last time the condition was true.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("ta.barssince")
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
ta.lowestbarsta.highestbarsta.valuewhenta.highestta.lowest
ta.bb()
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("ta.bb")
plot(middle, color=color.yellow)
plot(upper, color=color.yellow)
plot(lower, color=color.yellow)
plot(pineMiddle)
plot(pineUpper)
plot(pineLower)
RETURNS
Bollinger Bands.
REMARKS
SEE ALSO
ta.smata.stdevta.kc
ta.bbw()
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("ta.bbw")
plot(f_bbw(close, 5, 4))
RETURNS
REMARKS
SEE ALSO
ta.bbta.smata.stdev
ta.cci()
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.
ta.change()
6 overloads
Compares the current source value to its value length bars ago and returns the
difference.
ARGUMENTS
EXAMPLE
//@version=6
dailyBarTime = time('1D')
isNewDay = ta.change(dailyBarTime) != 0
colorChange = ta.change(isGreenBar)
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
ta.momta.cross
ta.cmo()
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("ta.cmo")
plot(f_cmo(close, 5))
RETURNS
SEE ALSO
ta.rsita.stochmath.sum
ta.cog()
The cog (center of gravity) is an indicator based on statistics and the Fibonacci golden
ratio.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("ta.cog", overlay=true)
plot(ta.cog(close, 10))
num = 0.0
for i = 0 to length - 1
price = source[i]
-num / sum
plot(pine_cog(close, 10))
RETURNS
Center of Gravity.
REMARKS
SEE ALSO
ta.stoch
ta.correlation()
Correlation coefficient. Describes the degree to which two series tend to deviate from
their ta.sma values.
SYNTAX
ARGUMENTS
RETURNS
Correlation coefficient.
REMARKS
SEE ALSO
request.security
ta.cross()
SYNTAX
ARGUMENTS
source1 (series int/float) First data series.
RETURNS
SEE ALSO
ta.change
ta.crossover()
SYNTAX
ARGUMENTS
RETURNS
ta.crossunder()
SYNTAX
ARGUMENTS
source1 (series int/float) First data series.
RETURNS
ta.cum()
Cumulative (total) sum of source. In other words it's a sum of all elements
of source.
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
math.sum
ta.dev()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("ta.dev")
plot(ta.dev(close, 10))
sum = 0.0
for i = 0 to length - 1
val = source[i]
dev = sum/length
plot(pine_dev(close, 10))
RETURNS
REMARKS
SEE ALSO
ta.varianceta.stdev
ta.dmi()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator(title="Directional Movement Index", shorttitle="DMI", format=format.price, precision=4)
RETURNS
Tuple of three DMI series: Positive Directional Movement (+DI), Negative Directional
Movement (-DI) and Average Directional Movement Index (ADX).
SEE ALSO
ta.rsita.tsita.mfi
ta.ema()
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 alpha = 2 / (length +
1).
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("ta.ema")
plot(ta.ema(close, 15))
alpha = 2 / (length + 1)
sum = 0.0
plot(pine_ema(close,15))
RETURNS
REMARKS
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
ta.smata.rmata.wmata.vwmata.swmata.alma
ta.falling()
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
ta.rising
ta.highest()
2 overloads
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
ta.lowestta.lowestbarsta.highestbarsta.valuewhenta.barssince
ta.highestbars()
2 overloads
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
ta.lowestta.highestta.lowestbarsta.barssinceta.valuewhen
ta.hma()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
RETURNS
REMARKS
SEE ALSO
ta.emata.rmata.wmata.vwmata.sma
ta.kc()
2 overloads
ta.kc(series, length, mult, useTrueRange) → [series float, series float, series float]
ARGUMENTS
EXAMPLE
//@version=6
indicator("ta.kc")
plot(middle, color=color.yellow)
plot(upper, color=color.yellow)
plot(lower, color=color.yellow)
plot(pineMiddle)
plot(pineUpper)
plot(pineLower)
RETURNS
Keltner Channels.
REMARKS
SEE ALSO
ta.emata.atrta.bb
ta.kcw()
2 overloads
Keltner Channels Width. The Keltner Channels Width is the difference between the
upper and the lower Keltner Channels divided by the middle channel.
ARGUMENTS
EXAMPLE
//@version=6
indicator("ta.kcw")
plot(f_kcw(close, 5, 4, true))
RETURNS
REMARKS
SEE ALSO
ta.kcta.emata.atrta.bb
ta.linreg()
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
source (series int/float) Source series.
RETURNS
REMARKS
na values in the source series are included in calculations and will produce
an na result.
ta.lowest()
2 overloads
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.
ta.highestta.lowestbarsta.highestbarsta.valuewhenta.barssince
ta.lowestbars()
2 overloads
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
ta.lowestta.highestta.highestbarsta.barssinceta.valuewhen
ta.macd()
SYNTAX
ta.macd(source, fastlen, slowlen, siglen) → [series float, series float, series float]
ARGUMENTS
EXAMPLE
//@version=6
indicator("MACD")
plot(macdLine, color=color.blue)
plot(signalLine, color=color.orange)
If you need only one value, use placeholders '_' like this:
EXAMPLE
//@version=6
indicator("MACD")
plot(signalLine, color=color.orange)
RETURNS
Tuple of three MACD series: MACD line, signal line and histogram line.
REMARKS
SEE ALSO
ta.smata.ema
ta.max()
Returns the all-time high value of source from the beginning of the chart up to the
current bar.
SYNTAX
ARGUMENTS
REMARKS
ta.median()
2 overloads
ARGUMENTS
RETURNS
REMARKS
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
mfi
plot(pine_mfi(hlc3, 14))
RETURNS
REMARKS
SEE ALSO
ta.rsimath.sum
ta.min()
Returns the all-time low value of source from the beginning of the chart up to the
current bar.
SYNTAX
ARGUMENTS
REMARKS
ta.mode()
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.
ta.mom()
Momentum of source price and source price length bars ago. This is simply a
difference: source - source[length].
SYNTAX
ARGUMENTS
length (series int) Offset from the current bar to the previous bar.
RETURNS
REMARKS
na values in the source series are included in calculations and will produce
an na result.
SEE ALSO
ta.change
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()
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.
SEE ALSO
ta.percentile_linear_interpolation
ta.percentrank()
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
timeframe = "1W"
weekChange = timeframe.change(timeframe)
if weekChange
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.
ta.pivothigh()
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 = ta.pivothigh(leftBars, rightBars)
RETURNS
REMARKS
ta.pivotlow()
2 overloads
This function returns price of the pivot low point. It returns 'NaN', if there was no
pivot low point.
SYNTAX & OVERLOADS
ARGUMENTS
EXAMPLE
//@version=6
indicator("PivotLow", overlay=true)
leftBars = input(2)
rightBars=input(2)
RETURNS
REMARKS
ta.range()
2 overloads
Returns the difference between the min and max values in a series.
ARGUMENTS
source (series int) Series of values to process.
RETURNS
The difference between the min and max values in the series.
REMARKS
ta.rci()
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
ta.rising()
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
ta.falling
ta.rma()
Moving average used in RSI. It is the exponentially weighted moving average with
alpha = 1 / length.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("ta.rma")
plot(ta.rma(close, 15))
alpha = 1/length
sum = 0.0
plot(pine_rma(close, 15))
RETURNS
REMARKS
SEE ALSO
ta.smata.emata.wmata.vwmata.swmata.almata.rsi
ta.roc()
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.
ta.rsi()
Relative strength index. It is calculated using the ta.rma() of upward and downward
changes of source over the last length bars.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("ta.rsi")
plot(ta.rsi(close, 7))
pine_rsi(x, y) =>
rs = ta.rma(u, y) / ta.rma(d, y)
res
plot(pine_rsi(close, 7))
RETURNS
REMARKS
ta.rma
ta.sar()
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("ta.sar")
if bar_index == 1
isBelow := true
maxMin := high
result := low[1]
else
isBelow := false
maxMin := low
result := high[1]
isFirstTrendBar := true
acceleration := start
if isBelow
isFirstTrendBar := true
isBelow := false
maxMin := low
acceleration := start
else
isFirstTrendBar := true
isBelow := true
maxMin := high
acceleration := start
if not isFirstTrendBar
if isBelow
maxMin := high
else
maxMin := low
if isBelow
if bar_index > 1
result := math.min(result, low[2])
else
if bar_index > 1
result
RETURNS
Parabolic SAR.
ta.sma()
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("ta.sma")
plot(ta.sma(close, 15))
pine_sma(x, y) =>
sum = 0.0
for i = 0 to y - 1
plot(pine_sma(close, 15))
RETURNS
REMARKS
SEE ALSO
ta.emata.rmata.wmata.vwmata.swmata.alma
ta.stdev()
SYNTAX
ARGUMENTS
biased (series bool) Determines which estimate should be used. Optional. The
default is true.
EXAMPLE
//@version=6
indicator("ta.stdev")
plot(ta.stdev(close, 5))
EPS = 1e-10
if isZero(res, EPS)
res := 0
else
res := res
else
15
sumOfSquareDeviations = 0.0
for i = 0 to length - 1
plot(pine_stdev(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.
SEE ALSO
ta.devta.variance
ta.stoch()
SYNTAX
ARGUMENTS
source (series int/float) Source series.
RETURNS
Stochastic.
REMARKS
SEE ALSO
ta.cog
ta.supertrend()
SYNTAX
ARGUMENTS
factor (series int/float) The multiplier by which the ATR will get multiplied.
EXAMPLE
//@version=6
atr = ta.atr(atrPeriod)
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
int _direction = na
float superTrend = na
prevSuperTrend = superTrend[1]
if na(atr[1])
_direction := 1
else
[superTrend, _direction]
RETURNS
Tuple of two supertrend series: supertrend line and direction of trend. Possible values
are 1 (down direction) and -1 (up direction).
SEE ALSO
ta.macd
ta.swma()
Symmetrically weighted moving average with fixed length: 4. Weights: [1/6, 2/6, 2/6,
1/6].
SYNTAX
ta.swma(source) → series float
ARGUMENTS
EXAMPLE
//@version=6
indicator("ta.swma")
plot(ta.swma(close))
pine_swma(x) =>
plot(pine_swma(close))
RETURNS
REMARKS
na values in the source series are included in calculations and will produce
an na result.
SEE ALSO
ta.smata.emata.rmata.wmata.vwmata.alma
ta.tr()
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: math.max(high - low, math.abs(high -
close[1]), math.abs(low - close[1]))
SYNTAX
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
ta.trta.atr
ta.tsi()
SYNTAX
ARGUMENTS
RETURNS
REMARKS
Returns the value of the source series on the bar where the condition was true on
the nth most recent occurrence.
ARGUMENTS
source (series color) The value to be returned from the bar where the condition is
met.
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("ta.valuewhen")
slow = ta.sma(close, 7)
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
ta.lowestbarsta.highestbarsta.barssinceta.highestta.lowest
ta.variance()
Variance is the expectation of the squared deviation of a series from its mean
(ta.sma), 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.
SEE ALSO
ta.devta.stdev
ta.vwap()
3 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("Simple VWAP")
vwap = ta.vwap(open)
plot(vwap)
EXAMPLE
//@version=6
indicator("Advanced VWAP")
anchor = timeframe.change(anchorTimeframe)
plot(vwap)
RETURNS
REMARKS
Calculations only begin the first time the anchor condition becomes true. Until then,
the function returns na.
SEE ALSO
ta.vwap
ta.vwma()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("ta.vwma")
plot(ta.vwma(close, 15))
pine_vwma(x, y) =>
plot(pine_vwma(close, 15))
RETURNS
REMARKS
SEE ALSO
ta.smata.emata.rmata.wmata.swmata.alma
ta.wma()
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("ta.wma")
plot(ta.wma(close, 15))
pine_wma(x, y) =>
norm = 0.0
sum = 0.0
for i = 0 to y - 1
weight = (y - i) * y
sum / norm
plot(pine_wma(close, 15))
RETURNS
REMARKS
SEE ALSO
ta.smata.emata.rmata.vwmata.swmata.alma
ta.wpr()
Williams %R. The oscillator shows the current closing price in relation to the high and
low of the past 'length' bars.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
RETURNS
Williams %R.
REMARKS
SEE ALSO
ta.mfita.cmo
table()
Casts na to table
SYNTAX
ARGUMENTS
x (series table) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
floatintboolcolorstringlinelabel
table.cell()
The function defines a cell in the table and sets its attributes.
SYNTAX
table.cell(table_id, column, row, text, width, height, text_color, text_halign, text_valign, text_size, bgcolor,
tooltip, text_font_family, text_formatting) → void
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 (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 color.black.
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: size.auto (0), size.tiny (8), size.small (10), size.normal (14), size.large (20), size.hug
e (36). The default value is size.normal 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.
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 table.new.
Each table.cell call overwrites all previously defined properties of a cell. If you
call table.cell twice in a row, e.g., the first time with text='Test Text', and the second
time with text_color=color.red 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 table.cell 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 barstate.islast block whenever possible, to restrict their execution to the last bar
of the series.
SEE ALSO
table.cell_set_bgcolortable.cell_set_heighttable.cell_set_texttable.cell_set_text_formattingtable.cell
_set_text_colortable.cell_set_text_haligntable.cell_set_text_sizetable.cell_set_text_valigntable.cell_s
et_widthtable.cell_set_tooltip
table.cell_set_bgcolor()
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.
SEE ALSO
table.cell_set_heighttable.cell_set_texttable.cell_set_text_colortable.cell_set_text_haligntable.cell_s
et_text_sizetable.cell_set_text_valigntable.cell_set_widthtable.cell_set_tooltip
table.cell_set_height()
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.
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_bgcolortable.cell_set_texttable.cell_set_text_colortable.cell_set_text_haligntable.cell_
set_text_sizetable.cell_set_text_valigntable.cell_set_widthtable.cell_set_tooltip
table.cell_set_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.
EXAMPLE
//@version=6
indicator("TABLE example")
SEE ALSO
table.cell_set_bgcolortable.cell_set_heighttable.cell_set_text_colortable.cell_set_text_haligntable.c
ell_set_text_sizetable.cell_set_text_valigntable.cell_set_widthtable.cell_set_tooltiptable.cell_set_text
_formatting
table.cell_set_text_color()
The function sets the color of the text inside the cell.
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.
SEE ALSO
table.cell_set_bgcolortable.cell_set_heighttable.cell_set_texttable.cell_set_text_haligntable.cell_set
_text_sizetable.cell_set_text_valigntable.cell_set_widthtable.cell_set_tooltip
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.
EXAMPLE
//@version=6
table.cell_set_text_font_family(t, 0, 0, font.family_monospace)
SEE ALSO
table.newfont.family_defaultfont.family_monospace
table.cell_set_text_formatting()
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.
SEE ALSO
table.cell_set_bgcolortable.cell_set_heighttable.cell_set_text_colortable.cell_set_text_haligntable.c
ell_set_text_sizetable.cell_set_text_valigntable.cell_set_widthtable.cell_set_tooltiptable.cell_set_text
table.cell_set_text_halign()
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_bgcolortable.cell_set_heighttable.cell_set_texttable.cell_set_text_colortable.cell_set_t
ext_sizetable.cell_set_text_valigntable.cell_set_widthtable.cell_set_tooltip
table.cell_set_text_size()
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_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: size.auto (0), size.tiny (8), size.small (10), size.normal (14), size.large (20), size.hug
e (36). The default value is size.normal or 14.
SEE ALSO
table.cell_set_bgcolortable.cell_set_heighttable.cell_set_texttable.cell_set_text_colortable.cell_set_t
ext_haligntable.cell_set_text_valigntable.cell_set_widthtable.cell_set_tooltip
table.cell_set_text_valign()
SYNTAX
ARGUMENTS
table_id (series table) A table object.
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_bgcolortable.cell_set_heighttable.cell_set_texttable.cell_set_text_colortable.cell_set_t
ext_haligntable.cell_set_text_sizetable.cell_set_widthtable.cell_set_tooltip
table.cell_set_tooltip()
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")
SEE ALSO
table.cell_set_bgcolortable.cell_set_heighttable.cell_set_text_colortable.cell_set_text_haligntable.c
ell_set_text_sizetable.cell_set_text_valigntable.cell_set_widthtable.cell_set_text
table.cell_set_width()
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.
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
table.cell_set_bgcolortable.cell_set_heighttable.cell_set_texttable.cell_set_text_colortable.cell_set_t
ext_haligntable.cell_set_text_sizetable.cell_set_text_valigntable.cell_set_tooltip
table.clear()
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
if barstate.islast
colNum = 8, rowNum = 8
padding = "◯"
for c = 0 to colNum - 1
for r = 0 to rowNum - 1
table.clear(donutTable, 2, 2, 5, 5)
SEE ALSO
table.deletetable.new
table.delete()
SYNTAX
table.delete(table_id) → void
ARGUMENTS
EXAMPLE
//@version=6
indicator("table.delete example")
if barstate.islast
table.cell(table_id = testTable, column = 0, row = 0, text = "Open is " + str.tostring(open))
if barstate.isrealtime
table.delete(testTable)
SEE ALSO
table.newtable.clear
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_column (series int) The index of the column of the first cell to merge.
Numbering starts at 0.
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")
// Header
table.merge_cells(maTable, 0, 0, 2, 0)
// Cell Titles
// Values
REMARKS
This function will merge cells, even if their properties are not yet defined
with table.cell.
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:start_row coordinates.
An attempt to merge a cell that has already been merged will result in an error.
SEE ALSO
table.deletetable.new
table.new()
SYNTAX
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("table.new example")
if barstate.islast
RETURNS
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 table.cell and other table.cell_*() functions.
One table.new 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 table.new in conjunction with either the var keyword (so the table object is
only created on the first bar) or in an if barstate.islast block (so the table object is only
created on the last bar).
SEE ALSO
table.celltable.cleartable.deletetable.set_bgcolortable.set_border_colortable.set_border_widthtabl
e.set_frame_colortable.set_frame_widthtable.set_position
table.set_bgcolor()
SYNTAX
ARGUMENTS
bgcolor (series color) The background color of the table. Optional. The default is no
color.
SEE ALSO
table.cleartable.deletetable.newtable.set_border_colortable.set_border_widthtable.set_frame_col
ortable.set_frame_widthtable.set_position
table.set_border_color()
The function sets the color of the borders (excluding the outer frame) of the table's
cells.
SYNTAX
border_color (series color) The color of the borders. Optional. The default is no color.
SEE ALSO
table.cleartable.deletetable.newtable.set_frame_colortable.set_border_widthtable.set_bgcolortabl
e.set_frame_widthtable.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.cleartable.deletetable.newtable.set_frame_colortable.set_frame_widthtable.set_bgcolortable
.set_border_colortable.set_position
table.set_frame_color()
SYNTAX
ARGUMENTS
frame_color (series color) The color of the frame of the table. Optional. The default
is no color.
SEE ALSO
table.cleartable.deletetable.newtable.set_border_colortable.set_border_widthtable.set_bgcolortab
le.set_frame_widthtable.set_position
table.set_frame_width()
SYNTAX
ARGUMENTS
frame_width (series int) The width of the outer frame of the table. Optional. The
default is 0.
SEE ALSO
table.cleartable.deletetable.newtable.set_frame_colortable.set_border_widthtable.set_bgcolortabl
e.set_border_colortable.set_position
table.set_position()
SYNTAX
ARGUMENTS
SEE ALSO
table.cleartable.deletetable.newtable.set_bgcolortable.set_border_colortable.set_border_widthtab
le.set_frame_colortable.set_frame_width
ticker.heikinashi()
2 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("ticker.heikinashi", overlay=true)
plot(heikinashi_close)
plot(heikinashi_aapl_60_close)
RETURNS
SEE ALSO
syminfo.tickeridsyminfo.tickerrequest.securityticker.renkoticker.linebreakticker.kagiticker.pointfigu
re
ticker.inherit()
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.
SYNTAX & OVERLOADS
ARGUMENTS
symbol (simple string) The symbol to construct the new ticker ID for.
EXAMPLE
//@version=6
indicator("ticker.inherit")
//@variable A Heikin Ashi ticker ID for "NASDAQ:AAPL" with Extended Hours enabled.
HAtickerExtHours = ticker.heikinashi(tickerExtHours)
testSymbol = "NASDAQ:MSFT"
//@variable A ticker ID for "NASDAQ:MSFT" with inherited Heikin Ashi and Extended Hours modifiers.
//@variable The `close` price requested using "NASDAQ:MSFT" with inherited modifiers.
plot(compareData)
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.
ticker.kagi()
2 overloads
Creates a ticker identifier for requesting Kagi values.
ARGUMENTS
EXAMPLE
//@version=6
indicator("ticker.kagi", overlay=true)
kagi_tickerid = ticker.kagi(syminfo.tickerid, 3)
plot(kagi_close)
RETURNS
SEE ALSO
syminfo.tickeridsyminfo.tickerrequest.securityticker.heikinashiticker.renkoticker.linebreakticker.poi
ntfigure
ticker.linebreak()
2 overloads
ARGUMENTS
symbol (simple string) Symbol ticker identifier.
EXAMPLE
//@version=6
indicator("ticker.linebreak", overlay=true)
linebreak_tickerid = ticker.linebreak(syminfo.tickerid, 3)
plot(linebreak_close)
RETURNS
SEE ALSO
syminfo.tickeridsyminfo.tickerrequest.securityticker.heikinashiticker.renkoticker.kagiticker.pointfig
ure
ticker.modify()
2 overloads
Creates a ticker identifier for requesting additional data for the script.
ARGUMENTS
tickerid (series string) Symbol name with exchange prefix, e.g. 'BATS:MSFT',
'NASDAQ:MSFT' or tickerid with session and adjustment from the ticker.new function.
EXAMPLE
//@version=6
indicator("ticker_modify", overlay=true)
t2 = ticker.modify(t1, session.extended)
plot(c1)
plot(c2)
RETURNS
SEE ALSO
syminfo.tickeridsyminfo.tickersyminfo.sessionsession.extendedsession.regularticker.heikinashiadj
ustment.noneadjustment.splitsadjustment.dividendsbackadjustment.inheritbackadjustment.onb
ackadjustment.offsettlement_as_close.inheritsettlement_as_close.onsettlement_as_close.off
ticker.new()
2 overloads
Creates a ticker identifier for requesting additional data for the script.
ARGUMENTS
prefix (series string) Exchange prefix. For example: 'BATS', 'NYSE', 'NASDAQ'.
Exchange prefix of main series is syminfo.prefix.
ticker (series string) Ticker name. For example 'AAPL', 'MSFT', 'EURUSD'. Ticker name
of the main series is syminfo.ticker.
session (series string) Session type. Optional argument. Possible
values: session.regular, session.extended. Session type of the current chart
is syminfo.session. If session is not given, then syminfo.session value is used.
EXAMPLE
//@version=6
indicator("ticker.new", overlay=true)
t2 = ticker.heikinashi(t)
plot(c, style=plot.style_linebr)
RETURNS
REMARKS
SEE ALSO
syminfo.tickeridsyminfo.tickersyminfo.sessionsession.extendedsession.regularticker.heikinashiadj
ustment.noneadjustment.splitsadjustment.dividendsbackadjustment.inheritbackadjustment.onb
ackadjustment.offsettlement_as_close.inheritsettlement_as_close.onsettlement_as_close.off
ticker.pointfigure()
2 overloads
ARGUMENTS
source (simple string) The source for calculating Point & Figure. Possible values are:
'hl', 'close'.
param (simple int/float) ATR Length if style is equal to 'ATR', or Box Size if style is
equal to 'Traditional'.
EXAMPLE
//@version=6
indicator("ticker.pointfigure", overlay=true)
plot(pnf_close)
RETURNS
SEE ALSO
syminfo.tickeridsyminfo.tickerrequest.securityticker.heikinashiticker.renkoticker.linebreakticker.ka
gi
ticker.renko()
2 overloads
param (simple int/float) ATR Length if style is equal to 'ATR', or Box Size if style is
equal to 'Traditional'.
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("ticker.renko", overlay=true)
plot(renko_close)
EXAMPLE
//@version=6
RETURNS
SEE ALSO
syminfo.tickeridsyminfo.tickerrequest.securityticker.heikinashiticker.linebreakticker.kagiticker.poin
tfigure
ticker.standard()
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 syminfo.tickerid.
EXAMPLE
//@version=6
// Requests data from the chart type the script is running on.
// Request data from the standard chart type, regardless of the chart type the script is running on.
// This will not use a standard ticker ID because the `symbol` argument contains only the ticker — not the
prefix (exchange).
plot(chartTypeValue)
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
request.security
time()
3 overloads
The time function returns the UNIX time of the current bar for the specified
timeframe and session or NaN if the time point is out of session.
ARGUMENTS
bars_back (series int) Optional. The bar offset on the script's main timeframe. If the
value is positive, the function retrieves the timestamp of the bar N bars back relative
to the current bar on the main timeframe. If the value is a negative number from -1
to -500, the function retrieves the expected time of a future bar on that timeframe.
The default is 0.
EXAMPLE
//@version=6
indicator("Time", overlay=true)
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(timeframe.period, "0000-0000:23456")
EXAMPLE
//@version=6
indicator("Time", overlay=true)
t1 = time(timeframe.period, "1000-1100,1400-1500:23456")
RETURNS
UNIX time.
REMARKS
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1
January 1970.
SEE ALSO
time
time_close()
3 overloads
Returns the UNIX time of the current bar's close for the specified timeframe and
session, or na if the time point is outside the session. On non-standard price-based
chart types (Renko, Line break, Kagi, Point & Figure, and Range), this function
returns na on the chart's realtime bars.
ARGUMENTS
bars_back (series int) Optional. The bar offset on the script's main timeframe. If the
value is positive, the function retrieves the timestamp of the bar N bars back relative
to the current bar on the main timeframe. If the value is a negative number from -1
to -500, the function retrieves the expected time of a future bar on that timeframe.
The default is 0.
EXAMPLE
//@version=6
indicator("Time", overlay=true)
RETURNS
UNIX time.
REMARKS
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1
January 1970.
SEE ALSO
time_close
timeframe.change()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
isNewDay = timeframe.change("1D")
RETURNS
timeframe.from_seconds()
2 overloads
ARGUMENTS
//@version=6
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_secondsrequest.securityrequest.security_lower_tf
timeframe.in_seconds()
2 overloads
ARGUMENTS
timeframe (simple string) Timeframe string in timeframe string
specifications format. Optional. The default is timeframe.period.
EXAMPLE
//@version=6
indicator("`timeframe_in_seconds()`")
tfInput = input.timeframe("1D")
secondsInTf = timeframe.in_seconds(tfInput)
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
input.timeframetimeframe.periodtimeframe.from_seconds
timestamp()
5 overloads
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("2011-10-10T14:48:00"))
RETURNS
UNIX time.
REMARKS
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1
January 1970.
SEE ALSO
time
weekofyear()
2 overloads
ARGUMENTS
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 week 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 week of the trading day.
SEE ALSO
weekofyeartimeyearmonthdayofmonthdayofweekhourminutesecond
year()
2 overloads
ARGUMENTS
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
yeartimemonthdayofmonthdayofweekhourminutesecond
Keywords
and
Logical AND. Applicable to boolean expressions.
SYNTAX
RETURNS
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 const string title. If a field's title is not specified, its title
is the string representation of its name. Use str.tostring on an enum field to retrieve
its title.
SYNTAX
<field_2> [= <title_2>]
...
<field_N> [= <title_N>]
One can use an enum to quickly create a dropdown input with the help of
the input.enum function. The options that appear in the dropdown represent the
titles of the enum fields.
EXAMPLE
//@version=6
//@field exch Has an empty string as the title to represent the chart timezone.
enum tz
utc = "UTC"
exch = ""
ny = "America/New_York"
chi = "America/Chicago"
lon = "Europe/London"
tok = "Asia/Tokyo"
//@variable The selected timezone. The input's dropdown contains the fields in the `tz` enum.
inSession := 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
enum symbols
aapl = "NASDAQ:AAPL"
tsla = "NASDAQ:TSLA"
amzn = "NASDAQ:AMZN"
//@variable A map that accepts fields from the `symbols` enum as keys and "float" values.
// Plot the value from the `data` map accessed by the `symbols.aapl` key.
plot(data.get(symbols.aapl))
export
EXAMPLE
//@version=6
//@returns Void.
// Using the function from inside the library to show an example on the published chart.
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.
SEE ALSO
libraryimportsimpleseriestype
for
SYNTAX
return_expression
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 code line or block 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
//@function Calculates the number of bars in the last `length` bars that have their `close` above the curre
nt `close`.
greaterCloseCount(length) =>
int result = 0
for i = 1 to length
result += 1
result
plot(greaterCloseCount(14))
EXAMPLE
//@version=6
a = array.from(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 += array.get(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_num value becomes greater than the from_num value.
SEE ALSO
for...inwhile
for...in
The for...in structure allows the repeated execution of a number of statements for
each element in an array. It can be used with either one argument: array_element,
or with two: [index, array_element]. The second form doesn't affect the
functionality of the loop. It tracks the current iteration's index in the tuple's first
variable.
SYNTAX
return_expression
return_expression
index - An optional variable that tracks the current iteration's index. Indexing starts at
0. The variable is immutable in the loop's body. When used, it must be included in a
tuple also containing array_element.
continue - A keyword that can only be used in loops. It causes the next iteration of the
loop to be executed.
Scripts can modify arrays and matrices while iterating over their elements with this
structure. However, maps cannot change while looping through their key-value pairs.
To modify a map within a for...in loop, iterate over the key-value pairs of a copy or
over the elements in its map.keys array.
Here, we use the single-argument form of for...in to determine on each bar how
many of the bar's OHLC values are greater than the SMA of 'close' values:
EXAMPLE
//@version=6
indicator("for...in")
// Here we determine on each bar how many of the bar's OHLC values are greater than the SMA of 'close'
values
int result = 0
result += 1
result
Here, we use the two-argument form of for...in to set the values of our isPos array
to true when their corresponding value in our valuesArray array is positive:
EXAMPLE
//@version=6
indicator("for...in")
var valuesArray = array.from(4, -8, 11, 78, -16, 34, 7, 99, 0, 55)
if value > 0
if barstate.islastconfirmedhistory
EXAMPLE
//@version=6
matrix1 = matrix.new<int>(2, 3, 4)
sum = 0.0
sum += array.sum(rowArray)
plot(sum)
SEE ALSO
forwhilearray.sumarray.minarray.max
if
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.
SYNTAX
var_declarationX = if condition
var_decl_then0
var_decl_then1
var_decl_thenN
var_decl_else0
var_decl_else1
var_decl_elseN
else
var_decl_else0
var_decl_else1
var_decl_elseN
return_expression_else
where
condition — if the condition is true, the logic from the block 'then' (var_decl_then0,
var_decl_then1, etc.) is used.
If the condition is false, the logic from the block 'else' (var_decl_else0, var_decl_else1,
etc.) is used.
EXAMPLE
//@version=6
indicator("if")
close
else
open
// close
// else
// "open"
plot(x)
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")
close
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")
close
else
open
plot(x)
EXAMPLE
//@version=6
strategy("if")
if (ta.crossover(high, low))
strategy.cancel(id="BBandLE")
EXAMPLE
//@version=6
indicator("if")
float x = na
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" namespace",
import username/num_methods/1 as m
y = m.sinh(3.14)
plot(y)
REMARKS
SEE ALSO
libraryexport
method
SYNTAX
<functionBlock>
EXAMPLE
//@version=6
indicator("")
//@function Pushes a new value into the array and removes the first one if the resulting array is greater t
han `maxSize`. Can be used as a method.
id.push(value)
id.shift()
prices.maintainArray(50, close)
// The method can also be called like a function, without using dot notation.
// This calls the `array.avg()` 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(prices.avg())
not
SYNTAX
not expr1
RETURNS
or
SYNTAX
expr1 or expr2
RETURNS
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
=> default_local_block
[variable_declaration = ] switch
=> default_local_block
EXAMPLE
//@version=6
string i_maType = input.string("EMA", "MA type", options = ["EMA", "SMA", "RMA", "WMA"])
plot(ma)
EXAMPLE
//@version=6
switch
RETURNS
The value of the last expression in the local block of statements that is executed.
REMARKS
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
[export ]type <UDT_identifier>
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
timeframeInput = input.timeframe("1D")
type bar
float o = open
float h = high
float l = low
float c = close
int t = time
bar s = bar.new()
box.new(b.t, b.h, right, b.l, boxColor, xloc = xloc.bar_time, bgcolor = color.new(boxColor, 90))
box.set_border_color(boxId, boxColor)
box.set_bgcolor(boxId, color.new(boxColor, 90))
box.set_top(boxId, b.h)
box.set_bottom(boxId, b.l)
box.set_right(boxId, time)
if not na(secBar)
if not barstate.islast
if timeframe.change(timeframeInput)
// On historical bars, draw a new box in the past when the HTF closes.
drawBox(secBar, time[1])
else
if na(lastBox) or timeframe.change(timeframeInput)
// On the last bar, only draw a new current box the first time we get there or when HTF ch
anges.
else
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
var a = close
var b = 0.0
var c = 0.0
var green_bars_count = 0
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
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.
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
type barData
int index = -1
currBar.index += 1
currBar.ticks += 1
// Will be equal to bar_index on all bars
plot(currBar.index)
plot(currBar.ticks)
The same += operation applied to both the index and ticks fields results in
different real-time values because ticks 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
The while statement allows the conditional iteration of a local code block.
SYNTAX
continue
break
return_expression
where:
condition - when true, the local block of the while statement is executed. When false,
execution of the script resumes after the while statement.
continue - The continue keyword causes the loop to branch to its next iteration.
break - The break keyword causes the loop to terminate. The script's execution
resumes after the while statement.
EXAMPLE
//@version=6
indicator("while")
int factorial = 1
counter := counter - 1
plot(factorial)
REMARKS
The local code block after the initial while line must be indented with four spaces or
a tab. For the while loop to terminate, the boolean expression following while must
eventually become false, or a break must be executed.
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 array.new<type>, array.from function.
EXAMPLE
//@version=6
indicator("array", overlay=true)
array<float> a = na
a := array.new<float>(1, close)
plot(array.get(a, 0))
REMARKS
SEE ALSO
varlinelabeltableboxarray.new<type>array.from
bool
EXAMPLE
//@version=6
indicator("bool")
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
varvaripintfloatcolorstringtruefalse
box
Keyword used to explicitly declare the "box" type of a variable or a parameter. Box
objects (or IDs) can be created with the box.new function.
EXAMPLE
//@version=6
indicator("box")
REMARKS
SEE ALSO
varlinelabeltablebox.new
chart.point
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
EXAMPLE
//@version=6
color labelColor = #FF000080 // Red color (FF0000) with 50% transparency (80 which is half of FF).
if barstate.islastconfirmedhistory
c = color.rgb(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.
SEE ALSO
varvaripintfloatstringcolor.rgbcolor.new
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
plot(close, myTitle)
EXAMPLE
//@version=6
//@variable A variable declared as "const float" that attempts to assign the result of `input.float()` as its v
alue.
// This declaration causes an error. The "input float" qualified type is stronger than "const float".
plot(myVar)
REMARKS
SEE ALSO
simpleseries
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
SEE ALSO
varvaripintboolcolorstring
int
Keyword used to explicitly declare the "int" (integer) type of a variable or a parameter.
EXAMPLE
//@version=6
indicator("int")
i := na
plot(i)
REMARKS
SEE ALSO
varvaripfloatboolcolorstring
label
Keyword used to explicitly declare the "label" type of a variable or a parameter. Label
objects (or IDs) can be created with the label.new function.
EXAMPLE
//@version=6
indicator("label")
// Empty `label1` label ID.
if barstate.islastconfirmedhistory
REMARKS
SEE ALSO
varlineboxlabel.new
line
Keyword used to explicitly declare the "line" type of a variable or a parameter. Line
objects (or IDs) can be created with the line.new function.
EXAMPLE
//@version=6
indicator("line")
REMARKS
SEE ALSO
varlabelboxline.new
linefill
EXAMPLE
//@version=6
indicator("linefill", overlay=true)
if barstate.islastconfirmedhistory
REMARKS
SEE ALSO
varlinelabeltableboxlinefill.new
map
Keyword used to explicitly declare the "map" type of a variable or a parameter. Map
objects (or IDs) can be created with the map.new<type,type> function.
EXAMPLE
//@version=6
indicator("map", overlay=true)
map<int, float> a = na
a := map.new<int, float>()
a.put(bar_index, close)
REMARKS
SEE ALSO
map.new<type,type>
matrix
EXAMPLE
//@version=6
indicator("matrix example")
matrix<int> m1 = matrix.new<int>(2, 3, 0)
// `matrix<int>` is unnecessary because the `matrix.new<int>()` function returns an `int` type matrix object
.
m2 = matrix.new<int>(2, 3, 0)
if barstate.islastconfirmedhistory
REMARKS
SEE ALSO
varmatrix.new<type>array
polyline
SEE ALSO
chart.point
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
//@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.
for i = 0 to length - 1
if cond[i]
value = source[i]
result
//@variable The highest `close` value from every fifth bar over the last 100 bars.
plot(hiValue)
EXAMPLE
//@version=6
// The `histbase` accepts "input int/float". It can't accept the stronger "series int" qualified type.
REMARKS
SEE ALSO
simpleconst
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
EXAMPLE
//@version=6
//@function Calculates the length values for a ribbon of four EMAs by multiplying the `baseLength`.
//@param baseLength The initial EMA length. Requires "simple int" because you can't use "series int" in `t
a.ema()`.
EXAMPLE
//@version=6
// The `close` variable returns a "series float" value. Since `myVar` is restricted to "simple" values, it cannot
myVar := close
plot(myVar)
REMARKS
SEE ALSO
seriesconst
string
EXAMPLE
//@version=6
indicator("string")
plot(na, title=s)
REMARKS
SEE ALSO
varvaripintfloatboolstr.tostringstr.format
table
Keyword used to explicitly declare the "table" type of a variable or a parameter. Table
objects (or IDs) can be created with the table.new function.
EXAMPLE
//@version=6
indicator("table")
if barstate.islastconfirmedhistory
REMARKS
SEE ALSO
varlinelabelboxtable.new
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.
-=
SYNTAX
expr1 -= expr2
EXAMPLE
//@version=6
indicator("-=")
a=2
b=3
a -= b
// Result: a = -1.
plot(a)
RETURNS
:=
SYNTAX
<var_name> := <new_value>
EXAMPLE
//@version=6
indicator("My script")
myVar = 10
// Modifies the existing global scope `myVar` variable by changing its value from 10 to 20.
myVar := 20
// Creates a new `myVar` variable local to the `if` condition and unreachable from the global scope.
myVar = 30
plot(myVar)
!=
SYNTAX
expr1 != expr2
RETURNS
?:
SYNTAX
EXAMPLE
//@version=6
indicator("?:")
plot(hl2, color=c)
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("[]")
a := a[1] // immediately set current value to the same as previous. `na` in the beginning of history
a := low
plot(a)
RETURNS
A series of values.
SEE ALSO
math.floor
SYNTAX
expr1 * expr2
RETURNS
*=
SYNTAX
expr1 *= expr2
EXAMPLE
//@version=6
indicator("*=")
a=2
b=3
a *= b
// Result: a = 6.
plot(a)
RETURNS
SYNTAX
expr1 / expr2
RETURNS
/=
SYNTAX
expr1 /= expr2
EXAMPLE
//@version=6
indicator("/=")
float a = 3.0
b=3
a /= b
// Result: a = 1.
plot(a)
RETURNS
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.
%=
SYNTAX
expr1 %= expr2
EXAMPLE
//@version=6
indicator("%=")
a=3
b=3
a %= b
// Result: a = 0.
plot(a)
RETURNS
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.
+=
SYNTAX
expr1 += expr2
EXAMPLE
//@version=6
indicator("+=")
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.
<
SYNTAX
RETURNS
<=
SYNTAX
RETURNS
==
SYNTAX
expr1 == expr2
RETURNS
=>
SYNTAX
<local_block>
<function_result>
EXAMPLE
//@version=6
indicator("=>")
// single-line function
f1(x, y) => x + y
// multi-line function
f2(x, y) =>
sum = x + y
REMARKS
You can learn more about user-defined functions in the User Manual's pages
on Declaring functions and Libraries.
>
SYNTAX
RETURNS
Boolean value, or series of boolean values.
>=
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
library("MyLibrary")
@enum
If placed above an enum declaration, it adds a custom description for the enum. The
Pine Editor's autosuggest uses this description and displays it when a user hovers
over the enum name. When used in library scripts, the descriptions of all enums
using the export keyword will pre-fill the "Description" field in the publication
dialogue.
EXAMPLE
//@version=6
indicator("Session highlight", overlay = true)
//@field exch Has an empty string as the title to represent the chart timezone.
enum tz
utc = "UTC"
exch = ""
ny = "America/New_York"
chi = "America/Chicago"
lon = "Europe/London"
tok = "Asia/Tokyo"
//@variable The selected timezone. The input's dropdown contains the fields in the `tz` enum.
inSession := 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
//@field index The index of the bar where the point is located, i.e., its `x` coordinate.
//@field price The price where the point is located, i.e., its `y` coordinate.
type Point
int index
float price
//@variable If the current `high` is the highest over the last 20 bars, returns a new `Point` instance, `na` ot
herwise.
Point highest = na
if ta.highestbars(high, 20) == 0
@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
library("MyLibrary")
@param
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
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
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
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
@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
//@field index The index of the bar where the point is located, i.e., its `x` coordinate.
//@field price The price where the point is located, i.e., its `y` coordinate.
type Point
int index
float price
//@variable If the current `high` is the highest over the last 20 bars, returns a new `Point` instance, `na` ot
herwise.
Point highest = na
if ta.highestbars(high, 20) == 0
@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
//@field index The index of the bar where the point is located, i.e., its `x` coordinate.
//@field price The price where the point is located, i.e., its `y` coordinate.
type Point
int index
float price
//@variable If the current `high` is the highest over the last 20 bars, returns a new `Point` instance, `na` ot
herwise.
Point highest = na
if ta.highestbars(high, 20) == 0
@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
//Pine Script® v1 has no function named `indicator()`, so the script will not compile.
indicator("Pine v1 Indicator")
plot(close)
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.