Pinescript v5 Manual
Pinescript v5 Manual
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.
It is NOT recommended to use barstate.isconfirmed in request.security expression. Its
value requested from request.security is unpredictable.
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
barstate.isfirstbarstate.islastbarstate.ishistorybarstate.isrealtimebarstate.isnewbarstate.islastconf
irmedhistory
barstate.isfirst
Returns true if current bar is first bar in barset, false otherwise.
TYPE
series bool
REMARKS
Pine Script® code that uses this variable could calculate differently on history and
real-time data.
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
barstate.islastbarstate.ishistorybarstate.isrealtimebarstate.isnewbarstate.isconfirmedbarstate.isla
stconfirmedhistory
barstate.ishistory
Returns true if current bar is a historical bar, false otherwise.
TYPE
series bool
REMARKS
Pine Script® code that uses this variable could calculate differently on history and
real-time data.
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
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
Returns true if current bar is a real-time bar, false otherwise.
TYPE
series bool
REMARKS
Pine Script® code that uses this variable could calculate differently on history and
real-time data.
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
barstate.isfirstbarstate.islastbarstate.ishistorybarstate.isnewbarstate.isconfirmedbarstate.islastco
nfirmedhistory
box.all
Returns an array filled with all the current boxes drawn by the script.
TYPE
array<box>
EXAMPLE
//@version=5
indicator("box.all")
//delete all boxes
box.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, border_style=line.style_d
ashed)
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
Returns the color of the chart's background from the "Chart
settings/Appearance/Background" field. When a gradient is selected, the middle point
of the gradient is returned.
TYPE
input color
SEE ALSO
chart.fg_color
chart.fg_color
Returns a color providing optimal contrast with chart.bg_color.
TYPE
input color
SEE ALSO
chart.bg_color
chart.is_heikinashi
TYPE
simple bool
RETURNS
Returns true if the chart type is Heikin Ashi, false otherwise.
SEE ALSO
chart.is_renkochart.is_linebreakchart.is_kagichart.is_pnfchart.is_range
chart.is_kagi
TYPE
simple bool
RETURNS
Returns true if the chart type is Kagi, false otherwise.
SEE ALSO
chart.is_renkochart.is_linebreakchart.is_heikinashichart.is_pnfchart.is_range
chart.is_linebreak
TYPE
simple bool
RETURNS
Returns true if the chart type is Line break, false otherwise.
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
Returns true if the chart type is Range, false otherwise.
SEE ALSO
chart.is_renkochart.is_linebreakchart.is_kagichart.is_pnfchart.is_heikinashi
chart.is_renko
TYPE
simple bool
RETURNS
Returns true if the chart type is Renko, false otherwise.
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 bars, candles, hollow candles, line, area or
baseline, false otherwise.
SEE ALSO
chart.is_renkochart.is_linebreakchart.is_kagichart.is_pnfchart.is_rangechart.is_heikinashi
chart.left_visible_bar_time
The time of the leftmost bar currently visible on the chart.
TYPE
input int
REMARKS
Scripts using this variable will automatically re-execute when its value updates to
reflect changes in the chart, which can be caused by users scrolling the chart, or new
real-time bars.
Alerts created on a script that includes this variable will only use the value assigned
to the variable at the moment of the alert's creation, regardless of whether the value
changes afterward, which may lead to repainting.
SEE ALSO
chart.right_visible_bar_time
chart.right_visible_bar_time
The time of the rightmost bar currently visible on the chart.
TYPE
input int
REMARKS
Scripts using this variable will automatically re-execute when its value updates to
reflect changes in the chart, which can be caused by users scrolling the chart, or new
real-time bars.
Alerts created on a script that includes this variable will only use the value assigned
to the variable at the moment of the alert's creation, regardless of whether the value
changes afterward, which may lead to repainting.
SEE ALSO
chart.left_visible_bar_time
close
Close price of the current bar when it has closed, or last traded price of a yet
incomplete, realtime bar.
TYPE
series float
REMARKS
Previous values may be accessed with square brackets operator [], e.g. close[1],
close[2].
SEE ALSO
openhighlowvolumetimehl2hlc3hlcc4ohlc4
dayofmonth
Date of current bar time in exchange timezone.
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
Day of week for current bar time in exchange timezone.
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
UNIX time, expressed in milliseconds.
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
UNIX time, expressed in milliseconds.
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
UNIX time, expressed in milliseconds.
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
UNIX time, expressed in milliseconds.
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
Current high price.
TYPE
series float
REMARKS
Previous values may be accessed with square brackets operator [], e.g. high[1],
high[2].
SEE ALSO
openlowclosevolumetimehl2hlc3hlcc4ohlc4
hl2
Is a shortcut for (high + low)/2
TYPE
series float
SEE ALSO
openhighlowclosevolumetimehlc3hlcc4ohlc4
hlc3
Is a shortcut for (high + low + close)/3
TYPE
series float
SEE ALSO
openhighlowclosevolumetimehl2hlcc4ohlc4
hlcc4
Is a shortcut for (high + low + close + close)/4
TYPE
series float
SEE ALSO
openhighlowclosevolumetimehl2hlc3ohlc4
hour
Current bar hour in exchange timezone.
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=5
indicator("label.all")
//delete all labels
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=5
strategy("Mark Last X Bars For Backtesting", overlay = true, calc_on_every_tick = true)
lastBarsFilterInput = input.int(100, "Bars Count:")
// Here, we store the 'last_bar_index' value that is known from the beginning of the script's
calculation.
// The 'last_bar_index' will change when new real-
time bars appear, so we declare 'lastbar' with the 'var' keyword.
var lastbar = last_bar_index
// Check if the current bar_index is 'lastBarsFilterInput' removed from the last bar on the c
hart, or the chart is traded in real-time.
allowedToTrade = (lastbar - bar_index <= lastBarsFilterInput) or barstate.isrealtime
bgcolor(allowedToTrade ? color.new(color.green, 80) : na)
RETURNS
Last historical bar index for closed markets, or the real-time bar index for open
markets.
REMARKS
Please note that using this variable can cause indicator repainting.
SEE ALSO
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=5
indicator("line.all")
//delete all lines
line.new(bar_index - 10, close, bar_index, close)
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
Current low price.
TYPE
series float
REMARKS
Previous values may be accessed with square brackets operator [], e.g. low[1],
low[2].
SEE ALSO
openhighclosevolumetimehl2hlc3hlcc4ohlc4
minute
Current bar minute in exchange timezone.
TYPE
series int
SEE ALSO
minutetimeyearmonthweekofyeardayofmonthdayofweekhoursecond
month
Current bar month in exchange timezone.
TYPE
series int
REMARKS
Note that this variable returns the month based on the time of the bar's open. For
overnight sessions (e.g. EURUSD, where Monday session starts on Sunday, 17:00) this
value can be lower by 1 than the month of the trading day.
SEE ALSO
monthtimeyearweekofyeardayofmonthdayofweekhourminutesecond
na
A keyword signifying "not available", indicating that a variable has no assigned value.
TYPE
simple na
EXAMPLE
//@version=5
indicator("na")
// CORRECT
// Plot no value when on bars zero to nine. Plot `close` on other bars.
plot(bar_index < 10 ? na : close)
// CORRECT ALTERNATIVE
// Initialize `a` to `na`. Reassign `close` to `a` on bars 10 and later.
float a = na
if bar_index >= 10
a := close
plot(a)
// INCORRECT
// Trying to test the preceding bar's `close` for `na`.
// Will not work correctly on bar zero, when `close[1]` is `na`.
plot(close[1] == na ? close : close[1])
// CORRECT
// Use the `na()` function to test for `na`.
plot(na(close[1]) ? close : close[1])
// CORRECT ALTERNATIVE
// `nz()` tests `close[1]` for `na`. It returns `close[1]` if it is not `na`, and `close` if
it is.
plot(nz(close[1], close))
REMARKS
Do not use this variable with comparison operators to test values for na, as it might
lead to unexpected behavior. Instead, use the na function. Note that na can be used
to initialize variables when the initialization statement also specifies the variable's
type.
SEE ALSO
nanzfixnan
ohlc4
Is a shortcut for (open + high + low + close)/4
TYPE
series float
SEE ALSO
openhighlowclosevolumetimehl2hlc3hlcc4
open
Current open price.
TYPE
series float
REMARKS
Previous values may be accessed with square brackets operator [], e.g. open[1],
open[2].
SEE ALSO
highlowclosevolumetimehl2hlc3hlcc4ohlc4
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
Current bar second in exchange timezone.
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=5
strategy("`session.isfirstbar` Example", overlay = true)
longCondition = year >= 2022
// Place a long order at the `close` of the trading session's first bar.
if session.isfirstbar and longCondition
strategy.entry("Long", strategy.long)
// Close the long position at the `close` of the trading session's last bar.
if session.islastbar and barstate.isconfirmed
strategy.close("Long", immediately = true)
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=5
strategy("`session.isfirstbar_regular` Example", overlay = true)
longCondition = year >= 2022
// Place a long order at the `close` of the trading session's first bar.
if session.isfirstbar and longCondition
strategy.entry("Long", strategy.long)
// Close the long position at the `close` of the trading session's last bar.
if session.islastbar_regular and barstate.isconfirmed
strategy.close("Long", immediately = true)
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=5
strategy("`session.islastbar` Example", overlay = true)
longCondition = year >= 2022
// Place a long order at the `close` of the trading session's last bar.
// The position will enter on the `open` of next session's first bar.
if session.islastbar and longCondition
strategy.entry("Long", strategy.long)
// Close 'Long' position at the close of the last bar of the trading session
if session.islastbar and barstate.isconfirmed
strategy.close("Long", immediately = true)
REMARKS
This variable is not guaranteed to return true once in every session because the last
bar of the session might not exist if no trades occur during what should be the
session's last bar.
This variable is not guaranteed to work as expected on non-standard chart types,
e.g., Renko.
SEE ALSO
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=5
strategy("`session.islastbar_regular` Example", overlay = true)
longCondition = year >= 2022
// Place a long order at the `close` of the trading session's first bar.
if session.isfirstbar and longCondition
strategy.entry("Long", strategy.long)
// Close the long position at the `close` of the trading session's last bar.
if session.islastbar_regular and barstate.isconfirmed
strategy.close("Long", immediately = true)
REMARKS
This variable is not guaranteed to return true once in every session because the last
bar of the session might not exist if no trades occur during what should be the
session's last bar.
This variable is not guaranteed to work as expected on non-standard chart types,
e.g., Renko.
SEE ALSO
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 interval.
TYPE
series int
SEE ALSO
strategy.position_sizestrategy.opentradesstrategy.wintradesstrategy.losstradesstrategy.eventrade
s
strategy.equity
Current equity (strategy.initial_capital + strategy.netprofit + strategy.openprofit).
TYPE
series float
SEE ALSO
strategy.netprofitstrategy.openprofitstrategy.position_size
strategy.eventrades
Number of breakeven trades for the whole trading interval.
TYPE
series int
SEE ALSO
strategy.position_sizestrategy.opentradesstrategy.closedtradesstrategy.wintradesstrategy.losstrad
es
strategy.grossloss
Total currency value of all completed losing trades.
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
Total currency value of all completed winning trades.
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
The amount of initial capital set in the strategy properties.
TYPE
series float
SEE ALSO
strategy
strategy.losstrades
Number of unprofitable trades for the whole trading interval.
TYPE
series int
SEE ALSO
strategy.position_sizestrategy.opentradesstrategy.closedtradesstrategy.wintradesstrategy.eventra
des
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=5
strategy("Margin call management", overlay = true, margin_long = 25, margin_short = 25,
default_qty_type = strategy.percent_of_equity, default_qty_value = 395)
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.
if math.abs(changePercent(close, strategy.margin_liquidation_price)) <= 10
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
Maximum number of contracts/shares/lots/units in one trade for the whole trading
interval.
TYPE
series float
SEE ALSO
strategy.position_sizestrategy.max_contracts_held_longstrategy.max_contracts_held_short
strategy.max_contracts_held_long
Maximum number of contracts/shares/lots/units in one long trade for the whole
trading interval.
TYPE
series float
SEE ALSO
strategy.position_sizestrategy.max_contracts_held_allstrategy.max_contracts_held_short
strategy.max_contracts_held_short
Maximum number of contracts/shares/lots/units in one short trade for the whole
trading interval.
TYPE
series float
SEE ALSO
strategy.position_sizestrategy.max_contracts_held_allstrategy.max_contracts_held_long
strategy.max_drawdown
Maximum equity drawdown value for the whole trading interval.
TYPE
series float
SEE ALSO
strategy.netprofitstrategy.equitystrategy.max_runup
strategy.max_drawdown_percent
The maximum equity drawdown value for the whole trading interval, expressed as a
percentage and calculated by formula: Lowest Value During Trade / (Entry
Price x Quantity) * 100.
TYPE
series float
SEE ALSO
strategy.max_drawdown
strategy.max_runup
Maximum equity run-up value for the whole trading interval.
TYPE
series float
SEE ALSO
strategy.netprofitstrategy.equitystrategy.max_drawdown
strategy.max_runup_percent
The maximum equity run-up value for the whole trading interval, 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
Total currency value of all completed trades.
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
Current unrealized profit or loss for all open positions.
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
Returns the capital amount currently held by open trades.
TYPE
series float
EXAMPLE
//@version=5
strategy(
"strategy.opentrades.capital_held example", overlay=false, margin_long=50, margin_short=5
0,
default_qty_type = strategy.percent_of_equity, default_qty_value = 100
)
strategy.position_entry_name
Name of the order that initially opened current market position.
TYPE
series string
SEE ALSO
strategy.position_size
strategy.position_size
Direction and size of the current market position. If the value is > 0, the market
position is long. If the value is < 0, the market position is short. The absolute value is
the number of contracts/shares/lots/units in trade (position size).
TYPE
series float
SEE ALSO
strategy.position_avg_price
strategy.wintrades
Number of profitable trades for the whole trading interval.
TYPE
series int
SEE ALSO
strategy.position_sizestrategy.opentradesstrategy.closedtradesstrategy.losstradesstrategy.eventra
des
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
Description for the current symbol.
TYPE
simple string
SEE ALSO
syminfo.tickersyminfo.prefix
syminfo.employees
The number of employees the company has.
TYPE
simple int
EXAMPLE
//@version=5
indicator("syminfo simple")
//@variable A table containing information about a company's employees, shareholders, and sha
res.
var result_table = table.new(position = position.top_right, columns = 2, rows = 5, border_wid
th = 1)
if barstate.islastconfirmedhistory
// Add header cells
table.cell(table_id = result_table, column = 0, row = 0, text = "name")
table.cell(table_id = result_table, column = 1, row = 0, text = "value")
// Add employee info cells.
table.cell(table_id = result_table, column = 0, row = 1, text = "employees")
table.cell(table_id = result_table, column = 1, row = 1, text = str.tostring(syminfo.empl
oyees))
// Add shareholder cells.
table.cell(table_id = result_table, column = 0, row = 2, text = "shareholders")
table.cell(table_id = result_table, column = 1, row = 2, text = str.tostring(syminfo.shar
eholders))
// Add float shares outstanding cells.
table.cell(table_id = result_table, column = 0, row = 3, text = "shares_outstanding_float
")
table.cell(table_id = result_table, column = 1, row = 3, text = str.tostring(syminfo.shar
es_outstanding_float))
// Add total shares outstanding cells.
table.cell(table_id = result_table, column = 0, row = 4, text = "shares_outstanding_total
")
table.cell(table_id = result_table, column = 1, row = 4, text = str.tostring(syminfo.shar
es_outstanding_total))
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
A sector is a broad section of the economy. An industry is a narrower classification.
NASDAQ:CAT (Caterpillar, Inc.) for example, belongs to the "Producer Manufacturing"
sector and the "Trucks/Construction/Farm Machinery" industry.
syminfo.minmove
Returns a whole number used to calculate the smallest increment between a symbol's
price movements (syminfo.mintick). It is the numerator in
the syminfo.mintick formula: syminfo.minmove / syminfo.pricescale =
syminfo.mintick.
TYPE
simple int
SEE ALSO
ticker.newsyminfo.tickertimeframe.periodtimeframe.multipliersyminfo.root
syminfo.mintick
Min tick value for the current symbol.
TYPE
simple float
SEE ALSO
syminfo.pointvalue
syminfo.pointvalue
Point value for the current symbol.
TYPE
simple float
SEE ALSO
syminfo.mintick
syminfo.prefix
Prefix of current symbol name (i.e. for 'CME_EOD:TICKER' prefix is 'CME_EOD').
TYPE
simple string
EXAMPLE
//@version=5
indicator("syminfo.prefix")
syminfo.pricescale
Returns a whole number used to calculate the smallest increment between a symbol's
price movements (syminfo.mintick). It is the denominator in
the syminfo.mintick formula: syminfo.minmove / syminfo.pricescale =
syminfo.mintick.
TYPE
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=5
indicator("syminfo recommendations", overlay = true)
//@variable A table containing information about analyst recommendations.
var table ratings = table.new(position.top_right, 8, 2, frame_color = #000000)
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
// Add header cells.
table.cell(ratings, 0, 0, "Start Date", bgcolor = color.gray, text_color = #000000, text_
size = size.large)
table.cell(ratings, 1, 0, "End Date", bgcolor = color.gray, text_color = #000000, text_si
ze = size.large)
table.cell(ratings, 2, 0, "Buy", bgcolor = color.teal, text_color = #000000, text_size =
size.large)
table.cell(ratings, 3, 0, "Strong Buy", bgcolor = color.lime, text_color = #000000, text_
size = size.large)
table.cell(ratings, 4, 0, "Sell", bgcolor = color.maroon, text_color = #000000, text_size
= size.large)
table.cell(ratings, 5, 0, "Strong Sell", bgcolor = color.red, text_color = #000000, text_
size = size.large)
table.cell(ratings, 6, 0, "Hold", bgcolor = color.orange, text_color = #000000, text_size
= size.large)
table.cell(ratings, 7, 0, "Total", bgcolor = color.silver, text_color = #000000, text_siz
e = size.large)
// Recommendation strings
string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd")
string endDate = str.format_time(YTD, "yyyy-MM-dd")
string buyRatings = str.tostring(syminfo.recommendations_buy)
string strongBuyRatings = str.tostring(syminfo.recommendations_buy_strong)
string sellRatings = str.tostring(syminfo.recommendations_sell)
string strongSellRatings = str.tostring(syminfo.recommendations_sell_strong)
string holdRatings = str.tostring(syminfo.recommendations_hold)
string totalRatings = str.tostring(syminfo.recommendations_total)
// Add value cells
table.cell(ratings, 0, 1, startDate, bgcolor = color.gray, text_color = #000000, text_siz
e = size.large)
table.cell(ratings, 1, 1, endDate, bgcolor = color.gray, text_color = #000000, text_size
= size.large)
table.cell(ratings, 2, 1, buyRatings, bgcolor = color.teal, text_color = #000000, text_si
ze = size.large)
table.cell(ratings, 3, 1, strongBuyRatings, bgcolor = color.lime, text_color = #000000, t
ext_size = size.large)
table.cell(ratings, 4, 1, sellRatings, bgcolor = color.maroon, text_color = #000000, text
_size = size.large)
SEE ALSO
syminfo.recommendations_buy_strongsyminfo.recommendations_datesyminfo.recommendations_h
oldsyminfo.recommendations_totalsyminfo.recommendations_sellsyminfo.recommendations_sell_s
trong
syminfo.recommendations_buy_strong
The number of analysts who gave the current symbol a "Strong Buy" rating.
TYPE
series int
EXAMPLE
//@version=5
indicator("syminfo recommendations", overlay = true)
//@variable A table containing information about analyst recommendations.
var table ratings = table.new(position.top_right, 8, 2, frame_color = #000000)
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
// Add header cells.
table.cell(ratings, 0, 0, "Start Date", bgcolor = color.gray, text_color = #000000, text_
size = size.large)
table.cell(ratings, 1, 0, "End Date", bgcolor = color.gray, text_color = #000000, text_si
ze = size.large)
table.cell(ratings, 2, 0, "Buy", bgcolor = color.teal, text_color = #000000, text_size =
size.large)
table.cell(ratings, 3, 0, "Strong Buy", bgcolor = color.lime, text_color = #000000, text_
size = size.large)
table.cell(ratings, 4, 0, "Sell", bgcolor = color.maroon, text_color = #000000, text_size
= size.large)
table.cell(ratings, 5, 0, "Strong Sell", bgcolor = color.red, text_color = #000000, text_
size = size.large)
table.cell(ratings, 6, 0, "Hold", bgcolor = color.orange, text_color = #000000, text_size
= size.large)
table.cell(ratings, 7, 0, "Total", bgcolor = color.silver, text_color = #000000, text_siz
e = size.large)
// Recommendation strings
string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd")
string endDate = str.format_time(YTD, "yyyy-MM-dd")
string buyRatings = str.tostring(syminfo.recommendations_buy)
string strongBuyRatings = str.tostring(syminfo.recommendations_buy_strong)
string sellRatings = str.tostring(syminfo.recommendations_sell)
string strongSellRatings = str.tostring(syminfo.recommendations_sell_strong)
string holdRatings = str.tostring(syminfo.recommendations_hold)
string totalRatings = str.tostring(syminfo.recommendations_total)
// Add value cells
table.cell(ratings, 0, 1, startDate, bgcolor = color.gray, text_color = #000000, text_siz
e = size.large)
table.cell(ratings, 1, 1, endDate, bgcolor = color.gray, text_color = #000000, text_size
= size.large)
table.cell(ratings, 2, 1, buyRatings, bgcolor = color.teal, text_color = #000000, text_si
ze = size.large)
table.cell(ratings, 3, 1, strongBuyRatings, bgcolor = color.lime, text_color = #000000, t
ext_size = size.large)
table.cell(ratings, 4, 1, sellRatings, bgcolor = color.maroon, text_color = #000000, text
_size = size.large)
SEE ALSO
syminfo.recommendations_buysyminfo.recommendations_datesyminfo.recommendations_holdsymi
nfo.recommendations_totalsyminfo.recommendations_sellsyminfo.recommendations_sell_strong
syminfo.recommendations_date
The starting date of the last set of recommendations for the current symbol.
TYPE
series int
EXAMPLE
//@version=5
indicator("syminfo recommendations", overlay = true)
//@variable A table containing information about analyst recommendations.
var table ratings = table.new(position.top_right, 8, 2, frame_color = #000000)
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
// Add header cells.
table.cell(ratings, 0, 0, "Start Date", bgcolor = color.gray, text_color = #000000, text_
size = size.large)
table.cell(ratings, 1, 0, "End Date", bgcolor = color.gray, text_color = #000000, text_si
ze = size.large)
table.cell(ratings, 2, 0, "Buy", bgcolor = color.teal, text_color = #000000, text_size =
size.large)
table.cell(ratings, 3, 0, "Strong Buy", bgcolor = color.lime, text_color = #000000, text_
size = size.large)
table.cell(ratings, 4, 0, "Sell", bgcolor = color.maroon, text_color = #000000, text_size
= size.large)
table.cell(ratings, 5, 0, "Strong Sell", bgcolor = color.red, text_color = #000000, text_
size = size.large)
table.cell(ratings, 6, 0, "Hold", bgcolor = color.orange, text_color = #000000, text_size
= size.large)
table.cell(ratings, 7, 0, "Total", bgcolor = color.silver, text_color = #000000, text_siz
e = size.large)
// Recommendation strings
string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd")
string endDate = str.format_time(YTD, "yyyy-MM-dd")
string buyRatings = str.tostring(syminfo.recommendations_buy)
string strongBuyRatings = str.tostring(syminfo.recommendations_buy_strong)
string sellRatings = str.tostring(syminfo.recommendations_sell)
string strongSellRatings = str.tostring(syminfo.recommendations_sell_strong)
string holdRatings = str.tostring(syminfo.recommendations_hold)
string totalRatings = str.tostring(syminfo.recommendations_total)
// Add value cells
table.cell(ratings, 0, 1, startDate, bgcolor = color.gray, text_color = #000000, text_siz
e = size.large)
table.cell(ratings, 1, 1, endDate, bgcolor = color.gray, text_color = #000000, text_size
= size.large)
table.cell(ratings, 2, 1, buyRatings, bgcolor = color.teal, text_color = #000000, text_si
ze = size.large)
table.cell(ratings, 3, 1, strongBuyRatings, bgcolor = color.lime, text_color = #000000, t
ext_size = size.large)
table.cell(ratings, 4, 1, sellRatings, bgcolor = color.maroon, text_color = #000000, text
_size = size.large)
SEE ALSO
syminfo.recommendations_buysyminfo.recommendations_buy_strongsyminfo.recommendations_ho
ldsyminfo.recommendations_totalsyminfo.recommendations_sellsyminfo.recommendations_sell_st
rong
syminfo.recommendations_hold
The number of analysts who gave the current symbol a "Hold" rating.
TYPE
series int
EXAMPLE
//@version=5
indicator("syminfo recommendations", overlay = true)
//@variable A table containing information about analyst recommendations.
var table ratings = table.new(position.top_right, 8, 2, frame_color = #000000)
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
// Add header cells.
table.cell(ratings, 0, 0, "Start Date", bgcolor = color.gray, text_color = #000000, text_
size = size.large)
table.cell(ratings, 1, 0, "End Date", bgcolor = color.gray, text_color = #000000, text_si
ze = size.large)
table.cell(ratings, 2, 0, "Buy", bgcolor = color.teal, text_color = #000000, text_size =
size.large)
table.cell(ratings, 3, 0, "Strong Buy", bgcolor = color.lime, text_color = #000000, text_
size = size.large)
table.cell(ratings, 4, 0, "Sell", bgcolor = color.maroon, text_color = #000000, text_size
= size.large)
table.cell(ratings, 5, 0, "Strong Sell", bgcolor = color.red, text_color = #000000, text_
size = size.large)
table.cell(ratings, 6, 0, "Hold", bgcolor = color.orange, text_color = #000000, text_size
= size.large)
table.cell(ratings, 7, 0, "Total", bgcolor = color.silver, text_color = #000000, text_siz
e = size.large)
// Recommendation strings
string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd")
string endDate = str.format_time(YTD, "yyyy-MM-dd")
string buyRatings = str.tostring(syminfo.recommendations_buy)
string strongBuyRatings = str.tostring(syminfo.recommendations_buy_strong)
string sellRatings = str.tostring(syminfo.recommendations_sell)
string strongSellRatings = str.tostring(syminfo.recommendations_sell_strong)
string holdRatings = str.tostring(syminfo.recommendations_hold)
string totalRatings = str.tostring(syminfo.recommendations_total)
// Add value cells
table.cell(ratings, 0, 1, startDate, bgcolor = color.gray, text_color = #000000, text_siz
e = size.large)
table.cell(ratings, 1, 1, endDate, bgcolor = color.gray, text_color = #000000, text_size
= size.large)
table.cell(ratings, 2, 1, buyRatings, bgcolor = color.teal, text_color = #000000, text_si
ze = size.large)
table.cell(ratings, 3, 1, strongBuyRatings, bgcolor = color.lime, text_color = #000000, t
ext_size = size.large)
table.cell(ratings, 4, 1, sellRatings, bgcolor = color.maroon, text_color = #000000, text
_size = size.large)
SEE ALSO
syminfo.recommendations_buysyminfo.recommendations_buy_strongsyminfo.recommendations_da
tesyminfo.recommendations_totalsyminfo.recommendations_sellsyminfo.recommendations_sell_st
rong
syminfo.recommendations_sell
The number of analysts who gave the current symbol a "Sell" rating.
TYPE
series int
EXAMPLE
//@version=5
indicator("syminfo recommendations", overlay = true)
//@variable A table containing information about analyst recommendations.
var table ratings = table.new(position.top_right, 8, 2, frame_color = #000000)
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
// Add header cells.
table.cell(ratings, 0, 0, "Start Date", bgcolor = color.gray, text_color = #000000, text_
size = size.large)
table.cell(ratings, 1, 0, "End Date", bgcolor = color.gray, text_color = #000000, text_si
ze = size.large)
table.cell(ratings, 2, 0, "Buy", bgcolor = color.teal, text_color = #000000, text_size =
size.large)
table.cell(ratings, 3, 0, "Strong Buy", bgcolor = color.lime, text_color = #000000, text_
size = size.large)
table.cell(ratings, 4, 0, "Sell", bgcolor = color.maroon, text_color = #000000, text_size
= size.large)
table.cell(ratings, 5, 0, "Strong Sell", bgcolor = color.red, text_color = #000000, text_
size = size.large)
table.cell(ratings, 6, 0, "Hold", bgcolor = color.orange, text_color = #000000, text_size
= size.large)
table.cell(ratings, 7, 0, "Total", bgcolor = color.silver, text_color = #000000, text_siz
e = size.large)
// Recommendation strings
string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd")
string endDate = str.format_time(YTD, "yyyy-MM-dd")
string buyRatings = str.tostring(syminfo.recommendations_buy)
string strongBuyRatings = str.tostring(syminfo.recommendations_buy_strong)
string sellRatings = str.tostring(syminfo.recommendations_sell)
string strongSellRatings = str.tostring(syminfo.recommendations_sell_strong)
string holdRatings = str.tostring(syminfo.recommendations_hold)
string totalRatings = str.tostring(syminfo.recommendations_total)
// Add value cells
table.cell(ratings, 0, 1, startDate, bgcolor = color.gray, text_color = #000000, text_siz
e = size.large)
table.cell(ratings, 1, 1, endDate, bgcolor = color.gray, text_color = #000000, text_size
= size.large)
table.cell(ratings, 2, 1, buyRatings, bgcolor = color.teal, text_color = #000000, text_si
ze = size.large)
table.cell(ratings, 3, 1, strongBuyRatings, bgcolor = color.lime, text_color = #000000, t
ext_size = size.large)
table.cell(ratings, 4, 1, sellRatings, bgcolor = color.maroon, text_color = #000000, text
_size = size.large)
SEE ALSO
syminfo.recommendations_buysyminfo.recommendations_buy_strongsyminfo.recommendations_da
tesyminfo.recommendations_holdsyminfo.recommendations_totalsyminfo.recommendations_sell_s
trong
syminfo.recommendations_sell_strong
The number of analysts who gave the current symbol a "Strong Sell" rating.
TYPE
series int
EXAMPLE
//@version=5
indicator("syminfo recommendations", overlay = true)
//@variable A table containing information about analyst recommendations.
var table ratings = table.new(position.top_right, 8, 2, frame_color = #000000)
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
// Add header cells.
table.cell(ratings, 0, 0, "Start Date", bgcolor = color.gray, text_color = #000000, text_
size = size.large)
table.cell(ratings, 1, 0, "End Date", bgcolor = color.gray, text_color = #000000, text_si
ze = size.large)
table.cell(ratings, 2, 0, "Buy", bgcolor = color.teal, text_color = #000000, text_size =
size.large)
table.cell(ratings, 3, 0, "Strong Buy", bgcolor = color.lime, text_color = #000000, text_
size = size.large)
table.cell(ratings, 4, 0, "Sell", bgcolor = color.maroon, text_color = #000000, text_size
= size.large)
table.cell(ratings, 5, 0, "Strong Sell", bgcolor = color.red, text_color = #000000, text_
size = size.large)
table.cell(ratings, 6, 0, "Hold", bgcolor = color.orange, text_color = #000000, text_size
= size.large)
table.cell(ratings, 7, 0, "Total", bgcolor = color.silver, text_color = #000000, text_siz
e = size.large)
// Recommendation strings
string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd")
string endDate = str.format_time(YTD, "yyyy-MM-dd")
string buyRatings = str.tostring(syminfo.recommendations_buy)
string strongBuyRatings = str.tostring(syminfo.recommendations_buy_strong)
string sellRatings = str.tostring(syminfo.recommendations_sell)
string strongSellRatings = str.tostring(syminfo.recommendations_sell_strong)
string holdRatings = str.tostring(syminfo.recommendations_hold)
string totalRatings = str.tostring(syminfo.recommendations_total)
// Add value cells
table.cell(ratings, 0, 1, startDate, bgcolor = color.gray, text_color = #000000, text_siz
e = size.large)
table.cell(ratings, 1, 1, endDate, bgcolor = color.gray, text_color = #000000, text_size
= size.large)
table.cell(ratings, 2, 1, buyRatings, bgcolor = color.teal, text_color = #000000, text_si
ze = size.large)
table.cell(ratings, 3, 1, strongBuyRatings, bgcolor = color.lime, text_color = #000000, t
ext_size = size.large)
table.cell(ratings, 4, 1, sellRatings, bgcolor = color.maroon, text_color = #000000, text
_size = size.large)
SEE ALSO
syminfo.recommendations_buysyminfo.recommendations_buy_strongsyminfo.recommendations_da
tesyminfo.recommendations_holdsyminfo.recommendations_totalsyminfo.recommendations_sell
syminfo.recommendations_total
The total number of recommendations for the current symbol.
TYPE
series int
EXAMPLE
//@version=5
indicator("syminfo recommendations", overlay = true)
//@variable A table containing information about analyst recommendations.
var table ratings = table.new(position.top_right, 8, 2, frame_color = #000000)
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
// Add header cells.
table.cell(ratings, 0, 0, "Start Date", bgcolor = color.gray, text_color = #000000, text_
size = size.large)
table.cell(ratings, 1, 0, "End Date", bgcolor = color.gray, text_color = #000000, text_si
ze = size.large)
table.cell(ratings, 2, 0, "Buy", bgcolor = color.teal, text_color = #000000, text_size =
size.large)
table.cell(ratings, 3, 0, "Strong Buy", bgcolor = color.lime, text_color = #000000, text_
size = size.large)
table.cell(ratings, 4, 0, "Sell", bgcolor = color.maroon, text_color = #000000, text_size
= size.large)
table.cell(ratings, 5, 0, "Strong Sell", bgcolor = color.red, text_color = #000000, text_
size = size.large)
table.cell(ratings, 6, 0, "Hold", bgcolor = color.orange, text_color = #000000, text_size
= size.large)
table.cell(ratings, 7, 0, "Total", bgcolor = color.silver, text_color = #000000, text_siz
e = size.large)
// Recommendation strings
string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd")
string endDate = str.format_time(YTD, "yyyy-MM-dd")
string buyRatings = str.tostring(syminfo.recommendations_buy)
string strongBuyRatings = str.tostring(syminfo.recommendations_buy_strong)
string sellRatings = str.tostring(syminfo.recommendations_sell)
string strongSellRatings = str.tostring(syminfo.recommendations_sell_strong)
string holdRatings = str.tostring(syminfo.recommendations_hold)
string totalRatings = str.tostring(syminfo.recommendations_total)
// Add value cells
table.cell(ratings, 0, 1, startDate, bgcolor = color.gray, text_color = #000000, text_siz
e = size.large)
table.cell(ratings, 1, 1, endDate, bgcolor = color.gray, text_color = #000000, text_size
= size.large)
table.cell(ratings, 2, 1, buyRatings, bgcolor = color.teal, text_color = #000000, text_si
ze = size.large)
table.cell(ratings, 3, 1, strongBuyRatings, bgcolor = color.lime, text_color = #000000, t
ext_size = size.large)
table.cell(ratings, 4, 1, sellRatings, bgcolor = color.maroon, text_color = #000000, text
_size = size.large)
SEE ALSO
syminfo.recommendations_buysyminfo.recommendations_buy_strongsyminfo.recommendations_da
tesyminfo.recommendations_holdsyminfo.recommendations_sellsyminfo.recommendations_sell_st
rong
syminfo.root
Root for derivatives like futures contract. For other symbols returns the same value
as syminfo.ticker.
TYPE
simple string
EXAMPLE
//@version=5
indicator("syminfo.root")
// If the current chart symbol is continuous futures ('ES1!'), it would display 'ES'.
if barstate.islastconfirmedhistory
label.new(bar_index, high, syminfo.root)
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
A sector is a broad section of the economy. An industry is a narrower classification.
NASDAQ:CAT (Caterpillar, Inc.) for example, belongs to the "Producer Manufacturing"
sector and the "Trucks/Construction/Farm Machinery" industry.
syminfo.session
Session type of the chart main series. Possible values
are session.regular, session.extended.
TYPE
simple string
SEE ALSO
session.regularsession.extended
syminfo.shareholders
The number of shareholders the company has.
TYPE
simple int
EXAMPLE
//@version=5
indicator("syminfo simple")
//@variable A table containing information about a company's employees, shareholders, and sha
res.
var result_table = table.new(position = position.top_right, columns = 2, rows = 5, border_wid
th = 1)
if barstate.islastconfirmedhistory
// Add header cells
table.cell(table_id = result_table, column = 0, row = 0, text = "name")
table.cell(table_id = result_table, column = 1, row = 0, text = "value")
// Add employee info cells.
table.cell(table_id = result_table, column = 0, row = 1, text = "employees")
table.cell(table_id = result_table, column = 1, row = 1, text = str.tostring(syminfo.empl
oyees))
// Add shareholder cells.
table.cell(table_id = result_table, column = 0, row = 2, text = "shareholders")
table.cell(table_id = result_table, column = 1, row = 2, text = str.tostring(syminfo.shar
eholders))
// Add float shares outstanding cells.
table.cell(table_id = result_table, column = 0, row = 3, text = "shares_outstanding_float
")
table.cell(table_id = result_table, column = 1, row = 3, text = str.tostring(syminfo.shar
es_outstanding_float))
// Add total shares outstanding cells.
table.cell(table_id = result_table, column = 0, row = 4, text = "shares_outstanding_total
")
table.cell(table_id = result_table, column = 1, row = 4, text = str.tostring(syminfo.shar
es_outstanding_total))
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=5
indicator("syminfo simple")
//@variable A table containing information about a company's employees, shareholders, and sha
res.
var result_table = table.new(position = position.top_right, columns = 2, rows = 5, border_wid
th = 1)
if barstate.islastconfirmedhistory
// Add header cells
table.cell(table_id = result_table, column = 0, row = 0, text = "name")
table.cell(table_id = result_table, column = 1, row = 0, text = "value")
// Add employee info cells.
table.cell(table_id = result_table, column = 0, row = 1, text = "employees")
table.cell(table_id = result_table, column = 1, row = 1, text = str.tostring(syminfo.empl
oyees))
// Add shareholder cells.
table.cell(table_id = result_table, column = 0, row = 2, text = "shareholders")
table.cell(table_id = result_table, column = 1, row = 2, text = str.tostring(syminfo.shar
eholders))
// Add float shares outstanding cells.
table.cell(table_id = result_table, column = 0, row = 3, text = "shares_outstanding_float
")
table.cell(table_id = result_table, column = 1, row = 3, text = str.tostring(syminfo.shar
es_outstanding_float))
// Add total shares outstanding cells.
table.cell(table_id = result_table, column = 0, row = 4, text = "shares_outstanding_total
")
table.cell(table_id = result_table, column = 1, row = 4, text = str.tostring(syminfo.shar
es_outstanding_total))
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=5
indicator("syminfo simple")
//@variable A table containing information about a company's employees, shareholders, and sha
res.
var result_table = table.new(position = position.top_right, columns = 2, rows = 5, border_wid
th = 1)
if barstate.islastconfirmedhistory
// Add header cells
table.cell(table_id = result_table, column = 0, row = 0, text = "name")
table.cell(table_id = result_table, column = 1, row = 0, text = "value")
// Add employee info cells.
table.cell(table_id = result_table, column = 0, row = 1, text = "employees")
table.cell(table_id = result_table, column = 1, row = 1, text = str.tostring(syminfo.empl
oyees))
// Add shareholder cells.
table.cell(table_id = result_table, column = 0, row = 2, text = "shareholders")
table.cell(table_id = result_table, column = 1, row = 2, text = str.tostring(syminfo.shar
eholders))
// Add float shares outstanding cells.
table.cell(table_id = result_table, column = 0, row = 3, text = "shares_outstanding_float
")
table.cell(table_id = result_table, column = 1, row = 3, text = str.tostring(syminfo.shar
es_outstanding_float))
// Add total shares outstanding cells.
table.cell(table_id = result_table, column = 0, row = 4, text = "shares_outstanding_total
")
table.cell(table_id = result_table, column = 1, row = 4, text = str.tostring(syminfo.shar
es_outstanding_total))
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=5
indicator("syminfo target_price")
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
//@variable A line connecting the current `close` to the highest yearly price estimate.
highLine = line.new(time, close, YTD, syminfo.target_price_high, color = color.green, xlo
c = xloc.bar_time)
//@variable A line connecting the current `close` to the lowest yearly price estimate.
lowLine = line.new(time, close, YTD, syminfo.target_price_low, color = color.red, xloc =
xloc.bar_time)
//@variable A line connecting the current `close` to the median yearly price estimate.
medianLine = line.new(time, close, YTD, syminfo.target_price_median, color = color.gray,
xloc = xloc.bar_time)
//@variable A line connecting the current `close` to the average yearly price estimate.
averageLine = line.new(time, close, YTD, syminfo.target_price_average, color = color.oran
ge, xloc = xloc.bar_time)
// Fill the space between targets
linefill.new(lowLine, medianLine, color.new(color.red, 90))
linefill.new(medianLine, highLine, color.new(color.green, 90))
// Create a label displaying the total number of analyst estimates.
string estimatesText = str.format("Number of estimates: {0}", syminfo.target_price_estima
tes)
label.new(bar_index, close, estimatesText, textcolor = color.white, size = size.large)
SEE ALSO
syminfo.target_price_datesyminfo.target_price_estimatessyminfo.target_price_highsyminfo.target
_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=5
indicator("syminfo target_price")
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
//@variable A line connecting the current `close` to the highest yearly price estimate.
highLine = line.new(time, close, YTD, syminfo.target_price_high, color = color.green, xlo
c = xloc.bar_time)
//@variable A line connecting the current `close` to the lowest yearly price estimate.
lowLine = line.new(time, close, YTD, syminfo.target_price_low, color = color.red, xloc =
xloc.bar_time)
//@variable A line connecting the current `close` to the median yearly price estimate.
medianLine = line.new(time, close, YTD, syminfo.target_price_median, color = color.gray,
xloc = xloc.bar_time)
//@variable A line connecting the current `close` to the average yearly price estimate.
averageLine = line.new(time, close, YTD, syminfo.target_price_average, color = color.oran
ge, xloc = xloc.bar_time)
// Fill the space between targets
linefill.new(lowLine, medianLine, color.new(color.red, 90))
linefill.new(medianLine, highLine, color.new(color.green, 90))
// Create a label displaying the total number of analyst estimates.
string estimatesText = str.format("Number of estimates: {0}", syminfo.target_price_estima
tes)
label.new(bar_index, close, estimatesText, textcolor = color.white, size = size.large)
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=5
indicator("syminfo target_price")
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
//@variable A line connecting the current `close` to the highest yearly price estimate.
highLine = line.new(time, close, YTD, syminfo.target_price_high, color = color.green, xlo
c = xloc.bar_time)
//@variable A line connecting the current `close` to the lowest yearly price estimate.
lowLine = line.new(time, close, YTD, syminfo.target_price_low, color = color.red, xloc =
xloc.bar_time)
//@variable A line connecting the current `close` to the median yearly price estimate.
medianLine = line.new(time, close, YTD, syminfo.target_price_median, color = color.gray,
xloc = xloc.bar_time)
//@variable A line connecting the current `close` to the average yearly price estimate.
averageLine = line.new(time, close, YTD, syminfo.target_price_average, color = color.oran
ge, xloc = xloc.bar_time)
// Fill the space between targets
linefill.new(lowLine, medianLine, color.new(color.red, 90))
linefill.new(medianLine, highLine, color.new(color.green, 90))
// Create a label displaying the total number of analyst estimates.
string estimatesText = str.format("Number of estimates: {0}", syminfo.target_price_estima
tes)
label.new(bar_index, close, estimatesText, textcolor = color.white, size = size.large)
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=5
indicator("syminfo target_price")
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
//@variable A line connecting the current `close` to the highest yearly price estimate.
highLine = line.new(time, close, YTD, syminfo.target_price_high, color = color.green, xlo
c = xloc.bar_time)
//@variable A line connecting the current `close` to the lowest yearly price estimate.
lowLine = line.new(time, close, YTD, syminfo.target_price_low, color = color.red, xloc =
xloc.bar_time)
//@variable A line connecting the current `close` to the median yearly price estimate.
medianLine = line.new(time, close, YTD, syminfo.target_price_median, color = color.gray,
xloc = xloc.bar_time)
//@variable A line connecting the current `close` to the average yearly price estimate.
averageLine = line.new(time, close, YTD, syminfo.target_price_average, color = color.oran
ge, xloc = xloc.bar_time)
// Fill the space between targets
linefill.new(lowLine, medianLine, color.new(color.red, 90))
linefill.new(medianLine, highLine, color.new(color.green, 90))
// Create a label displaying the total number of analyst estimates.
string estimatesText = str.format("Number of estimates: {0}", syminfo.target_price_estima
tes)
label.new(bar_index, close, estimatesText, textcolor = color.white, size = size.large)
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=5
indicator("syminfo target_price")
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
//@variable A line connecting the current `close` to the highest yearly price estimate.
highLine = line.new(time, close, YTD, syminfo.target_price_high, color = color.green, xlo
c = xloc.bar_time)
//@variable A line connecting the current `close` to the lowest yearly price estimate.
lowLine = line.new(time, close, YTD, syminfo.target_price_low, color = color.red, xloc =
xloc.bar_time)
//@variable A line connecting the current `close` to the median yearly price estimate.
medianLine = line.new(time, close, YTD, syminfo.target_price_median, color = color.gray,
xloc = xloc.bar_time)
//@variable A line connecting the current `close` to the average yearly price estimate.
averageLine = line.new(time, close, YTD, syminfo.target_price_average, color = color.oran
ge, xloc = xloc.bar_time)
// Fill the space between targets
linefill.new(lowLine, medianLine, color.new(color.red, 90))
linefill.new(medianLine, highLine, color.new(color.green, 90))
// Create a label displaying the total number of analyst estimates.
string estimatesText = str.format("Number of estimates: {0}", syminfo.target_price_estima
tes)
label.new(bar_index, close, estimatesText, textcolor = color.white, size = size.large)
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=5
indicator("syminfo target_price")
if barstate.islastconfirmedhistory
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
//@variable A line connecting the current `close` to the highest yearly price estimate.
highLine = line.new(time, close, YTD, syminfo.target_price_high, color = color.green, xlo
c = xloc.bar_time)
//@variable A line connecting the current `close` to the lowest yearly price estimate.
lowLine = line.new(time, close, YTD, syminfo.target_price_low, color = color.red, xloc =
xloc.bar_time)
//@variable A line connecting the current `close` to the median yearly price estimate.
medianLine = line.new(time, close, YTD, syminfo.target_price_median, color = color.gray,
xloc = xloc.bar_time)
//@variable A line connecting the current `close` to the average yearly price estimate.
averageLine = line.new(time, close, YTD, syminfo.target_price_average, color = color.oran
ge, xloc = xloc.bar_time)
// Fill the space between targets
linefill.new(lowLine, medianLine, color.new(color.red, 90))
linefill.new(medianLine, highLine, color.new(color.green, 90))
// Create a label displaying the total number of analyst estimates.
string estimatesText = str.format("Number of estimates: {0}", syminfo.target_price_estima
tes)
label.new(bar_index, close, estimatesText, textcolor = color.white, size = size.large)
SEE ALSO
syminfo.target_price_averagesyminfo.target_price_datesyminfo.target_price_estimatessyminfo.ta
rget_price_highsyminfo.target_price_low
syminfo.ticker
Symbol name without exchange prefix, e.g. 'MSFT'.
TYPE
simple string
SEE ALSO
syminfo.tickeridtimeframe.periodtimeframe.multipliersyminfo.root
syminfo.tickerid
Returns the full form of the ticker ID representing a symbol, for use as an argument in
functions with a ticker or symbol parameter. It always includes the prefix
(exchange) and ticker separated by a colon ("NASDAQ:AAPL"), but it can also include
other symbol data such as dividend adjustment, chart type, currency conversion, etc.
TYPE
simple string
REMARKS
Because the value of this variable does not always use a simple "prefix:ticker" format,
it is a poor candidate for use in boolean comparisons or string manipulation functions.
In those contexts, run the variable's result through ticker.standard to purify it. This
will remove any extraneous information and return a ticker ID consistently formatted
using the "prefix:ticker" structure.
SEE ALSO
ticker.newsyminfo.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
Intraday Intensity Index.
TYPE
series float
EXAMPLE
//@version=5
indicator("Intraday Intensity Index")
plot(ta.iii, color=color.yellow)
plot(f_iii())
ta.nvi
Negative Volume Index.
TYPE
series float
EXAMPLE
//@version=5
indicator("Negative Volume Index")
plot(ta.nvi, color=color.yellow)
plot(f_nvi())
ta.obv
On Balance Volume.
TYPE
series float
EXAMPLE
//@version=5
indicator("On Balance Volume")
plot(ta.obv, color=color.yellow)
plot(f_obv())
ta.pvi
Positive Volume Index.
TYPE
series float
EXAMPLE
//@version=5
indicator("Positive Volume Index")
plot(ta.pvi, color=color.yellow)
plot(f_pvi())
ta.pvt
Price-Volume Trend.
TYPE
series float
EXAMPLE
//@version=5
indicator("Price-Volume Trend")
plot(ta.pvt, color=color.yellow)
ta.tr
True range, equivalent to ta.tr(handle_na = false). It is calculated
as math.max(high - low, math.abs(high - close[1]), math.abs(low -
close[1])).
TYPE
series float
SEE ALSO
ta.trta.atr
ta.vwap
Volume Weighted Average Price. It uses hlc3 as its source series.
TYPE
series float
SEE ALSO
ta.vwap
ta.wad
Williams Accumulation/Distribution.
TYPE
series float
EXAMPLE
//@version=5
indicator("Williams Accumulation/Distribution")
plot(ta.wad, color=color.yellow)
plot(f_wad())
ta.wvad
Williams Variable Accumulation/Distribution.
TYPE
series float
EXAMPLE
//@version=5
indicator("Williams Variable Accumulation/Distribution")
plot(ta.wvad, color=color.yellow)
// the same on pine
f_wvad() =>
(close - open) / (high - low) * volume
plot(f_wvad())
table.all
Returns an array filled with all the current tables drawn by the script.
TYPE
array<table>
EXAMPLE
//@version=5
indicator("table.all")
//delete all tables
table.new(position = position.top_right, columns = 2, rows = 1, bgcolor = color.yellow, borde
r_width = 1)
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
Returns true if current resolution is a daily resolution, false otherwise.
TYPE
simple bool
SEE ALSO
timeframe.isdwmtimeframe.isintradaytimeframe.isminutestimeframe.issecondstimeframe.isticksti
meframe.isweeklytimeframe.ismonthly
timeframe.isdwm
Returns true if current resolution is a daily or weekly or monthly resolution, false
otherwise.
TYPE
simple bool
SEE ALSO
timeframe.isintradaytimeframe.isminutestimeframe.issecondstimeframe.istickstimeframe.isdailyti
meframe.isweeklytimeframe.ismonthly
timeframe.isintraday
Returns true if current resolution is an intraday (minutes or seconds) resolution, false
otherwise.
TYPE
simple bool
SEE ALSO
timeframe.isminutestimeframe.issecondstimeframe.istickstimeframe.isdwmtimeframe.isdailytime
frame.isweeklytimeframe.ismonthly
timeframe.isminutes
Returns true if current resolution is a minutes resolution, false otherwise.
TYPE
simple bool
SEE ALSO
timeframe.isdwmtimeframe.isintradaytimeframe.issecondstimeframe.istickstimeframe.isdailytime
frame.isweeklytimeframe.ismonthly
timeframe.ismonthly
Returns true if current resolution is a monthly resolution, false otherwise.
TYPE
simple bool
SEE ALSO
timeframe.isdwmtimeframe.isintradaytimeframe.isminutestimeframe.issecondstimeframe.isticksti
meframe.isdailytimeframe.isweekly
timeframe.isseconds
Returns true if current resolution is a seconds resolution, false otherwise.
TYPE
simple bool
SEE ALSO
timeframe.isdwmtimeframe.isintradaytimeframe.isminutestimeframe.istickstimeframe.isdailytime
frame.isweeklytimeframe.ismonthly
timeframe.isticks
Returns true if current resolution is a ticks resolution, false otherwise.
TYPE
simple bool
SEE ALSO
timeframe.isdwmtimeframe.isintradaytimeframe.isminutestimeframe.issecondstimeframe.isdailyt
imeframe.isweeklytimeframe.ismonthly
timeframe.isweekly
Returns true if current resolution is a weekly resolution, false otherwise.
TYPE
simple bool
SEE ALSO
timeframe.isdwmtimeframe.isintradaytimeframe.isminutestimeframe.issecondstimeframe.isticksti
meframe.isdailytimeframe.ismonthly
timeframe.multiplier
Multiplier of resolution, e.g. '60' - 60, 'D' - 1, '5D' - 5, '12M' - 12.
TYPE
simple int
SEE ALSO
syminfo.tickersyminfo.tickeridtimeframe.period
timeframe.period
A string representation of the chart's timeframe. The returned string's format is
"[<quantity>][<units>]", where <quantity> and <units> are in some cases absent.
<quantity> is the number of units, but it is absent if that number is 1. <unit> is "S" for
seconds, "D" for days, "W" for weeks, "M" for months, but it is absent for minutes. No
<unit> exists for hours.
The variable will return: "10S" for 10 seconds, "60" for 60 minutes, "D" for one day,
"2W" for two weeks, "3M" for one quarter.
Can be used as an argument with any function containing a timeframe parameter.
TYPE
simple string
SEE ALSO
syminfo.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
Current bar volume.
TYPE
series float
REMARKS
Previous values may be accessed with square brackets operator [], e.g. volume[1],
volume[2].
SEE ALSO
openhighlowclosetimehl2hlc3hlcc4ohlc4
weekofyear
Week number of current bar time in exchange timezone.
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
Current bar year in exchange timezone.
TYPE
series int
REMARKS
Note that this variable returns the year based on the time of the bar's open. For
overnight sessions (e.g. EURUSD, where Monday session starts on Sunday, 17:00) this
value can be lower by 1 than the year of the trading day.
SEE ALSO
yeartimemonthweekofyeardayofmonthdayofweekhourminutesecond
Constants
adjustment.dividends
Constant for dividends adjustment type (dividends adjustment is applied).
TYPE
const string
SEE ALSO
adjustment.noneadjustment.splitsticker.new
adjustment.none
Constant for none adjustment type (no adjustment is applied).
TYPE
const string
SEE ALSO
adjustment.splitsadjustment.dividendsticker.new
adjustment.splits
Constant for splits adjustment type (splits adjustment is applied).
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.
All function calls trigger the alert.
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
A constant to specify the value of the backadjustment parameter
in ticker.new and ticker.modify functions.
TYPE
const backadjustment
SEE ALSO
ticker.newticker.modifybackadjustment.onbackadjustment.off
backadjustment.off
A constant to specify the value of the backadjustment parameter
in ticker.new and ticker.modify functions.
TYPE
const backadjustment
SEE ALSO
ticker.newticker.modifybackadjustment.onbackadjustment.inherit
backadjustment.on
A constant to specify the value of the backadjustment parameter
in ticker.new and ticker.modify functions.
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
Is a named constant for #00BCD4 color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.g
reencolor.limecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.orange
color.black
Is a named constant for #363A45 color.
TYPE
const color
SEE ALSO
color.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.greencolor.li
mecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.blue
Is a named constant for #2962ff color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.g
reencolor.limecolor.olivecolor.yellowcolor.navycolor.tealcolor.aquacolor.orange
color.fuchsia
Is a named constant for #E040FB color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.greencolor.lim
ecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.gray
Is a named constant for #787B86 color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.greencolor.
limecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.green
Is a named constant for #4CAF50 color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.li
mecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.lime
Is a named constant for #00E676 color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.g
reencolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.maroon
Is a named constant for #880E4F color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.redcolor.purplecolor.fuchsiacolor.greencolor.lim
ecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.navy
Is a named constant for #311B92 color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.g
reencolor.limecolor.olivecolor.yellowcolor.bluecolor.tealcolor.aquacolor.orange
color.olive
Is a named constant for #808000 color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.g
reencolor.limecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.orange
Is a named constant for #FF9800 color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.g
reencolor.limecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aqua
color.purple
Is a named constant for #9C27B0 color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.fuchsiacolor.greencolor.li
mecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.red
Is a named constant for #FF5252 color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.purplecolor.fuchsiacolor.greencolor
.limecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.silver
Is a named constant for #B2B5BE color.
TYPE
const color
SEE ALSO
color.blackcolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.greencolor.li
mecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.teal
Is a named constant for #00897B color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.g
reencolor.limecolor.olivecolor.yellowcolor.navycolor.bluecolor.aquacolor.orange
color.white
Is a named constant for #FFFFFF color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.marooncolor.redcolor.purplecolor.fuchsiacolor.greencolor.li
mecolor.olivecolor.yellowcolor.navycolor.bluecolor.tealcolor.aquacolor.orange
color.yellow
Is a named constant for #FFEB3B color.
TYPE
const color
SEE ALSO
color.blackcolor.silvercolor.graycolor.whitecolor.marooncolor.redcolor.purplecolor.fuchsiacolor.g
reencolor.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
Hong Kong dollar.
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
South Korean won.
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
New Zealand dollar.
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
United States dollar.
TYPE
const string
SEE ALSO
strategy
currency.USDT
Tether.
TYPE
const string
SEE ALSO
strategy
currency.ZAR
South African rand.
TYPE
const string
SEE ALSO
strategy
dayofweek.friday
Is a named constant for return value of dayofweek function and value
of dayofweek variable.
TYPE
const int
SEE ALSO
dayofweek.sundaydayofweek.mondaydayofweek.tuesdaydayofweek.wednesdaydayofweek.thursda
ydayofweek.saturday
dayofweek.monday
Is a named constant for return value of dayofweek function and value
of dayofweek variable.
TYPE
const int
SEE ALSO
dayofweek.sundaydayofweek.tuesdaydayofweek.wednesdaydayofweek.thursdaydayofweek.fridayd
ayofweek.saturday
dayofweek.saturday
Is a named constant for return value of dayofweek function and value
of dayofweek variable.
TYPE
const int
SEE ALSO
dayofweek.sundaydayofweek.mondaydayofweek.tuesdaydayofweek.wednesdaydayofweek.thursda
ydayofweek.friday
dayofweek.sunday
Is a named constant for return value of dayofweek function and value
of dayofweek variable.
TYPE
const int
SEE ALSO
dayofweek.mondaydayofweek.tuesdaydayofweek.wednesdaydayofweek.thursdaydayofweek.friday
dayofweek.saturday
dayofweek.thursday
Is a named constant for return value of dayofweek function and value
of dayofweek variable.
TYPE
const int
SEE ALSO
dayofweek.sundaydayofweek.mondaydayofweek.tuesdaydayofweek.wednesdaydayofweek.fridayd
ayofweek.saturday
dayofweek.tuesday
Is a named constant for return value of dayofweek function and value
of dayofweek variable.
TYPE
const int
SEE ALSO
dayofweek.sundaydayofweek.mondaydayofweek.wednesdaydayofweek.thursdaydayofweek.fridayd
ayofweek.saturday
dayofweek.wednesday
Is a named constant for return value of dayofweek function and value
of dayofweek variable.
TYPE
const int
SEE ALSO
dayofweek.sundaydayofweek.mondaydayofweek.tuesdaydayofweek.thursdaydayofweek.fridaydayo
fweek.saturday
display.all
A named constant for use with the display parameter
of plot*() and input*() functions. Displays plotted or input values in all possible
locations.
TYPE
const plot_simple_display
SEE ALSO
plotplotshapeplotcharplotarrowplotbarplotcandle
display.data_window
A named constant for use with the display parameter
of plot*() and input*() functions. Displays plotted or input values in the Data
Window, a menu accessible from the chart's right sidebar.
TYPE
const plot_display
SEE ALSO
plotplotshapeplotcharplotarrowplotbarplotcandle
display.none
A named constant for use with the display parameter
of plot*() and input*() functions. plot*() functions using this will not display
their plotted values anywhere. However, alert template messages and fill functions
can still use the values, and they will appear in exported chart
data. input*() functions using this constant will only display their values within the
script's settings.
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
A named constant for use with the display parameter
of plot*() and input*() functions. Displays plotted or input values in the status
line next to the script's name on the chart if the chart's settings allow it.
TYPE
const plot_display
SEE ALSO
plotplotshapeplotcharplotarrowplotbarplotcandle
dividends.gross
A named constant for the request.dividends function. Is used to request the dividends
return on a stock before deductions.
TYPE
const string
SEE ALSO
request.dividends
dividends.net
A named constant for the request.dividends function. Is used to request the dividends
return on a stock after deductions.
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
A named constant for the request.earnings function. Is used to request the
standardized earnings value.
TYPE
const string
SEE ALSO
request.earnings
extend.both
A named constant for line.new and line.set_extend functions.
TYPE
const string
SEE ALSO
line.newline.set_extendextend.noneextend.leftextend.right
extend.left
A named constant for line.new and line.set_extend functions.
TYPE
const string
SEE ALSO
line.newline.set_extendextend.noneextend.rightextend.both
extend.none
A named constant for line.new and line.set_extend functions.
TYPE
const string
SEE ALSO
line.newline.set_extendextend.leftextend.rightextend.both
extend.right
A named constant for line.new and line.set_extend functions.
TYPE
const string
SEE ALSO
line.newline.set_extendextend.noneextend.leftextend.both
false
Literal representing a bool value, and result of a comparison operation.
REMARKS
See the User Manual for comparison operators and logical operators.
SEE ALSO
bool
font.family_default
Default text font
for box.new, box.set_text_font_family, label.new, label.set_text_font_family, table.
cell and table.cell_set_text_font_family functions.
TYPE
const string
SEE ALSO
box.newbox.set_text_font_familylabel.newlabel.set_text_font_familytable.celltable.cell_set_text
_font_familyfont.family_monospace
font.family_monospace
Monospace text font
for box.new, box.set_text_font_family, label.new, label.set_text_font_family, table.
cell and table.cell_set_text_font_family functions.
TYPE
const string
SEE ALSO
box.newbox.set_text_font_familylabel.newlabel.set_text_font_familytable.celltable.cell_set_text
_font_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
Is a named constant to use with the str.tostring function. Passing a number
to str.tostring with this argument rounds the number to the nearest value that can be
divided by syminfo.mintick, without the remainder, with ties rounding up, and returns
the string version of said value with trailing zeros.
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
Is a named constant for dashed linestyle of hline function.
TYPE
const hline_style
SEE ALSO
hline.style_solidhline.style_dotted
hline.style_dotted
Is a named constant for dotted linestyle of hline function.
TYPE
const hline_style
SEE ALSO
hline.style_solidhline.style_dashed
hline.style_solid
Is a named constant for solid linestyle of hline function.
TYPE
const hline_style
SEE ALSO
hline.style_dottedhline.style_dashed
label.style_arrowdown
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel
.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_rightl
abel.style_label_centerlabel.style_squarelabel.style_diamond
label.style_arrowup
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowdownla
bel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.style_la
bel_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_ri
ghtlabel.style_label_centerlabel.style_squarelabel.style_diamond
label.style_circle
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_arrowuplabel.style_arrowdow
nlabel.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
_rightlabel.style_label_centerlabel.style_squarelabel.style_diamond
label.style_cross
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_triangleu
plabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.style_arrowdo
wnlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.sty
le_label_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upp
er_rightlabel.style_label_centerlabel.style_squarelabel.style_diamond
label.style_diamond
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel
.style_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label
_rightlabel.style_label_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.st
yle_label_upper_rightlabel.style_label_centerlabel.style_square
label.style_flag
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_circlelabel.style_arrowuplabel.style_arrowdo
wnlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.sty
le_label_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upp
er_rightlabel.style_label_centerlabel.style_squarelabel.style_diamond
label.style_label_center
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel
.style_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label
_rightlabel.style_label_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.st
yle_label_upper_rightlabel.style_squarelabel.style_diamond
label.style_label_down
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel
.style_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_rightl
abel.style_label_centerlabel.style_squarelabel.style_diamond
label.style_label_left
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel
.style_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_rightlabel.style_lab
el_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rig
htlabel.style_label_centerlabel.style_squarelabel.style_diamond
label.style_label_lower_left
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel
.style_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label
_rightlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightlabel.
style_label_centerlabel.style_squarelabel.style_diamond
label.style_label_lower_right
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel
.style_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label
_rightlabel.style_label_lower_leftlabel.style_label_upper_leftlabel.style_label_upper_rightlabel.s
tyle_label_centerlabel.style_squarelabel.style_diamond
label.style_label_right
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel
.style_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label
_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightl
abel.style_label_centerlabel.style_squarelabel.style_diamond
label.style_label_up
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel
.style_arrowdownlabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.style_la
bel_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_ri
ghtlabel.style_label_centerlabel.style_squarelabel.style_diamond
label.style_label_upper_left
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel
.style_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label
_rightlabel.style_label_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_rightlabel.
style_label_centerlabel.style_squarelabel.style_diamond
label.style_label_upper_right
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel
.style_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label
_rightlabel.style_label_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.st
yle_label_centerlabel.style_squarelabel.style_diamond
label.style_none
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_xcrosslabel.style_crosslabel.style_triangleu
plabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.style_arrowdo
wnlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.sty
le_label_centerlabel.style_squarelabel.style_diamond
label.style_square
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel
.style_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label
_rightlabel.style_label_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.st
yle_label_upper_rightlabel.style_label_centerlabel.style_diamond
label.style_text_outline
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel
.style_arrowdownlabel.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label
_rightlabel.style_label_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.st
yle_label_upper_rightlabel.style_label_centerlabel.style_squarelabel.style_diamond
label.style_triangledown
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangleuplabel.style_flaglabel.style_circlelabel.style_arrowuplabel.style_arrowdownlabel.s
tyle_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.style_label_l
ower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rightla
bel.style_label_centerlabel.style_squarelabel.style_diamond
label.style_triangleup
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_xcrosslabel.style_crosslabel
.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.style_arrowdownlab
el.style_label_uplabel.style_label_downlabel.style_label_leftlabel.style_label_rightlabel.style_lab
el_lower_leftlabel.style_label_lower_rightlabel.style_label_upper_leftlabel.style_label_upper_rig
htlabel.style_label_centerlabel.style_squarelabel.style_diamond
label.style_xcross
Label style for label.new and label.set_style functions.
TYPE
const string
SEE ALSO
label.newlabel.set_stylelabel.set_textalignlabel.style_nonelabel.style_crosslabel.style_triangleupl
abel.style_triangledownlabel.style_flaglabel.style_circlelabel.style_arrowuplabel.style_arrowdow
nlabel.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.st
yle_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.
style_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.st
yle_arrow_both
line.style_dashed
Line style for line.new and line.set_style functions.
TYPE
const string
SEE ALSO
line.newline.set_styleline.style_solidline.style_dottedline.style_arrow_leftline.style_arrow_rightli
ne.style_arrow_both
line.style_dotted
Line style for line.new and line.set_style functions.
TYPE
const string
SEE ALSO
line.newline.set_styleline.style_solidline.style_dashedline.style_arrow_leftline.style_arrow_rightli
ne.style_arrow_both
line.style_solid
Line style for line.new and line.set_style functions.
TYPE
const string
SEE ALSO
line.newline.set_styleline.style_dottedline.style_dashedline.style_arrow_leftline.style_arrow_righ
tline.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
Is a named constant for Euler's number. It is equal to 2.7182818284590452.
TYPE
const float
SEE ALSO
math.phimath.pimath.rphi
math.phi
Is a named constant for the golden ratio. It is equal to 1.6180339887498948.
TYPE
const float
SEE ALSO
math.emath.pimath.rphi
math.pi
Is a named constant for Archimedes' constant. It is equal to 3.1415926535897932.
TYPE
const float
SEE ALSO
math.emath.phimath.rphi
math.rphi
Is a named constant for the golden ratio conjugate. It is equal to
0.6180339887498948.
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
A named constant for the 'Area' style, to be used as an argument for
the style parameter in the plot function.
TYPE
const plot_style
SEE ALSO
plotplot.style_steplinebrplot.style_lineplot.style_linebrplot.style_steplineplot.style_stepline_diam
ondplot.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_diam
ondplot.style_histogramplot.style_crossplot.style_areaplot.style_columnsplot.style_circles
plot.style_circles
A named constant for the 'Circles' style, to be used as an argument for
the style parameter in the plot function.
TYPE
const plot_style
SEE ALSO
plotplot.style_steplinebrplot.style_lineplot.style_linebrplot.style_steplineplot.style_stepline_diam
ondplot.style_histogramplot.style_crossplot.style_areaplot.style_areabrplot.style_columns
plot.style_columns
A named constant for the 'Columns' style, to be used as an argument for
the style parameter in the plot function.
TYPE
const plot_style
SEE ALSO
plotplot.style_steplinebrplot.style_lineplot.style_linebrplot.style_steplineplot.style_stepline_diam
ondplot.style_histogramplot.style_crossplot.style_areaplot.style_areabrplot.style_circles
plot.style_cross
A named constant for the 'Cross' style, to be used as an argument for
the style parameter in the plot function.
TYPE
const plot_style
SEE ALSO
plotplot.style_steplinebrplot.style_lineplot.style_linebrplot.style_steplineplot.style_stepline_diam
ondplot.style_histogramplot.style_areaplot.style_areabrplot.style_columnsplot.style_circles
plot.style_histogram
A named constant for the 'Histogram' style, to be used as an argument for
the style parameter in the plot function.
TYPE
const plot_style
SEE ALSO
plotplot.style_steplinebrplot.style_lineplot.style_linebrplot.style_steplineplot.style_stepline_diam
ondplot.style_crossplot.style_areaplot.style_areabrplot.style_columnsplot.style_circles
plot.style_line
A named constant for the 'Line' style, to be used as an argument for
the style parameter in the plot function.
TYPE
const plot_style
SEE ALSO
plotplot.style_steplinebrplot.style_linebrplot.style_steplineplot.style_stepline_diamondplot.style_
histogramplot.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_hi
stogramplot.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_hist
ogramplot.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.st
yle_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_diamond
plot.style_histogramplot.style_crossplot.style_areaplot.style_areabrplot.style_columns
position.bottom_center
Table position is used in table.new, table.cell functions.
Binds the table to the bottom edge in the 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
Table position is used in table.new, table.cell functions.
Binds the table to the bottom left of the screen.
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
Table position is used in table.new, table.cell functions.
Binds the table to the bottom right of the screen.
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
Table position is used in table.new, table.cell functions.
Binds the table to the center of the screen.
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
Table position is used in table.new, table.cell functions.
Binds the table to the left side of the screen.
TYPE
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
Table position is used in table.new, table.cell functions.
Binds the table to the right side of the screen.
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
Table position is used in table.new, table.cell functions.
Binds the table to the top edge in the center.
TYPE
const string
SEE ALSO
table.newtable.celltable.set_positionposition.top_leftposition.top_rightposition.middle_leftpositi
on.middle_centerposition.middle_rightposition.bottom_leftposition.bottom_center
position.top_left
Table position is used in table.new, table.cell functions.
Binds the table to the upper-left edge.
TYPE
const string
SEE ALSO
table.newtable.celltable.set_positionposition.top_centerposition.top_rightposition.middle_leftpos
ition.middle_centerposition.middle_rightposition.bottom_leftposition.bottom_center
position.top_right
Table position is used in table.new, table.cell functions.
Binds the table to the upper-right edge.
TYPE
const string
SEE ALSO
table.newtable.celltable.set_positionposition.top_leftposition.top_centerposition.middle_leftposi
tion.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
Constant for extended session type (with extended hours data).
TYPE
const string
SEE ALSO
session.regularsyminfo.session
session.regular
Constant for regular session type (no extended hours data).
TYPE
const string
SEE ALSO
session.extendedsyminfo.session
settlement_as_close.inherit
A constant to specify the value of the settlement_as_close parameter
in ticker.new and ticker.modify functions.
TYPE
const settlement
SEE ALSO
ticker.newticker.modifysettlement_as_close.onsettlement_as_close.off
settlement_as_close.off
A constant to specify the value of the settlement_as_close parameter
in ticker.new and ticker.modify functions.
TYPE
const settlement
SEE ALSO
ticker.newticker.modifysettlement_as_close.onsettlement_as_close.inherit
settlement_as_close.on
A constant to specify the value of the settlement_as_close parameter
in ticker.new and ticker.modify functions.
TYPE
const settlement
SEE ALSO
ticker.newticker.modifysettlement_as_close.inheritsettlement_as_close.off
shape.arrowdown
Shape style for plotshape function.
TYPE
const string
SEE ALSO
plotshape
shape.arrowup
Shape style for plotshape function.
TYPE
const string
SEE ALSO
plotshape
shape.circle
Shape style for plotshape function.
TYPE
const string
SEE ALSO
plotshape
shape.cross
Shape style for plotshape function.
TYPE
const string
SEE ALSO
plotshape
shape.diamond
Shape style for plotshape function.
TYPE
const string
SEE ALSO
plotshape
shape.flag
Shape style for plotshape function.
TYPE
const string
SEE ALSO
plotshape
shape.labeldown
Shape style for plotshape function.
TYPE
const string
SEE ALSO
plotshape
shape.labelup
Shape style for plotshape function.
TYPE
const string
SEE ALSO
plotshape
shape.square
Shape style for plotshape function.
TYPE
const string
SEE ALSO
plotshape
shape.triangledown
Shape style for plotshape function.
TYPE
const string
SEE ALSO
plotshape
shape.triangleup
Shape style for plotshape function.
TYPE
const string
SEE ALSO
plotshape
shape.xcross
Shape style for plotshape function.
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
This is one of the arguments that can be supplied to
the default_qty_type parameter in the strategy declaration statement. It is only
relevant when no value is used for the ‘qty’ parameter
in strategy.entry or strategy.order function calls. It specifies that an amount of cash
in the strategy.account_currency will be used to enter trades.
TYPE
const string
EXAMPLE
//@version=5
strategy("strategy.cash", overlay = true, default_qty_value = 50, default_qty_type = strategy
.cash, initial_capital = 1000000)
if bar_index == 0
// As ‘qty’ is not defined, the previously defined values for the `default_qty_type` an
d `default_qty_value` parameters are used to enter trades, namely 50 units of cash in the cur
rency of `strategy.account_currency`.
// `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
Commission type for an order. A percentage of the cash volume of order.
TYPE
const string
SEE ALSO
strategy
strategy.direction.all
It allows strategy to open both long and short positions.
TYPE
const string
SEE ALSO
strategy.risk.allow_entry_in
strategy.direction.long
It allows strategy to open only long positions.
TYPE
const string
SEE ALSO
strategy.risk.allow_entry_in
strategy.direction.short
It allows strategy to open only short positions.
TYPE
const string
SEE ALSO
strategy.risk.allow_entry_in
strategy.fixed
This is one of the arguments that can be supplied to
the default_qty_type parameter in the strategy declaration statement. It is only
relevant when no value is used for the ‘qty’ parameter
in strategy.entry or strategy.order function calls. It specifies that a number of
contracts/shares/lots will be used to enter trades.
TYPE
const string
EXAMPLE
//@version=5
strategy("strategy.fixed", overlay = true, default_qty_value = 50, default_qty_type = strateg
y.fixed, initial_capital = 1000000)
if bar_index == 0
// As ‘qty’ is not defined, the previously defined values for the `default_qty_type` an
d `default_qty_value` 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
Long position entry.
TYPE
const strategy_direction
SEE ALSO
strategy.entrystrategy.exitstrategy.order
strategy.oca.cancel
OCA type value for strategy's functions. The parameter determines that an order
should belong to an OCO group, where as soon as an order is filled, all other orders of
the same group are cancelled. Note: if more than 1 guaranteed-to-be-executed orders
of the same OCA group are placed at once, all those orders are filled.
TYPE
const string
SEE ALSO
strategy.entrystrategy.exitstrategy.order
strategy.oca.none
OCA type value for strategy's functions. The parameter determines that an order
should not belong to any particular OCO group.
TYPE
const string
SEE ALSO
strategy.entrystrategy.exitstrategy.order
strategy.oca.reduce
OCA type value for strategy's functions. The parameter determines that an order
should belong to an OCO group, where if X number of contracts of an order is filled,
number of contracts for each other order of the same OCO group is decreased by X.
Note: if more than 1 guaranteed-to-be-executed orders of the same OCA group are
placed at once, all those orders are filled.
TYPE
const string
SEE ALSO
strategy.entrystrategy.exitstrategy.order
strategy.percent_of_equity
This is one of the arguments that can be supplied to
the default_qty_type parameter in the strategy declaration statement. It is only
relevant when no value is used for the ‘qty’ parameter
in strategy.entry or strategy.order function calls. It specifies that a percentage (0-
100) of equity will be used to enter trades.
TYPE
const string
EXAMPLE
//@version=5
strategy("strategy.percent_of_equity", overlay = false, default_qty_value = 100, default_qty_
type = strategy.percent_of_equity, initial_capital = 1000000)
// As ‘qty’ is not defined, the previously defined values for the `default_qty_type` and `d
efault_qty_value` parameters 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 price = (10 * close).
if bar_index == 4
strategy.entry("EN", strategy.long, qty = 10)
if bar_index == 6
strategy.close("EN")
SEE ALSO
strategy
strategy.short
Short position entry.
TYPE
const strategy_direction
SEE ALSO
strategy.entrystrategy.exitstrategy.order
text.align_bottom
Vertical text alignment
for box.new, box.set_text_valign, table.cell and table.cell_set_text_valign functions.
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_textal
ign functions.
TYPE
const string
SEE ALSO
label.newlabel.set_styletext.align_lefttext.align_right
text.align_left
Horizontal text alignment
for box.new, box.set_text_halign, label.new and label.set_textalign functions.
TYPE
const string
SEE ALSO
label.newlabel.set_styletext.align_centertext.align_right
text.align_right
Horizontal text alignment
for box.new, box.set_text_halign, label.new and label.set_textalign functions.
TYPE
const string
SEE ALSO
label.newlabel.set_styletext.align_centertext.align_left
text.align_top
Vertical text alignment
for box.new, box.set_text_valign, table.cell and table.cell_set_text_valign functions.
TYPE
const string
SEE ALSO
table.celltable.cell_set_text_valigntext.align_centertext.align_lefttext.align_right
text.wrap_auto
Automatic wrapping mode for box.new and box.set_text_wrap functions.
TYPE
const string
SEE ALSO
box.newbox.set_textbox.set_text_wrap
text.wrap_none
Disabled wrapping mode for box.new and box.set_text_wrap functions.
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
A named constant that specifies the algorithm of interpretation of y-value in
function label.new.
TYPE
const string
SEE ALSO
label.newlabel.set_ylocyloc.priceyloc.belowbar
yloc.belowbar
A named constant that specifies the algorithm of interpretation of y-value in
function label.new.
TYPE
const string
SEE ALSO
label.newlabel.set_ylocyloc.priceyloc.abovebar
yloc.price
A named constant that specifies the algorithm of interpretation of y-value in
function label.new.
TYPE
const string
SEE ALSO
label.newlabel.set_ylocyloc.abovebaryloc.belowbar
Functions
alert()
Creates an alert event when called during the real-time bar, which will trigger a
script alert based on "alert function events" if one was previously created for the
indicator or strategy through the "Create Alert" dialog box.
SYNTAX
array.abs()
2 overloads
Returns an array containing the absolute value of each element in the original array.
SYNTAX & OVERLOADS
array.abs(id) → array<float>
array.abs(id) → array<int>
ARGUMENTS
id (array<int/float>) An array object.
SEE ALSO
array.new_floatarray.insertarray.slicearray.reverseorder.ascendingorder.descending
array.avg()
2 overloads
The function returns the mean of an array's elements.
SYNTAX & OVERLOADS
ARGUMENTS
id (array<int/float>) An array object.
EXAMPLE
//@version=5
indicator("array.avg example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.avg(a))
RETURNS
Mean of array's elements.
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
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
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
array.clear()
The function removes all elements from an array.
SYNTAX
array.clear(id) → void
ARGUMENTS
id (any array type) An array object.
EXAMPLE
//@version=5
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
array.copy()
The function creates a copy of an existing array.
SYNTAX
array.copy(id) → array<type>
ARGUMENTS
id (any array type) An array object.
EXAMPLE
//@version=5
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()
The function returns the covariance of two arrays.
SYNTAX
array.every()
Returns true if all elements of the id array are true, false otherwise.
SYNTAX
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
array.first()
Returns the array's first element. Throws a runtime error if the array is empty.
SYNTAX
array.from()
11 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.
SYNTAX & OVERLOADS
ARGUMENTS
arg0, arg1, ... (<arg..._type>) Array arguments.
EXAMPLE
//@version=5
indicator("array.from_example", overlay = false)
arr = array.from("Hello", "World!") // arr (array<string>) will contain 2 elements: {Hello},
{World!}.
plot(close)
RETURNS
The array element's value.
REMARKS
This function can accept up to 4,000 'int', 'float', 'bool', or 'color' arguments. For all
other types, including user-defined types, the limit is 999.
array.get()
The function returns the value of the element at the specified index.
SYNTAX
array.includes()
The function returns true if the value was found in an array, false otherwise.
SYNTAX
array.indexof()
The function returns the index of the first occurrence of the value, or -1 if the value
is not found.
SYNTAX
array.insert()
The function changes the contents of an array by adding new elements in place.
SYNTAX
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
array.last()
Returns the array's last element. Throws a runtime error if the array is empty.
SYNTAX
array.lastindexof()
The function returns the index of the last occurrence of the value, or -1 if the value is
not found.
SYNTAX
array.max()
4 overloads
The function returns the greatest value, or the nth greatest value in a given array.
SYNTAX & OVERLOADS
ARGUMENTS
id (array<int/float>) An array object.
EXAMPLE
//@version=5
indicator("array.max")
a = array.from(5, -2, 0, 9, 1)
thirdHighest = array.max(a, 2) // 1
plot(thirdHighest)
RETURNS
The greatest or the nth greatest value in the array.
SEE ALSO
array.new_floatarray.minarray.sum
array.median()
2 overloads
The function returns the median of an array's elements.
SYNTAX & OVERLOADS
ARGUMENTS
id (array<int/float>) An array object.
EXAMPLE
//@version=5
indicator("array.median example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.median(a))
RETURNS
The median of the array's elements.
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.
SYNTAX & OVERLOADS
ARGUMENTS
id (array<int/float>) An array object.
EXAMPLE
//@version=5
indicator("array.min")
a = array.from(5, -2, 0, 9, 1)
secondLowest = array.min(a, 1) // 0
plot(secondLowest)
RETURNS
The smallest or the nth smallest value in the array.
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.
SYNTAX & OVERLOADS
ARGUMENTS
id (array<int/float>) An array object.
EXAMPLE
//@version=5
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()
The function creates a new array object of bool type elements.
SYNTAX
array.new_box()
The function creates a new array object of box type elements.
SYNTAX
array.new_color()
The function creates a new array object of color type elements.
SYNTAX
array.new_float()
The function creates a new array object of float type elements.
SYNTAX
array.new_int()
The function creates a new array object of int type elements.
SYNTAX
array.new_label()
The function creates a new array object of label type elements.
SYNTAX
array.new_line()
The function creates a new array object of line type elements.
SYNTAX
array.new_linefill()
The function creates a new array object of linefill type elements.
SYNTAX
array.new_table()
The function creates a new array object of table type elements.
SYNTAX
array.new<type>()
The function creates a new array object of <type> elements.
SYNTAX
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.
SYNTAX & OVERLOADS
ARGUMENTS
id (array<int/float>) An array object.
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.
SYNTAX & OVERLOADS
ARGUMENTS
id (array<int/float>) An array object.
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
Returns the percentile rank of the element at the specified index.
SYNTAX & OVERLOADS
ARGUMENTS
id (array<int/float>) An array object.
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
array.push()
The function appends a value to an array.
SYNTAX
array.range()
2 overloads
The function returns the difference between the min and max values from a given
array.
SYNTAX & OVERLOADS
ARGUMENTS
id (array<int/float>) An array object.
EXAMPLE
//@version=5
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
array.remove(id, index) → series <type>
ARGUMENTS
id (any array type) An array object.
index (series int) The index of the element to remove.
EXAMPLE
//@version=5
indicator("array.remove example")
a = array.new_float(5,high)
removedEl = array.remove(a, 0)
plot(array.size(a))
plot(removedEl)
RETURNS
The value of the removed element.
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
id (any array type) An array object.
EXAMPLE
//@version=5
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
array.shift()
The function removes an array's first element and returns its value.
SYNTAX
array.size()
The function returns the number of elements in an array.
SYNTAX
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
array.some()
Returns true if at least one element of the id array is true, false otherwise.
SYNTAX
array.sort()
The function sorts the elements of an array.
SYNTAX
array.sort(id, order) → void
ARGUMENTS
id (array<int/float/string>) An array object.
order (series sort_order) The sort order: order.ascending (default) or
order.descending.
EXAMPLE
//@version=5
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
label.new(bar_index, close, str.tostring(a))
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
array.standardize()
2 overloads
The function returns the array of standardized elements.
SYNTAX & OVERLOADS
array.standardize(id) → array<float>
array.standardize(id) → array<int>
ARGUMENTS
id (array<int/float>) An array object.
EXAMPLE
//@version=5
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
The array of standardized elements.
SEE ALSO
array.maxarray.minarray.modearray.avgarray.variancearray.stdev
array.stdev()
2 overloads
The function returns the standard deviation of an array's elements.
SYNTAX & OVERLOADS
ARGUMENTS
id (array<int/float>) An array object.
biased (series bool) Determines which estimate should be used. Optional. The default
is true.
EXAMPLE
//@version=5
indicator("array.stdev example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.stdev(a))
RETURNS
The standard deviation of the array's elements.
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
The function returns the sum of an array's elements.
SYNTAX & OVERLOADS
ARGUMENTS
id (array<int/float>) An array object.
EXAMPLE
//@version=5
indicator("array.sum example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.sum(a))
RETURNS
The sum of the array's elements.
SEE ALSO
array.new_floatarray.maxarray.min
array.unshift()
The function inserts the value at the beginning of the array.
SYNTAX
array.variance()
2 overloads
The function returns the variance of an array's elements.
SYNTAX & OVERLOADS
array.variance(id, biased) → series float
ARGUMENTS
id (array<int/float>) An array object.
biased (series bool) Determines which estimate should be used. Optional. The default
is true.
EXAMPLE
//@version=5
indicator("array.variance example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.variance(a))
RETURNS
The variance of the array's elements.
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()
Set color of bars.
SYNTAX
bgcolor()
Fill background of bars with specified color.
SYNTAX
bool()
4 overloads
Casts na to bool
SYNTAX & OVERLOADS
ARGUMENTS
x (simple int/float/bool) The value to convert to the specified type, usually na.
RETURNS
The value of the argument after casting to bool.
SEE ALSO
floatintcolorstringlinelabel
box()
Casts na to box.
SYNTAX
box.copy()
Clones the box object.
SYNTAX
box.delete()
Deletes the specified box object. If it has already been deleted, does nothing.
SYNTAX
box.delete(id) → void
ARGUMENTS
id (series box) A box object to delete.
SEE ALSO
box.new
box.get_bottom()
Returns the price value of the bottom border of the box.
SYNTAX
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
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
box.get_top()
Returns the price value of the top border of the box.
SYNTAX
box.new()
2 overloads
Creates a new box object.
SYNTAX & OVERLOADS
ARGUMENTS
top_left (chart.point) A chart.point object that specifies the top-left corner location
of the box.
bottom_right (chart.point) A chart.point object that specifies the bottom-right
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.
border_style (series string) Style of the four borders. Possible
values: line.style_solid, line.style_dotted, line.style_dashed. Optional. The default
value is line.style_solid.
extend (series string) When 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 string) The size of the text. An optional parameter, the default
value is size.auto. Possible
values: size.auto, size.tiny, size.small, size.normal, size.large, size.huge.
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) Defines whether the text is presented in a single line,
extending past the width of the box if necessary, or wrapped so every line is no wider
than the box itself (and clipped by the bottom border of the box if the height of the
resulting wrapped text is higher than the height of the box). Optional. 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=5
indicator("box.new")
var b = box.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, border_style=line
.style_dashed)
box.set_lefttop(b, time, 100)
box.set_rightbottom(b, time + 60 * 60 * 24, 500)
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_lef
tbox.set_topbox.set_bottom_right_pointbox.set_rightbox.set_bottombox.set_border_colorbox.set
_bgcolorbox.set_border_widthbox.set_border_stylebox.set_extend
box.set_bgcolor()
Sets the background color of the box.
SYNTAX
box.set_border_color()
Sets the border color of the box.
SYNTAX
box.set_border_style()
Sets the border style of the box.
SYNTAX
box.set_border_width()
Sets the border width of the box.
SYNTAX
box.set_bottom_right_point()
Sets the bottom-right corner location of the id box to point.
SYNTAX
box.set_left()
Sets the left coordinate of the box.
SYNTAX
box.set_lefttop()
Sets the left and top coordinates of the box.
SYNTAX
box.set_right()
Sets the right coordinate of the box.
SYNTAX
box.set_rightbottom()
Sets the right and bottom coordinates of the box.
SYNTAX
box.set_text()
The function sets the text in the box.
SYNTAX
box.set_text_color()
The function sets the color of the text inside the box.
SYNTAX
box.set_text_font_family()
The function sets the font family of the text inside the box.
SYNTAX
box.set_text_halign()
The function sets the horizontal alignment of the box's text.
SYNTAX
box.set_text_size()
The function sets the size of the box's text.
SYNTAX
box.set_text_valign()
The function sets the vertical alignment of a box's text.
SYNTAX
box.set_text_wrap()
The function sets the mode of wrapping of the text inside the box.
SYNTAX
box.set_top()
Sets the top coordinate of the box.
SYNTAX
box.set_top_left_point()
Sets the top-left corner location of the id box to point.
SYNTAX
chart.point.copy(id) → chart.point
ARGUMENTS
id (chart.point) A chart.point object.
chart.point.from_index()
Returns a chart.point object with index as its x-coordinate and price as its y-
coordinate.
SYNTAX
chart.point.now()
Returns a chart.point object with price as the y-coordinate
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
SYNTAX & OVERLOADS
ARGUMENTS
x (const color) The value to convert to the specified type, usually na.
RETURNS
The value of the argument after casting to color.
SEE ALSO
floatintboolstringlinelabel
color.b()
4 overloads
Retrieves the value of the color's blue component.
SYNTAX & OVERLOADS
ARGUMENTS
color (const color) Color.
EXAMPLE
//@version=5
indicator("color.b", overlay=true)
plot(color.b(color.blue))
RETURNS
The value (0 to 255) of the color's blue component.
color.from_gradient()
Based on the relative position of value in the bottom_value to top_value range, the
function returns a color from the gradient defined by bottom_color to top_color.
SYNTAX
ARGUMENTS
color (const color) Color.
EXAMPLE
//@version=5
indicator("color.g", overlay=true)
plot(color.g(color.green))
RETURNS
The value (0 to 255) of the color's green component.
color.new()
4 overloads
Function color applies the specified transparency to the given color.
SYNTAX & OVERLOADS
ARGUMENTS
color (const color) Color to apply transparency to.
transp (const int/float) Possible values are from 0 (not transparent) to 100 (invisible).
EXAMPLE
//@version=5
indicator("color.new", overlay=true)
plot(close, color=color.new(color.red, 50))
RETURNS
Color with specified transparency.
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
Retrieves the value of the color's red component.
SYNTAX & OVERLOADS
ARGUMENTS
color (const color) Color.
EXAMPLE
//@version=5
indicator("color.r", overlay=true)
plot(color.r(color.red))
RETURNS
The value (0 to 255) of the color's red component.
color.rgb()
4 overloads
Creates a new color with transparency using the RGB color model.
SYNTAX & OVERLOADS
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=5
indicator("color.rgb", overlay=true)
plot(close, color=color.rgb(255, 0, 0, 50))
RETURNS
Color with specified transparency.
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
Retrieves the color's transparency.
SYNTAX & OVERLOADS
ARGUMENTS
color (const color) Color.
EXAMPLE
//@version=5
indicator("color.t", overlay=true)
plot(color.t(color.new(color.red, 50)))
RETURNS
The value (0-100) of the color's transparency.
dayofmonth()
2 overloads
SYNTAX & OVERLOADS
ARGUMENTS
time (series int) UNIX time in milliseconds.
RETURNS
Day of month (in exchange timezone) for provided UNIX time.
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
SYNTAX & OVERLOADS
ARGUMENTS
time (series int) UNIX time in milliseconds.
RETURNS
Day of week (in exchange timezone) for provided UNIX time.
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
Fills background between two plots or hlines with a given color.
SYNTAX & OVERLOADS
ARGUMENTS
hline1 (hline) The first hline object. Required argument.
hline2 (hline) The second hline object. Required argument.
color (series color) Color of the background fill. 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.
title (const string) Title of the created fill object. Optional argument.
editable (const bool) If true then fill style will be editable in Format dialog. Default
is true.
fillgaps (const bool) Controls continuing fills on gaps, i.e., when one of the plot()
calls returns an na value. When true, the last fill will continue on gaps. The default is
false.
display (input plot_simple_display) Controls where the fill is displayed. Possible
values are: display.none, display.all. Default is display.all.
Fill between two horizontal lines
EXAMPLE
//@version=5
indicator("Fill between hlines", overlay = false)
h1 = hline(20)
h2 = hline(10)
fill(h1, h2, color = color.new(color.blue, 90))
Fill between two plots
EXAMPLE
//@version=5
indicator("Fill between plots", overlay = true)
p1 = plot(open)
p2 = plot(close)
fill(p1, p2, color = color.new(color.green, 90))
Gradient fill between two horizontal lines
EXAMPLE
//@version=5
indicator("Gradient Fill between hlines", overlay = false)
topVal = input.int(100)
botVal = input.int(0)
topCol = input.color(color.red)
botCol = input.color(color.blue)
topLine = hline(100, color = topCol, linestyle = hline.style_solid)
botLine = hline(0, color = botCol, linestyle = hline.style_solid)
fill(topLine, botLine, topVal, botVal, topCol, botCol)
SEE ALSO
plotbarcolorbgcolorhlinecolor.new
fixnan()
4 overloads
For a given series replaces NaN values with previous nearest non-NaN value.
SYNTAX & OVERLOADS
ARGUMENTS
source (series color) Source used for the calculation.
RETURNS
Series without na gaps.
SEE ALSO
nananz
float()
4 overloads
Casts na to float
SYNTAX & OVERLOADS
ARGUMENTS
x (const int/float) The value to convert to the specified type, usually na.
RETURNS
The value of the argument after casting to float.
SEE ALSO
intboolcolorstringlinelabel
hline()
Renders a horizontal line at a given fixed price level.
SYNTAX
// You may fill the background between any two hlines with a fill() function:
h1 = hline(20)
h2 = hline(10)
fill(h1, h2, color=color.new(color.green, 90))
RETURNS
An hline object, that can be used in fill
SEE ALSO
fill
hour()
2 overloads
SYNTAX & OVERLOADS
ARGUMENTS
time (series int) UNIX time in milliseconds.
RETURNS
Hour (in exchange timezone) for provided UNIX time.
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
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.
SYNTAX & OVERLOADS
input(defval, title, tooltip, inline, group, display) → input color
ARGUMENTS
defval (const int/float/bool/string/color or source-type built-ins) Determines the
default value of the input variable proposed in the script's "Settings/Inputs" tab, from
where script users can change it. Source-type built-ins are built-in series float
variables that specify the source of the calculation: close, hlc3, etc.
title (const string) Title of the input. If not specified, the variable name is used as
the input's title. If the title is specified, but it is empty, the name will be an empty
string.
tooltip (const string) The string that will be shown to the user when hovering over
the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line.
The string used as an argument is not displayed. It is only used to identify inputs
belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument
string. The string is also used as the header's text.
display (const plot_display) Controls where the script will display the input's
information, aside from within the script's settings. This option allows one to remove
a specific input from the script's status line or the Data Window to ensure only the
most necessary inputs are displayed there. Possible
values: 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=5
indicator("input", overlay=true)
i_switch = input(true, "On/Off")
plot(i_switch ? open : na)
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.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
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) → simple enum
ARGUMENTS
defval (simple enum) Determines the default value of the input, which users can
change in the script's "Settings/Inputs" tab. When the options parameter has a
specified tuple of enum fields, the tuple must include the defval.
title (const string) Title of the input. If not specified, the variable name is used as
the input's title. If the title is specified, but it is empty, the name will be an empty
string.
options (tuple of enum fields: [enumName.field1, enumName.field2, ...]) A list of
options to choose from. Optional. By default, the titles of all of the enum's fields are
available in the dropdown. Passing a tuple as the options argument limits the list to
only the included fields.
tooltip (const string) The string that will be shown to the user when hovering over
the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line.
The string used as an argument is not displayed. It is only used to identify inputs
belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument
string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before
indicator is added to chart. Default value is false.
display (const plot_display) Controls where the script will display the input's
information, aside from within the script's settings. This option allows one to remove
a specific input from the script's status line or the Data Window to ensure only the
most necessary inputs are displayed there. Possible
values: display.none, display.data_window, display.status_line, display.all. Optional.
The default is display.all.
EXAMPLE
//@version=5
indicator("Session highlight", overlay = true)
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.
SYNTAX & OVERLOADS
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=5
indicator("input.float", overlay=true)
i_angle1 = input.float(0.5, "Sin Angle", minval=-3.14, maxval=3.14, step=0.02)
plot(math.sin(i_angle1) > 0 ? close : open, "sin", color=color.green)
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.
SYNTAX & OVERLOADS
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=5
indicator("input.int", overlay=true)
i_len1 = input.int(10, "Length 1", minval=5, maxval=21, step=1)
plot(ta.sma(close, i_len1))
input.price()
Adds a price input to the script's "Settings/Inputs" tab. Using confirm =
true activates the interactive input mode where a price is selected by clicking on the
chart.
SYNTAX
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.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
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=5
indicator("input.string", overlay=true)
i_text = input.string("Hello!", "Message")
l = label.new(bar_index, high, i_text)
label.delete(l[1])
RETURNS
Value of input variable.
REMARKS
Result of input.string function always should be assigned to a variable, see examples
above.
SEE ALSO
input.text_areainput.boolinput.intinput.floatinput.symbolinput.timeframeinput.sessioninput.sourc
einput.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
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
input.text_area(defval, title, tooltip, 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.
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=5
indicator("input.text_area")
i_text = input.text_area(defval = "Hello \nWorld!", title = "Message")
plot(close)
RETURNS
Value of input variable.
REMARKS
Result of input.text_area function always should be assigned to a variable, see
examples above.
SEE ALSO
input.stringinput.boolinput.intinput.floatinput.symbolinput.timeframeinput.sessioninput.sourcein
put.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
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
int()
4 overloads
Casts na or truncates float value to int
SYNTAX & OVERLOADS
ARGUMENTS
x (const int/float) The value to convert to the specified type, usually na.
RETURNS
The value of the argument after casting to int.
SEE ALSO
floatboolcolorstringlinelabel
label()
Casts na to label
SYNTAX
label.copy()
Clones the label object.
SYNTAX
label.copy(id) → series label
ARGUMENTS
id (series label) Label object.
EXAMPLE
//@version=5
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
var labelHigh = label.new(bar_index + highestBars, highest, str.tostring(highest), color
= color.green)
var labelLow = label.copy(labelHigh)
label.set_xy(labelLow, bar_index + lowestBars, lowest)
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
id (series label) Label object to delete.
SEE ALSO
label.new
label.get_text()
Returns the text of this label object.
SYNTAX
label.get_x()
Returns UNIX time or bar index (depending on the last xloc value set) of this label's
position.
SYNTAX
label.get_y()
Returns price of this label's position.
SYNTAX
label.new()
2 overloads
Creates new label object.
SYNTAX & OVERLOADS
label.new(point, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip,
text_font_family, force_overlay) → series label
label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip,
text_font_family, force_overlay) → series label
ARGUMENTS
point (chart.point) A chart.point object that specifies the label's location.
text (series string) Label text. Default is empty string.
xloc (series string) See description of x argument. Possible
values: xloc.bar_index and xloc.bar_time. Default is xloc.bar_index.
yloc (series string) Possible values are yloc.price, yloc.abovebar, yloc.belowbar. If
yloc=yloc.price, y argument specifies the price of the label position. If
yloc=yloc.abovebar, label is located above bar. If yloc=yloc.belowbar, label is located
below bar. Default is yloc.price.
color (series color) Color of the label border and arrow
style (series string) Label style. Possible
values: label.style_none, label.style_xcross, label.style_cross, label.style_triangleup,
label.style_triangledown, label.style_flag, label.style_circle, label.style_arrowup, lab
el.style_arrowdown, label.style_label_up, label.style_label_down, label.style_label_l
eft, label.style_label_right, label.style_label_lower_left, label.style_label_lower_righ
t, label.style_label_upper_left, label.style_label_upper_right, label.style_label_cente
r, label.style_square, label.style_diamond, label.style_text_outline. Default
is label.style_label_down.
textcolor (series color) Text color.
size (series string) Label size. Possible
values: size.auto, size.tiny, size.small, size.normal, size.large, size.huge. Default
value is size.normal.
textalign (series string) Label text alignment. Possible
values: text.align_left, text.align_center, text.align_right. Default value
is text.align_center.
tooltip (series string) Hover to see tooltip label.
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=5
indicator("label.new")
var label1 = label.new(bar_index, low, text="Hello, world!", style=label.style_circle)
label.set_x(label1, 0)
label.set_xloc(label1, time, xloc.bar_time)
label.set_color(label1, color.red)
label.set_size(label1, size.large)
RETURNS
Label ID object which may be passed to label.setXXX and label.getXXX functions.
SEE ALSO
label.deletelabel.set_xlabel.set_ylabel.set_xylabel.set_xloclabel.set_yloclabel.set_colorlabel.set_
textcolorlabel.set_stylelabel.set_sizelabel.set_textalignlabel.set_tooltip
label.set_color()
Sets label border and arrow color.
SYNTAX
label.set_point()
Sets the location of the id label to point.
SYNTAX
label.set_style()
Sets label style.
SYNTAX
label.set_text()
Sets label text
SYNTAX
label.set_text_font_family()
The function sets the font family of the text inside the label.
SYNTAX
label.set_textalign()
Sets the alignment for the label text.
SYNTAX
label.set_textcolor()
Sets color of the label text.
SYNTAX
label.set_tooltip()
Sets the tooltip text.
SYNTAX
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
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_xloc()
Sets x-location and new bar index/time value.
SYNTAX
label.set_xy()
Sets bar index/time and price of the label position.
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.
y (series int/float) New price of the label position.
SEE ALSO
label.new
label.set_y()
Sets price of the label position
SYNTAX
label.set_y(id, y) → void
ARGUMENTS
id (series label) Label object.
y (series int/float) New price of the label position.
SEE ALSO
label.new
label.set_yloc()
Sets new y-location calculation algorithm.
SYNTAX
library()
Declaration statement identifying a script as a library.
SYNTAX
library(title, overlay) → void
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.
EXAMPLE
//@version=5
// @description Math library
library("num_methods", overlay = true)
// Calculate "sinh()" from the float parameter `x`
export sinh(float x) =>
(math.exp(x) - math.exp(-x)) / 2.0
plot(sinh(0))
SEE ALSO
indicatorstrategy
line()
Casts na to line
SYNTAX
line.copy()
Clones the line object.
SYNTAX
line.delete()
Deletes the specified line object. If it has already been deleted, does nothing.
SYNTAX
line.delete(id) → void
ARGUMENTS
id (series line) Line object to delete.
SEE ALSO
line.new
line.get_price()
Returns the price level of a line at a given bar index.
SYNTAX
line.get_x1()
Returns UNIX time or bar index (depending on the last xloc value set) of the first point
of the line.
SYNTAX
line.get_x1(id) → series int
ARGUMENTS
id (series line) Line object.
EXAMPLE
//@version=5
indicator("line.get_x1")
my_line = line.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time)
a = line.get_x1(my_line)
plot(time - line.get_x1(my_line)) //draws zero plot
RETURNS
UNIX timestamp (in milliseconds) or bar index.
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
line.get_y1()
Returns price of the first point of the line.
SYNTAX
line.get_y2()
Returns price of the second point of the line.
SYNTAX
line.new()
2 overloads
Creates new line object.
SYNTAX & OVERLOADS
line.new(x1, y1, x2, y2, xloc, extend, color, style, width, force_overlay) → series line
ARGUMENTS
first_point (chart.point) A chart.point object that specifies the line's starting
coordinate.
second_point (chart.point) A chart.point object that specifies the line's ending
coordinate.
xloc (series string) See description of x1 argument. Possible
values: xloc.bar_index and xloc.bar_time. Default is xloc.bar_index.
extend (series string) If extend=extend.none, draws segment starting at point (x1,
y1) and ending at point (x2, y2). If extend is equal to extend.right or extend.left,
draws a ray starting at point (x1, y1) or (x2, y2), respectively. If extend=extend.both,
draws a straight line that goes through these points. Default value is extend.none.
color (series color) Line color.
style (series string) Line style. Possible
values: line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, lin
e.style_arrow_right, line.style_arrow_both.
width (series int) Line width in pixels.
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=5
indicator("line.new")
var line1 = line.new(0, low, bar_index, high, extend=extend.right)
var line2 = line.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, style=line.s
tyle_dashed)
line.set_x2(line1, 0)
line.set_xloc(line1, time, time + 60 * 60 * 24, xloc.bar_time)
line.set_color(line2, color.green)
line.set_width(line2, 5)
RETURNS
Line ID object which may be passed to line.setXXX and line.getXXX functions.
SEE ALSO
line.deleteline.set_x1line.set_y1line.set_xy1line.set_x2line.set_y2line.set_xy2line.set_xlocline.se
t_colorline.set_extendline.set_styleline.set_width
line.set_color()
Sets the line color
SYNTAX
line.set_extend()
Sets extending type of this line object. If extend=extend.none, draws segment
starting at point (x1, y1) and ending at point (x2, y2). If extend is equal
to extend.right or extend.left, draws a ray starting at point (x1, y1) or (x2, y2),
respectively. If extend=extend.both, draws a straight line that goes through these
points.
SYNTAX
line.set_first_point()
Sets the first point of the id line to point.
SYNTAX
line.set_width()
Sets the line width.
SYNTAX
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
id (series line) Line object.
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
id (series line) Line object.
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()
Sets x-location and new bar index/time values.
SYNTAX
line.set_xy1()
Sets bar index/time and price of the first point.
SYNTAX
line.set_xy1(id, x, y) → void
ARGUMENTS
id (series line) Line object.
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.
y (series int/float) Price.
SEE ALSO
line.new
line.set_xy2()
Sets bar index/time and price of the second point
SYNTAX
line.set_xy2(id, x, y) → void
ARGUMENTS
id (series line) Line object.
x (series int) Bar index or bar time.
y (series int/float) Price.
SEE ALSO
line.new
line.set_y1()
Sets price of the first point
SYNTAX
line.set_y1(id, y) → void
ARGUMENTS
id (series line) Line object.
y (series int/float) Price.
SEE ALSO
line.new
line.set_y2()
Sets price of the second point.
SYNTAX
line.set_y2(id, y) → void
ARGUMENTS
id (series line) Line object.
y (series int/float) Price.
SEE ALSO
line.new
linefill()
Casts na to linefill.
SYNTAX
linefill.delete()
Deletes the specified linefill object. If it has already been deleted, does nothing.
SYNTAX
linefill.delete(id) → void
ARGUMENTS
id (series linefill) A linefill object.
linefill.get_line1()
Returns the ID of the first line used in the id linefill.
SYNTAX
log.error(message) → void
ARGUMENTS
message (series string) Log message.
EXAMPLE
//@version=5
strategy("My strategy", overlay = true, margin_long = 100, margin_short = 100, process_orders
_on_close = true)
bracketTickSizeInput = input.int(1000, "Stoploss/Take-Profit distance (in ticks)")
log.info("Exit orders have been placed: Take-profit at {0}, Stop-loss at {1}", close)
strategy.exit("Exit", "My Long Entry Id", profit = bracketTickSizeInput, loss = bracketTi
ckSizeInput)
if strategy.opentrades > 10
log.warning("{0} positions opened in the same direction in a row. Try adjusting `bracketT
ickSizeInput`", strategy.opentrades)
log.info(message) → void
ARGUMENTS
message (series string) Log message.
EXAMPLE
//@version=5
strategy("My strategy", overlay = true, margin_long = 100, margin_short = 100, process_orders
_on_close = true)
bracketTickSizeInput = input.int(1000, "Stoploss/Take-Profit distance (in ticks)")
log.info("Exit orders have been placed: Take-profit at {0}, Stop-loss at {1}", close)
strategy.exit("Exit", "My Long Entry Id", profit = bracketTickSizeInput, loss = bracketTi
ckSizeInput)
if strategy.opentrades > 10
log.warning("{0} positions opened in the same direction in a row. Try adjusting `bracketT
ickSizeInput`", strategy.opentrades)
log.warning(message) → void
ARGUMENTS
message (series string) Log message.
EXAMPLE
//@version=5
strategy("My strategy", overlay = true, margin_long = 100, margin_short = 100, process_orders
_on_close = true)
bracketTickSizeInput = input.int(1000, "Stoploss/Take-Profit distance (in ticks)")
if strategy.opentrades > 10
log.warning("{0} positions opened in the same direction in a row. Try adjusting `bracketT
ickSizeInput`", strategy.opentrades)
map.clear(id) → void
ARGUMENTS
id (any map type) A map object.
EXAMPLE
//@version=5
indicator("map.clear example")
oddMap = map.new<int, bool>()
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
map.copy()
Creates a copy of an existing map.
SYNTAX
map.get()
Returns the value associated with the specified key in the id map.
SYNTAX
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
id (any map type) A map object.
EXAMPLE
//@version=5
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
for key in keys
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
map.put()
Puts a new key-value pair into the id map.
SYNTAX
map.put_all()
Puts all key-value pairs from the id2 map into the id map.
SYNTAX
map.remove()
Removes a key-value pair from the id map.
SYNTAX
map.size()
Returns the number of key-value pairs in the id map.
SYNTAX
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
id (any map type) A map object.
EXAMPLE
//@version=5
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
for value in values
ohlc += value
plot(ohlc/4)
REMARKS
Maps maintain insertion order. The elements within the array returned by this
function will also be in the insertion order.
SEE ALSO
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.
SYNTAX & OVERLOADS
ARGUMENTS
number (const int) The number to use in the calculation.
RETURNS
The absolute value of number.
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].
SYNTAX & OVERLOADS
ARGUMENTS
angle (const int/float) The value, in radians, to use in the calculation.
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].
SYNTAX & OVERLOADS
ARGUMENTS
angle (const int/float) The value, in radians, to use in the calculation.
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.
SYNTAX & OVERLOADS
ARGUMENTS
angle (const int/float) The value, in radians, to use in the calculation.
RETURNS
The arc tangent of a value; the returned angle is in the range [-Pi/2, Pi/2].
math.avg()
2 overloads
Calculates average of all given series (elementwise).
SYNTAX & OVERLOADS
ARGUMENTS
number0, number1, ... (simple int/float) A sequence of numbers to use in the
calculation.
RETURNS
Average.
SEE ALSO
math.sumta.cumta.sma
math.ceil()
4 overloads
The ceil function returns the smallest (closest to negative infinity) integer that is
greater than or equal to the argument.
SYNTAX & OVERLOADS
ARGUMENTS
number (const int/float) The number to use in the calculation.
RETURNS
The smallest integer greater than or equal to the given number.
SEE ALSO
math.floormath.round
math.cos()
4 overloads
The cos function returns the trigonometric cosine of an angle.
SYNTAX & OVERLOADS
ARGUMENTS
angle (const int/float) Angle, in radians.
RETURNS
The trigonometric cosine of an angle.
math.exp()
4 overloads
The exp function of number is e raised to the power of number, where e is Euler's
number.
SYNTAX & OVERLOADS
ARGUMENTS
number (const int/float) The number to use in the calculation.
RETURNS
A value representing e raised to the power of number.
SEE ALSO
math.pow
math.floor()
4 overloads
SYNTAX & OVERLOADS
ARGUMENTS
number (const int/float) The number to use in the calculation.
RETURNS
The largest integer less than or equal to the given 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.
SYNTAX & OVERLOADS
ARGUMENTS
number (const int/float) The number to use in the calculation.
RETURNS
The natural logarithm of number.
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
number (const int/float) The number to use in the calculation.
RETURNS
The base 10 logarithm of number.
SEE ALSO
math.log
math.max()
8 overloads
Returns the greatest of multiple values.
SYNTAX & OVERLOADS
ARGUMENTS
number0, number1, ... (const int) A sequence of numbers to use in the calculation.
EXAMPLE
//@version=5
indicator("math.max", overlay=true)
plot(math.max(close, open))
plot(math.max(close, math.max(open, 42)))
RETURNS
The greatest of multiple given values.
SEE ALSO
math.min
math.min()
8 overloads
Returns the smallest of multiple values.
SYNTAX & OVERLOADS
ARGUMENTS
number0, number1, ... (const int) A sequence of numbers to use in the calculation.
EXAMPLE
//@version=5
indicator("math.min", overlay=true)
plot(math.min(close, open))
plot(math.min(close, math.min(open, 42)))
RETURNS
The smallest of multiple given values.
SEE ALSO
math.max
math.pow()
4 overloads
Mathematical power function.
SYNTAX & OVERLOADS
ARGUMENTS
base (const int/float) Specify the base to use.
exponent (const int/float) Specifies the exponent.
EXAMPLE
//@version=5
indicator("math.pow", overlay=true)
plot(math.pow(close, 2))
RETURNS
base raised to the power of exponent. If base is a series, it is calculated
elementwise.
SEE ALSO
math.sqrtmath.exp
math.random()
Returns a pseudo-random value. The function will generate a different sequence of
values for each script execution. Using the same value for the optional seed argument
will produce a repeatable sequence.
SYNTAX
ARGUMENTS
number (const int/float) The value to be rounded.
RETURNS
The value of number rounded to the nearest integer, or according to precision.
REMARKS
Note that for 'na' values function returns 'na'.
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.
SYNTAX & OVERLOADS
ARGUMENTS
number (simple int/float) The value to be rounded.
RETURNS
The number rounded to tick precision.
REMARKS
Note that for 'na' values function returns 'na'.
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.
SYNTAX & OVERLOADS
ARGUMENTS
number (const int/float) The number to use in the calculation.
RETURNS
The sign of the argument.
math.sin()
4 overloads
The sin function returns the trigonometric sine of an angle.
SYNTAX & OVERLOADS
math.sin(angle) → const float
ARGUMENTS
angle (const int/float) Angle, in radians.
RETURNS
The trigonometric sine of an angle.
math.sqrt()
4 overloads
Square root of any number >= 0 is the unique y >= 0 such that y^2 = number.
SYNTAX & OVERLOADS
ARGUMENTS
number (const int/float) The number to use in the calculation.
RETURNS
The square root of number.
SEE ALSO
math.pow
math.sum()
The sum function returns the sliding sum of last y values of x.
SYNTAX
math.tan()
4 overloads
The tan function returns the trigonometric tangent of an angle.
SYNTAX & OVERLOADS
ARGUMENTS
angle (const int/float) Angle, in radians.
RETURNS
The trigonometric tangent of an angle.
math.todegrees()
Returns an approximately equivalent angle in degrees from an angle measured in
radians.
SYNTAX
ARGUMENTS
id (any matrix type) A matrix object.
column (series int) The index of the column after which the new column will be
inserted. Optional. The default value is matrix.columns.
Adding a column to the matrix
EXAMPLE
//@version=5
indicator("`matrix.add_col()` Example 1")
if barstate.islastconfirmedhistory
// Create an empty matrix object.
var m = matrix.new<int>()
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.
SYNTAX & OVERLOADS
ARGUMENTS
id (any matrix type) A matrix object.
row (series int) The index of the row after which the new row will be inserted.
Optional. The default value is matrix.rows.
Adding a row to the matrix
EXAMPLE
//@version=5
indicator("`matrix.add_row()` Example 1")
if barstate.islastconfirmedhistory
// Create an empty matrix object.
var m = matrix.new<int>()
// Add the `a` array as the first row of the empty matrix.
matrix.add_row(m, 0, a)
matrix.avg()
2 overloads
The function calculates the average of all elements in the matrix.
SYNTAX & OVERLOADS
ARGUMENTS
id (matrix<int/float>) A matrix object.
EXAMPLE
//@version=5
indicator("`matrix.avg()` Example")
matrix.col()
The function creates a one-dimensional array from the elements of a matrix column.
SYNTAX
// Return an array with the values of the first column of matrix `m`.
a = matrix.col(m, 0)
matrix.columns()
The function returns the number of columns in the matrix.
SYNTAX
matrix.concat()
The function appends the m2 matrix to the m1 matrix.
SYNTAX
matrix.copy(id) → matrix<type>
ARGUMENTS
id (any matrix type) A matrix object to copy.
EXAMPLE
//@version=5
indicator("`matrix.copy()` Example")
matrix.det()
2 overloads
The function returns the determinant of a square matrix.
SYNTAX & OVERLOADS
ARGUMENTS
id (matrix<int/float>) A matrix object.
EXAMPLE
//@version=5
indicator("`matrix.det` Example")
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).
SYNTAX & OVERLOADS
ARGUMENTS
id1 (matrix<int>) Matrix to subtract from.
id2 (series int/float/matrix<int>) Matrix object or a scalar value to be subtracted.
Difference between two matrices
EXAMPLE
//@version=5
indicator("`matrix.diff()` Example 1")
// Create a new matrix containing the difference between the `m1` matrix and the "int" va
lue `1`.
var m2 = matrix.diff(m1, 1)
matrix.eigenvalues()
2 overloads
The function returns an array containing the eigenvalues of a square matrix.
SYNTAX & OVERLOADS
matrix.eigenvalues(id) → array<float>
matrix.eigenvalues(id) → array<int>
ARGUMENTS
id (matrix<int/float>) A matrix object.
EXAMPLE
//@version=5
indicator("`matrix.eigenvalues()` Example")
matrix.eigenvectors()
2 overloads
Returns a matrix of eigenvectors, in which each column is an eigenvector of
the id matrix.
SYNTAX & OVERLOADS
matrix.eigenvectors(id) → matrix<float>
matrix.eigenvectors(id) → matrix<int>
ARGUMENTS
id (matrix<int/float>) A matrix object.
EXAMPLE
//@version=5
indicator("`matrix.eigenvectors()` Example")
matrix.elements_count()
The function returns the total number of all matrix elements.
SYNTAX
matrix.fill()
The function fills a rectangular area of the id matrix defined by the
indices from_column to to_column (not including it) and from_row to to_row(not
including it) with the value.
SYNTAX
// 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)
matrix.get()
The function returns the element with the specified index of the matrix.
SYNTAX
plot(x)
RETURNS
The value of the element at the row and column index of the id matrix.
REMARKS
Indexing of the rows and columns starts at zero.
SEE ALSO
matrix.new<type>matrix.setmatrix.columnsmatrix.rows
matrix.inv()
2 overloads
The function returns the inverse of a square matrix.
SYNTAX & OVERLOADS
matrix.inv(id) → matrix<float>
matrix.inv(id) → matrix<int>
ARGUMENTS
id (matrix<int/float>) A matrix object.
EXAMPLE
//@version=5
indicator("`matrix.inv()` Example")
matrix.is_antidiagonal()
The function determines if the matrix is anti-diagonal (all elements outside the
secondary diagonal are zero).
SYNTAX
matrix.is_antisymmetric()
The function determines if a matrix is antisymmetric (its transpose equals its
negative).
SYNTAX
matrix.is_binary()
The function determines if the matrix is binary (when all elements of the matrix are 0
or 1).
SYNTAX
matrix.is_diagonal()
The function determines if the matrix is diagonal (all elements outside the main
diagonal are zero).
SYNTAX
matrix.is_identity()
The function determines if a matrix is an identity matrix (elements with ones on
the main diagonal and zeros elsewhere).
SYNTAX
matrix.is_square()
The function determines if the matrix is square (it has the same number of rows and
columns).
SYNTAX
matrix.is_stochastic()
The function determines if the matrix is stochastic.
SYNTAX
matrix.is_symmetric()
The function determines if a square matrix is symmetric (elements are symmetric
with respect to the main diagonal).
SYNTAX
matrix.is_triangular()
The function determines if the matrix is triangular (if all elements above or below
the main diagonal are zero).
SYNTAX
matrix.is_zero()
The function determines if all elements of the matrix are zero.
SYNTAX
matrix.kron()
2 overloads
The function returns the Kronecker product for the id1 and id2 matrices.
SYNTAX & OVERLOADS
ARGUMENTS
id1 (matrix<int/float>) First matrix object.
id2 (matrix<int/float>) Second matrix object.
EXAMPLE
//@version=5
indicator("`matrix.kron()` Example")
matrix.max()
2 overloads
The function returns the largest value from the matrix elements.
SYNTAX & OVERLOADS
ARGUMENTS
id (matrix<int/float>) A matrix object.
EXAMPLE
//@version=5
indicator("`matrix.max()` Example")
// Create a 2x2 matrix.
var m = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m, 0, 0, 1)
matrix.set(m, 0, 1, 2)
matrix.set(m, 1, 0, 3)
matrix.set(m, 1, 1, 4)
matrix.median()
2 overloads
The function calculates the median ("the middle" value) of matrix elements.
SYNTAX & OVERLOADS
ARGUMENTS
id (matrix<int/float>) A matrix object.
EXAMPLE
//@version=5
indicator("`matrix.median()` Example")
matrix.min()
2 overloads
The function returns the smallest value from the matrix elements.
SYNTAX & OVERLOADS
ARGUMENTS
id (matrix<int/float>) A matrix object.
EXAMPLE
//@version=5
indicator("`matrix.min()` Example")
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.
SYNTAX & OVERLOADS
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).
SYNTAX & OVERLOADS
ARGUMENTS
id1 (matrix<int>) First matrix object.
id2 (array<int>) Second matrix object, value or array.
Product of two matrices
EXAMPLE
//@version=5
indicator("`matrix.mult()` Example 1")
// Create a new matrix containing the product of the `m1` matrix and the `a` array.
var m3 = matrix.mult(m1, a)
matrix.new<type>()
The function creates a new matrix object. A matrix is a two-dimensional data
structure containing rows and columns. All elements in the matrix must be of the type
specified in the type template ("<type>").
SYNTAX
// Function to create a matrix whose rows are filled with array values.
matrixFromArray(int rows, int columns, array<float> data) =>
m = matrix.new<float>(rows, columns)
for i = 0 to rows <= 0 ? na : rows - 1
for j = 0 to columns <= 0 ? na : columns - 1
matrix.set(m, i, j, array.get(data, i * columns + j))
m
matrix.pinv()
2 overloads
The function returns the pseudoinverse of a matrix.
SYNTAX & OVERLOADS
matrix.pinv(id) → matrix<float>
matrix.pinv(id) → matrix<int>
ARGUMENTS
id (matrix<int/float>) A matrix object.
EXAMPLE
//@version=5
indicator("`matrix.pinv()` Example")
matrix.pow()
2 overloads
The function calculates the product of the matrix by itself power times.
SYNTAX & OVERLOADS
ARGUMENTS
id (matrix<int/float>) A matrix object.
power (series int) The number of times the matrix will be multiplied by itself.
EXAMPLE
//@version=5
indicator("`matrix.pow()` Example")
matrix.rank()
The function calculates the rank of the matrix.
SYNTAX
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
matrix.reshape()
The function rebuilds the id matrix to rows x cols dimensions.
SYNTAX
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
id (any matrix type) A matrix object.
EXAMPLE
//@version=5
indicator("`matrix.reverse()` Example")
matrix.row()
The function creates a one-dimensional array from the elements of a matrix row.
SYNTAX
// Return an array with the values of the first row of the matrix.
a = matrix.row(m, 0)
matrix.rows()
The function returns the number of rows in the matrix.
SYNTAX
matrix.set()
The function assigns value to the element at the row and column of the id matrix.
SYNTAX
matrix.sort()
The function rearranges the rows in the id matrix following the sorted order of the
values in the column.
SYNTAX
matrix.submatrix()
The function extracts a submatrix of the id matrix within the specified indices.
SYNTAX
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).
SYNTAX & OVERLOADS
ARGUMENTS
id1 (matrix<int>) First matrix object.
id2 (series int/float/matrix<int>) Second matrix object, or scalar value.
Sum of two matrices
EXAMPLE
//@version=5
indicator("`matrix.sum()` Example 1")
// Create a new matrix containing the sum of the `m1` matrix with the "int" value `1`.
var m2 = matrix.sum(m1, 1)
matrix.swap_columns()
The function swaps the columns at the index column1 and column2 in
the id matrix.
SYNTAX
matrix.swap_rows()
The function swaps the rows at the index row1 and row2 in the id matrix.
SYNTAX
matrix.trace()
2 overloads
The function calculates the trace of a matrix (the sum of the main diagonal's
elements).
SYNTAX & OVERLOADS
ARGUMENTS
id (matrix<int/float>) A matrix object.
EXAMPLE
//@version=5
indicator("`matrix.trace()` Example")
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
id (any matrix type) A matrix object.
EXAMPLE
//@version=5
indicator("`matrix.transpose()` Example")
max_bars_back()
Function sets the maximum number of bars that is available for historical reference of
a given built-in or user variable. When operator '[]' is applied to a variable - it is a
reference to a historical value of that variable.
If an argument of an operator '[]' is a compile time constant value (e.g. 'v[10]',
'close[500]') then there is no need to use 'max_bars_back' function for that variable.
Pine Script® compiler will use that constant value as history buffer size.
If an argument of an operator '[]' is a value, calculated at runtime (e.g. 'v[i]' where 'i' -
is a series variable) then Pine Script® attempts to autodetect the history buffer size
at runtime. Sometimes it fails and the script crashes at runtime because it eventually
refers to historical values that are out of the buffer. In that case you should use
'max_bars_back' to fix that problem manually.
SYNTAX
max_bars_back(var, num) → void
ARGUMENTS
var (series int/float/bool/color/label/line) Series variable identifier for which history
buffer should be resized. Possible values are: 'open', 'high', 'low', 'close', 'volume',
'time', or any user defined variable id.
num (const int) History buffer size which is the number of bars that could be
referenced for variable 'var'.
EXAMPLE
//@version=5
indicator("max_bars_back")
close_() => close
depth() => 400
d = depth()
v = close_()
max_bars_back(v, 500)
out = if bar_index > 0
v[d]
else
v
plot(out)
RETURNS
void
REMARKS
At the moment 'max_bars_back' cannot be applied to built-ins like 'hl2', 'hlc3', 'ohlc4'.
Please use multiple 'max_bars_back' calls as workaround here (e.g. instead of a single
‘max_bars_back(hl2, 100)’ call you should call the function twice:
‘max_bars_back(high, 100), max_bars_back(low, 100)’).
If the indicator or strategy 'max_bars_back' parameter is used, all variables in the
indicator are affected. This may result in excessive memory usage and cause runtime
problems. When possible (i.e. when the cause is a variable rather than a function),
please use the max_bars_back function instead.
SEE ALSO
indicator
minute()
2 overloads
SYNTAX & OVERLOADS
ARGUMENTS
time (series int) UNIX time in milliseconds.
RETURNS
Minute (in exchange timezone) for provided UNIX time.
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
SYNTAX & OVERLOADS
ARGUMENTS
time (series int) UNIX time in milliseconds.
RETURNS
Month (in exchange timezone) for provided UNIX time.
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.
SYNTAX & OVERLOADS
ARGUMENTS
x (<arg_type>) Value to be tested.
EXAMPLE
//@version=5
indicator("na")
// Use the `na()` function to test for `na`.
plot(na(close[1]) ? close : close[1])
// ALTERNATIVE
// `nz()` also tests `close[1]` for `na`. It returns `close[1]` if it is not `na`, and `close
` if it is.
plot(nz(close[1], close))
RETURNS
Returns true if x is na, false otherwise.
SEE ALSO
nafixnannz
nz()
16 overloads
Replaces NaN values with zeros (or given value) in a series.
SYNTAX & OVERLOADS
ARGUMENTS
source (simple color) Series of values to process.
EXAMPLE
//@version=5
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()
Plots a series of data on the chart.
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.
title (const string) Title of the plot.
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.
style (input plot_style) Type of plot. Possible values
are: plot.style_line, plot.style_stepline, plot.style_stepline_diamond, plot.style_histo
gram, plot.style_cross, plot.style_area, plot.style_columns, plot.style_circles, plot.st
yle_linebr, plot.style_areabr, plot.style_steplinebr. Default value is plot.style_line.
trackprice (input bool) If true then a horizontal price line will be shown at the level
of the last indicator value. Default is false.
histbase (input int/float) The price value used as the reference level when rendering
plot with plot.style_histogram, plot.style_columns or plot.style_area style. Default is
0.0.
offset (series 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 (const bool) If true then plot style will be editable in Format dialog. Default
is true.
show_last (input int) If set, defines the number of bars (from the last bar back to the
past) to plot on chart.
display (input plot_display) Controls where the plot's information is displayed.
Display options support addition and subtraction, meaning that using display.all
- display.status_line will display the plot's information everywhere except in
the script's status line. display.price_scale + display.status_line will
display the plot only in the price scale and status line. When display arguments
such as display.price_scale have user-controlled chart settings equivalents, the
relevant plot information will only appear when all settings allow for it. Possible
values: display.none, display.pane, display.data_window, display.price_scale, display.
status_line, display.all. Optional. The default is display.all.
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=5
indicator("plot")
plot(high+low, title='Title', color=color.new(#00ffaa, 70), linewidth=2, style=plot.style_are
a, offset=15, trackprice=true)
// You may fill the background between any two plots with a fill() function:
p1 = plot(open)
p2 = plot(close)
fill(p1, p2, color=color.new(color.green, 90))
RETURNS
A plot object, that can be used in fill
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
plotbar()
Plots ohlc bars on the chart.
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.
title (const string) Title of the plotbar. Optional 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 (const bool) If true then plotbar style will be editable in Format dialog.
Default is true.
show_last (input int) If set, defines the number of bars (from the last bar back to the
past) to plot on chart.
display (input plot_display) Controls where the plot's information is displayed.
Display options support addition and subtraction, meaning that using display.all
- display.status_line will display the plot's information everywhere except in
the script's status line. display.price_scale + display.status_line will
display the plot only in the price scale and status line. When display arguments
such as display.price_scale have user-controlled chart settings equivalents, the
relevant plot information will only appear when all settings allow for it. Possible
values: display.none, display.pane, display.data_window, display.price_scale, display.
status_line, display.all. Optional. The default is display.all.
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=5
indicator("plotbar example", overlay=true)
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()
Plots candles on the chart.
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.
title (const string) Title of the plotcandles. Optional 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 (const bool) If true then plotcandle style will be editable in Format dialog.
Default is true.
show_last (input int) If set, defines the number of candles (from the last bar back to
the past) to plot on chart.
bordercolor (series color) The border color of candles. An optional argument.
display (input plot_display) Controls where the plot's information is displayed.
Display options support addition and subtraction, meaning that using display.all
- display.status_line will display the plot's information everywhere except in
the script's status line. display.price_scale + display.status_line will
display the plot only in the price scale and status line. When display arguments
such as display.price_scale have user-controlled chart settings equivalents, the
relevant plot information will only appear when all settings allow for it. Possible
values: display.none, display.pane, display.data_window, display.price_scale, display.
status_line, display.all. Optional. The default is display.all.
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=5
indicator("plotcandle example", overlay=true)
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
series (series int/float/bool) Series of data to be plotted as shapes. Series is treated
as a series of boolean values for all location values except location.absolute. Required
argument.
title (const string) Title of the plot.
char (input string) Character to use as a visual shape.
location (input string) Location of shapes on the chart. Possible values
are: location.abovebar, location.belowbar, location.top, location.bottom, location.ab
solute. Default value is location.abovebar.
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 (series 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 (const bool) If true then plotchar style will be editable in Format dialog.
Default is true.
size (const string) Size of characters on the chart. Possible values
are: size.auto, size.tiny, size.small, size.normal, size.large, size.huge. Default
is size.auto.
show_last (input int) If set, defines the number of chars (from the last bar back to
the past) to plot on chart.
display (input plot_display) Controls where the plot's information is displayed.
Display options support addition and subtraction, meaning that using display.all
- display.status_line will display the plot's information everywhere except in
the script's status line. display.price_scale + display.status_line will
display the plot only in the price scale and status line. When display arguments
such as display.price_scale have user-controlled chart settings equivalents, the
relevant plot information will only appear when all settings allow for it. Possible
values: display.none, display.pane, display.data_window, display.price_scale, display.
status_line, display.all. Optional. The default is display.all.
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=5
indicator("plotchar example", overlay=true)
data = close >= open
plotchar(data, char='❄')
REMARKS
Use plotchar function in conjunction with 'overlay=true' indicator parameter!
SEE ALSO
plotplotshapeplotarrowbarcolorbgcolor
plotshape()
Plots visual shapes on the chart.
SYNTAX
plotshape(series, title, style, location, color, offset, text, textcolor, editable, size,
show_last, display, format, precision, force_overlay) → void
ARGUMENTS
series (series int/float/bool) Series of data to be plotted as shapes. Series is treated
as a series of boolean values for all location values except location.absolute. Required
argument.
title (const string) Title of the plot.
style (input string) Type of plot. Possible values
are: shape.xcross, shape.cross, shape.triangleup, shape.triangledown, shape.flag, sha
pe.circle, shape.arrowup, shape.arrowdown, shape.labelup, shape.labeldown, shape.
square, shape.diamond. Default value is shape.xcross.
location (input string) Location of shapes on the chart. Possible values
are: location.abovebar, location.belowbar, location.top, location.bottom, location.ab
solute. Default value is location.abovebar.
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 (series 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 (const bool) If true then plotshape style will be editable in Format dialog.
Default is true.
size (const string) Size of shapes on the chart. Possible values
are: size.auto, size.tiny, size.small, size.normal, size.large, size.huge. Default
is size.auto.
show_last (input int) If set, defines the number of shapes (from the last bar back to
the past) to plot on chart.
display (input plot_display) Controls where the plot's information is displayed.
Display options support addition and subtraction, meaning that using display.all
- display.status_line will display the plot's information everywhere except in
the script's status line. display.price_scale + display.status_line will
display the plot only in the price scale and status line. When display arguments
such as display.price_scale have user-controlled chart settings equivalents, the
relevant plot information will only appear when all settings allow for it. Possible
values: display.none, display.pane, display.data_window, display.price_scale, display.
status_line, display.all. Optional. The default is display.all.
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=5
indicator("plotshape example 1", overlay=true)
data = close >= open
plotshape(data, style=shape.xcross)
REMARKS
Use plotshape function in conjunction with 'overlay=true' indicator parameter!
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
id (series polyline) The polyline ID to delete.
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
points (array<chart.point>) An array of chart.point objects for the drawing to
sequentially connect.
curved (series bool) If true, the drawing will connect all points from
the points array using curved line segments. Optional. The default is false.
closed (series bool) If true, the drawing will also connect the first point to the last
point from the points array, resulting in a closed polyline. Optional. The default
is false.
xloc (series string) Determines the field of the chart.point objects in
the points array that the polyline will use for its x-coordinates. If xloc.bar_index,
the polyline will use the index field from each point. If xloc.bar_time, it will use
the time field. Optional. The default is xloc.bar_index.
line_color (series color) The color of the line segments. Optional. The default
is color.blue.
fill_color (series color) The fill color of the polyline. Optional. The default is na.
line_style (series string) The style of the polyline. Possible
values: line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, lin
e.style_arrow_right, line.style_arrow_both. Optional. The default is line.style_solid.
line_width (series int) The width of the line segments, expressed in pixels. Optional.
The default is 1.
force_overlay (const bool) If true, the drawing will display on the main chart pane,
even when the script occupies a separate pane. Optional. The default is false.
EXAMPLE
//@version=5
indicator("Polylines example", overlay = true)
//@variable If `true`, connects all points in the polyline with curved line segments.
bool curvedInput = input.bool(false, "Curve Polyline")
//@variable If `true`, connects the first point in the polyline to the last point.
bool closedInput = input.bool(true, "Close Polyline")
//@variable The color of the space filled by the polyline.
color fillcolor = input.color(color.new(color.blue, 90), "Fill Color")
if barstate.islastconfirmedhistory
//@variable An array of `chart.point` objects for the new polyline.
var points = array.new<chart.point>()
// Push new `chart.point` instances into the `points` array.
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))
// Add labels for each `chart.point` in `points`.
l1p1 = label.new(points.get(0), text = "p1", xloc = xloc.bar_time, color = na)
l1p2 = label.new(points.get(1), text = "p2", xloc = xloc.bar_time, color = na)
l2p1 = label.new(points.get(2), text = "p3", xloc = xloc.bar_time, color = na)
l2p2 = label.new(points.get(3), text = "p4", xloc = xloc.bar_time, color = na)
// Create a new polyline that connects each `chart.point` in the `points` array, starting
from the first.
polyline.new(points, curved = curvedInput, closed = closedInput, fill_color = fillcolor,
xloc = xloc.bar_time)
RETURNS
The ID of a new polyline object that a script can use in
other polyline.*() functions.
SEE ALSO
chart.point.new
request.currency_rate()
Provides a daily rate that can be used to convert a value expressed in
the from currency to another in the to currency.
SYNTAX
request.earnings()
Requests earnings data for the specified symbol.
SYNTAX
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
request.financial()
Requests financial series for symbol.
SYNTAX
request.quandl()
Requests Nasdaq Data Link (formerly Quandl) data for a symbol.
SYNTAX
request.security()
Requests data from another symbol and/or timeframe.
SYNTAX
// Returns the close of "AAPL" from the same timeframe as currently open on the chart.
aaplClose = request.security("AAPL", timeframe.period, close)
plot(aaplClose)
EXAMPLE
//@version=5
indicator("Advanced `request.security()` calls")
// This calculates a 10-period moving average on the active chart.
sma = ta.sma(close, 10)
// This sends the `sma` calculation for execution in the context of the "AAPL" symbol at a "2
40" (4 hours) timeframe.
aaplSma = request.security("AAPL", "240", sma)
plot(aaplSma)
// To avoid differences on historical and realtime bars, you can use this technique, which on
ly returns a value from the higher timeframe on the bar after it completes:
indexHighTF = barstate.isrealtime ? 1 : 0
indexCurrTF = barstate.isrealtime ? 0 : 1
nonRepaintingClose = request.security(syminfo.tickerid, "1D", close[indexHighTF])[indexCurrTF
]
plot(nonRepaintingClose, "Non-repainting close")
// Returns the 1H close of "AAPL", extended session included. The value is dividend-adjusted.
extendedTicker = ticker.modify("NASDAQ:AAPL", session = session.extended, adjustment = adjust
ment.dividends)
aaplExtAdj = request.security(extendedTicker, "60", close)
plot(aaplExtAdj)
// 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, hig
h, low, close, ta.ema(close, 10)])
plotcandle(open1D, high1D, low1D, close1D)
plot(ema1D)
// Returns an array containing the OHLC values of the chart's symbol from the 1D timeframe.
ohlcArray = request.security(syminfo.tickerid, "1D", array.from(open, high, low, close))
plotcandle(array.get(ohlcArray, 0), array.get(ohlcArray, 1), array.get(ohlcArray, 2), array.g
et(ohlcArray, 3))
RETURNS
A result determined by expression.
REMARKS
Pine Script® code using this function may calculate differently on historical and
realtime bars, leading to repainting.
A single script can have no more than 40 calls to request.*() functions.
SEE ALSO
syminfo.tickersyminfo.tickeridtimeframe.periodticker.newticker.modifyrequest.security_lower_tf
request.dividendsrequest.earningsrequest.splitsrequest.financialrequest.quandl
request.security_lower_tf()
Requests data from a specified symbol from a lower timeframe than the chart's. The
function returns an array containing one element for each closed lower timeframe
intrabar inside the current chart's bar. On a 5-minute chart using
a timeframe argument of "1", the size of the array will usually be 5, with each array
element representing the value of expression on a 1-minute intrabar, ordered
sequentially in time.
SYNTAX
// If the current chart timeframe is set to 120 minutes, then the `arrayClose` array will con
tain two 'close' values from the 60 minute timeframe for each bar.
arrClose = request.security_lower_tf(syminfo.tickerid, "60", close)
if bar_index == last_bar_index - 1
label.new(bar_index, high, str.tostring(arrClose))
RETURNS
An array of a type determined by expression, or a tuple of these.
REMARKS
Pine Script® code using this function may calculate differently on historical and real-
time bars, leading to repainting.
Please note that spreads (e.g., “AAPL+MSFT*TSLA”) will not always return reliable
data with this function.
A single script can have no more than 40 calls to request.*() functions.
A maximum of 100,000 lower timeframe bars can be accessed by this function. The
number of chart bars for which lower timeframe data is available will thus vary with
the requested lower timeframe.
SEE ALSO
request.securitysyminfo.tickersyminfo.tickeridtimeframe.periodticker.newrequest.dividendsreque
st.earningsrequest.splitsrequest.financialrequest.quandl
request.seed()
Requests data from a user-maintained GitHub repository and returns it as a series. An
in-depth tutorial on how to add new data can be found here.
SYNTAX
request.seed(source, symbol, expression, ignore_invalid_symbol, calc_bars_count) → series
<type>
ARGUMENTS
source (series string) Name of the GitHub repository.
symbol (series string) Name of the file in the GitHub repository containing the data.
The ".csv" file extension must not be included.
expression (<arg_expr_type>) An expression to be calculated and returned from the
requested symbol's context. It can be a built-in variable like close, an expression such
as ta.sma(close, 100), a non-mutable variable previously calculated in the
script, a function call that does not use Pine Script® drawings, an array, a matrix, or
a tuple. Mutable variables are not allowed, unless they are enclosed in the body of a
function used in the expression.
ignore_invalid_symbol (input bool) Determines the behavior of the function if the
specified symbol is not found: if false, the script will halt and throw a runtime error;
if true, the function will return na and execution will continue. Optional. The default
is false.
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 na.
EXAMPLE
//@version=5
indicator("BTC Development Activity")
runtime.error()
When called, causes a runtime error with the error message specified in
the message argument.
SYNTAX
runtime.error(message) → void
ARGUMENTS
message (series string) Error message.
second()
2 overloads
SYNTAX & OVERLOADS
second(time) → series int
ARGUMENTS
time (series int) UNIX time in milliseconds.
RETURNS
Second (in exchange timezone) for provided UNIX time.
REMARKS
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.
SYNTAX & OVERLOADS
ARGUMENTS
source (const string) Source string.
str (const string) The substring to search for.
EXAMPLE
//@version=5
indicator("str.contains")
// If the current chart is a continuous futures chart, e.g “BTC1!”, then the function will
return true, false otherwise.
var isFutures = str.contains(syminfo.tickerid, "!")
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.
SYNTAX & OVERLOADS
ARGUMENTS
source (const string) Source string.
str (const string) The substring to search for.
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.
SYNTAX & OVERLOADS
ARGUMENTS
formatString (simple string) Format string.
arg0, arg1, ... (simple int/float/bool/string) Values to format.
EXAMPLE
//@version=5
indicator("str.format", overlay=true)
// The format specifier inside the curly braces accepts certain modifiers:
// - Specify the number of decimals to display:
s1 = str.format("{0,number,#.#}", 1.34) // returns: 1.3
label.new(bar_index, close, text=s1)
// - Round a float value to an integer:
s2 = str.format("{0,number,integer}", 1.34) // returns: 1
label.new(bar_index - 1, close, text=s2)
// - Display a number in currency:
s3 = str.format("{0,number,currency}", 1.34) // returns: $1.34
label.new(bar_index - 2, close, text=s3)
// - Display a number as a percentage:
s4 = str.format("{0,number,percent}", 0.5) // returns: 50%
label.new(bar_index - 3, close, text=s4)
// EXAMPLES WITH SEVERAL ARGUMENTS
// returns: Number 1 is not equal to 4
s5 = str.format("Number {0} is not {1} to {2}", 1, "equal", 4)
label.new(bar_index - 4, close, text=s5)
// returns: 1.34 != 1.3
s6 = str.format("{0} != {0, number, #.#}", 1.34)
label.new(bar_index - 5, close, text=s6)
// returns: 1 is equal to 1, but 2 is equal to 2
s7 = str.format("{0, number, integer} is equal to 1, but {1, number, integer} is equal to 2",
1.34, 1.52)
label.new(bar_index - 6, close, text=s7)
// returns: The cash turnover amounted to $1,340,000.00
s8 = str.format("The cash turnover amounted to {0, number, currency}", 1340000)
label.new(bar_index - 7, close, text=s8)
// returns: Expected return is 10% - 20%
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
The formatted string.
REMARKS
By default, formatted numbers will display up to three decimals with no trailing
zeros.
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()
Converts the time timestamp into a string formatted according
to format and timezone.
SYNTAX
ARGUMENTS
string (const string) Source string.
RETURNS
The number of chars in source string.
str.lower()
3 overloads
Returns a new string with all letters converted to lowercase.
SYNTAX & OVERLOADS
ARGUMENTS
source (const string) String to be converted.
RETURNS
A new string with all letters converted to lowercase.
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.
SYNTAX & OVERLOADS
ARGUMENTS
source (simple string) Source string.
regex (simple string) The regular expression to which this string is to be matched.
EXAMPLE
//@version=5
indicator("str.match")
s = input.string("It's time to sell some NASDAQ:AAPL!")
if barstate.islastconfirmedhistory
label.new(bar_index, high, text = tickerid) // "NASDAQ:AAPL"
RETURNS
The new substring of the source string if it matches a regex regular expression, an
empty string otherwise.
REMARKS
Function returns first occurrence of the regular expression in the source string.
The backslash "" symbol in 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.
SYNTAX & OVERLOADS
ARGUMENTS
source (const string) Source string.
str (const string) The substring to search for.
RETURNS
Position of the str string in the source string.
REMARKS
Strings indexing starts at 0.
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.
SYNTAX & OVERLOADS
ARGUMENTS
source (const string) String to repeat.
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=5
indicator("str.repeat")
repeat = str.repeat("?", 3, ",") // Returns "?,?,?"
label.new(bar_index,close,repeat)
REMARKS
Returns na if the source is na.
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.
SYNTAX & OVERLOADS
ARGUMENTS
source (const string) Source string.
target (const string) String to be replaced.
replacement (const string) String to be inserted instead of the target string.
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=5
indicator("str.replace")
var source = "FTX:BTCUSD / FTX:BTCEUR"
if barstate.islastconfirmedhistory
// Display "BINANCE:BTCUSD / FTX:BTCEUR"
label.new(bar_index, high, text = newSource)
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.
SYNTAX & OVERLOADS
ARGUMENTS
source (simple string) Source string.
target (simple string) String to be replaced.
replacement (simple string) String to be substituted for each occurrence of target
string.
RETURNS
Processed string.
str.split()
Divides a string into an array of substrings and returns its array id.
SYNTAX
ARGUMENTS
source (const string) Source string.
str (const string) The substring to search for.
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.
SYNTAX & OVERLOADS
ARGUMENTS
source (const string) Source string from which to extract the substring.
begin_pos (const int) The beginning position of the extracted substring. It is inclusive
(the extracted substring includes the character at that position).
EXAMPLE
//@version=5
indicator("str.substring", overlay = true)
sym= input.symbol("NASDAQ:AAPL")
pos = str.pos(sym, ":") // Get position of ":" character
tkr= str.substring(sym, pos+1) // "AAPL"
if barstate.islastconfirmedhistory
label.new(bar_index, high, text = tkr)
RETURNS
The substring extracted from the source string.
REMARKS
Strings indexing starts from 0. If begin_pos is equal to end_pos, the function
returns an empty string.
SEE ALSO
str.containsstr.posstr.match
str.tonumber()
4 overloads
Converts a value represented in string to its "float" equivalent.
SYNTAX & OVERLOADS
ARGUMENTS
string (const string) String containing the representation of an integer or floating
point value.
RETURNS
A "float" equivalent of the value in string. If the value is not a properly formed
integer or floating point value, the function returns na.
str.tostring()
4 overloads
SYNTAX & OVERLOADS
ARGUMENTS
value (simple int/float) Value or array ID whose elements are converted to a string.
format (simple string) Format string. Accepts these format.*
constants: format.mintick, format.percent, format.volume. Optional. The default
value is '#.##########'.
RETURNS
The string representation of the value argument.
If the value argument is a string, it is returned as is.
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.
If the x argument is a string, the same string value will be returned.
Bool type arguments return "true" or "false".
When x is na, the function returns "NaN".
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.
SYNTAX & OVERLOADS
ARGUMENTS
source (const string) String to trim.
EXAMPLE
//@version=5
indicator("str.trim")
trim = str.trim(" abc ") // Returns "abc"
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
Returns a new string with all letters converted to uppercase.
SYNTAX & OVERLOADS
ARGUMENTS
source (const string) String to be converted.
RETURNS
A new string with all letters converted to uppercase.
SEE ALSO
str.lower
strategy()
This declaration statement designates the script as a strategy and sets a number of
strategy-related properties.
SYNTAX
strategy.cancel()
It is a command to cancel/deactivate pending orders by referencing their names,
which were generated by the
functions: strategy.order, strategy.entry and strategy.exit.
SYNTAX
strategy.cancel(id) → void
ARGUMENTS
id (series string) A required parameter. The order identifier. It is possible to cancel
an order by referencing its identifier.
EXAMPLE
//@version=5
strategy(title = "simple order cancellation example")
conditionForBuy = open > high[1]
if conditionForBuy
strategy.entry("long", strategy.long, 1, limit = low) // enter long using limit order at
low price of current 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()
A command to cancel/deactivate all pending orders generated by any of the following
functions: strategy.order, strategy.entry, strategy.exit, and strategy.close.
SYNTAX
strategy.cancel_all() → void
EXAMPLE
//@version=5
strategy(title = "simple all orders cancellation example")
conditionForBuy1 = open > high[1]
if conditionForBuy1
strategy.entry("long entry 1", strategy.long, 1, limit = low) // enter long by limit if c
onditionForBuy1 is true
conditionForBuy2 = conditionForBuy1 and open[1] > high[2]
if conditionForBuy2
strategy.entry("long entry 2", strategy.long, 1, limit = ta.lowest(low, 2)) // enter long
by limit if conditionForBuy2 is true
conditionForStopTrading = open < ta.lowest(low, 2)
if conditionForStopTrading
strategy.cancel_all() // cancel both limit orders if the conditon conditionForStopTrading
is true
strategy.close()
It is a command to exit from the entry with the specified ID. If there were multiple
entry orders with the same ID, all of them are exited at once. If there are no open
entries with the specified ID by the moment the command is triggered, the command
will not come into effect. The command uses market order. Every entry is closed by a
separate market order.
SYNTAX
strategy.close_all()
2 overloads
Exits the current market position, making it flat.
SYNTAX & OVERLOADS
ARGUMENTS
comment (series string) An optional parameter. Additional notes on the order.
alert_message (series string) An optional parameter which replaces the
{{strategy.order.alert_message}} placeholder when it is used in the "Create Alert"
dialog box's "Message" field.
EXAMPLE
//@version=5
strategy("closeAll Demo", overlay=false)
if open > close
strategy.entry("buy", strategy.long)
if open < close
strategy.close_all(comment = "close all entries")
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
// 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")
strategy.closedtrades.entry_bar_index()
Returns the bar_index of the closed trade's entry.
SYNTAX
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
if (longCondition)
strategy.entry("Long", strategy.long, stop = stopPrice, comment = str.tostring(stopPrice,
"#.####"))
strategy.exit("EXIT", trail_points = 1000, trail_offset = 0)
if barstate.islastconfirmedhistory or barstate.isrealtime
table.cell(testTable, 0, 0, 'Last closed trade:')
table.cell(testTable, 0, 1, "Order stop price value: " + strategy.closedtrades.entry_comm
ent(strategy.closedtrades - 1))
table.cell(testTable, 0, 2, "Actual Entry Price: " + str.tostring(strategy.closedtrades.e
ntry_price(strategy.closedtrades - 1)))
SEE ALSO
strategystrategy.entrystrategy.closedtrades
strategy.closedtrades.entry_id()
Returns the id of the closed trade's entry.
SYNTAX
strategy.closedtrades.entry_price()
Returns the price of the closed trade's entry.
SYNTAX
// 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")
strategy.closedtrades.entry_time()
Returns the UNIX time of the closed trade's entry, expressed in milliseconds..
SYNTAX
// 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")
// Display average duration converted to seconds and formatted using 2 decimal points
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(avgTradeDuration() / 1000, "#.##") + " seconds")
SEE ALSO
strategy.opentrades.entry_timestrategy.closedtrades.exit_timetime
strategy.closedtrades.exit_bar_index()
Returns the bar_index of the closed trade's exit.
SYNTAX
// Strategy calls to place a single short trade. We enter the trade at the first bar and exit
the trade at 10 bars before the last chart bar.
if bar_index == 0
strategy.entry("Short", strategy.short)
if bar_index == last_bar_index - 10
strategy.close("Short")
// 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")
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
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)
"TP" => tpCount += 1
"SL" => slCount += 1
"TRAIL" => trailCount += 1
[slCount, tpCount, trailCount]
if barstate.islastconfirmedhistory
[slCount, tpCount, trailCount] = exitStats()
table.cell(testTable, 0, 0, "Closed trades (" + str.tostring(strategy.closedtrades) +") s
tats:")
table.cell(testTable, 0, 1, "Stop Loss: " + str.tostring(slCount))
table.cell(testTable, 0, 2, "Take Profit: " + str.tostring(tpCount))
table.cell(testTable, 0, 3, "Trailing Stop: " + str.tostring(trailCount))
SEE ALSO
strategystrategy.exitstrategy.closestrategy.closedtrades
strategy.closedtrades.exit_id()
Returns the id of the closed trade's exit.
SYNTAX
// When a new open trade is detected then we create the exit strategy corresponding with the
matching entry id
// We detect the correct entry id by determining if a position is long or short based on the
position quantity
if ta.change(strategy.opentrades) != 0
posSign = strategy.opentrades.size(strategy.opentrades - 1)
strategy.exit(posSign > 0 ? "SL Long Exit" : "SL Short Exit", strategy.opentrades.entry_i
d(strategy.opentrades - 1), stop = posSign > 0 ? high - ta.tr : low + ta.tr)
// 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
msg = "Trade closed by: " + strategy.closedtrades.exit_id(strategy.closedtrades - 1)
label.new(bar_index, high + (3 * ta.tr), msg)
RETURNS
Returns the id of the closed trade's exit.
REMARKS
The function returns na if trade_num is not in the range: 0 to strategy.closedtrades-1.
SEE ALSO
strategy.closedtrades.exit_bar_indexstrategy.closedtrades.exit_pricestrategy.closedtrades.exit_ti
me
strategy.closedtrades.exit_price()
Returns the price of the closed trade's exit.
SYNTAX
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
// 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")
// Display average duration converted to seconds and formatted using 2 decimal points.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(avgTradeDuration() / 1000, "#.##") + " seconds")
EXAMPLE
// Reopens a closed trade after X seconds.
//@version=5
strategy("strategy.closedtrades.exit_time Example 2")
reopenPositionAfter(timeSec) =>
if strategy.closedtrades > 0
if time - strategy.closedtrades.exit_time(strategy.closedtrades - 1) >= timeSec * 100
0
strategy.entry("Long", strategy.long)
if ta.change(strategy.opentrades) != 0
strategy.exit("Long", stop = low * 0.9, profit = high * 2.5)
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
// 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
for tradeNo = 0 to strategy.closedtrades - 1
maxDrawdown := math.max(maxDrawdown, strategy.closedtrades.max_drawdown(tradeNo))
result = maxDrawdown
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
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
// 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
for tradeNo = 0 to strategy.closedtrades - 1
maxRunup := math.max(maxRunup, strategy.closedtrades.max_runup(tradeNo))
result = maxRunup
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
strategy.closedtrades.profit()
Returns the profit/loss of the closed trade, expressed in strategy.account_currency.
Losses are expressed as negative values.
SYNTAX
// 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 commissio
n.
avgGrossProfit() =>
sumGrossProfit = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
sumGrossProfit += strategy.closedtrades.profit(tradeNo) - strategy.closedtrades.commi
ssion(tradeNo)
result = nz(sumGrossProfit / strategy.closedtrades)
strategy.closedtrades.profit_percent()
Returns the profit/loss value of the closed trade, expressed as a percentage. Losses
are expressed as negative values.
SYNTAX
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
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
dateInput = input.time(timestamp("20 Jul 2021 00:00 +0300"), "From Date", confirm = true)
buyAndHoldReturnPct(fromDate) =>
if time >= fromDate
money = close * syminfo.pointvalue
var initialBal = strategy.convert_to_account(money)
(strategy.convert_to_account(money) - initialBal) / initialBal * 100
plot(buyAndHoldReturnPct(dateInput))
SEE ALSO
strategystrategy.convert_to_symbol
strategy.convert_to_symbol()
Converts the value from the currency used by the strategy
(strategy.account_currency) to the currency that the symbol on the chart is traded in
(syminfo.currency).
SYNTAX
// Calculate the max qty we can buy using current chart's currency.
calcContracts(accountMoney) =>
math.floor(strategy.convert_to_symbol(accountMoney) / syminfo.pointvalue / close)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars using
our custom qty.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long, qty = qt)
if bar_index % 20 == 0
strategy.close("Long")
SEE ALSO
strategystrategy.convert_to_account
strategy.default_entry_qty()
Calculates the default quantity, in units, of an entry order
from strategy.entry or strategy.order if it were to fill at the
specified fill_price value. The calculation depends on several strategy properties,
including default_qty_type, default_qty_value, currency, and other
parameters in the strategy function and their representation in the "Properties" tab of
the strategy's settings.
SYNTAX
if ta.change(direction) < 0
//@variable The stop price of the entry order.
stopPrice = close + syminfo.mintick * stopOffsetInput
//@variable The expected default fill quantity at the `stopPrice`. This value may not ref
lect actual qty of the filled order, because fill price may be different.
calculatedQty = strategy.default_entry_qty(stopPrice)
strategy.entry("My Long Entry Id", strategy.long, stop = stopPrice)
label.new(bar_index, stopPrice, str.format("Stop set at {0}\nExpected qty at {0}: {1}", m
ath.round_to_mintick(stopPrice), calculatedQty))
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.
This value represents the default calculated quantity of an order.
Order placement commands can override the default value by explicitly passing a
new qty value in the function call.
strategy.entry()
It is a command to enter market position. If an order with the same ID is already
pending, it is possible to modify the order. If there is no order with the specified ID, a
new order is placed. To deactivate an entry order, the
command strategy.cancel or strategy.cancel_all should be used. In comparison to the
function strategy.order, the function strategy.entry is affected by pyramiding and it
can reverse market position correctly. If both 'limit' and 'stop' parameters are 'NaN',
the order type is market order.
SYNTAX
strategy.exit()
It is a command to exit either a specific entry, or whole market position. If an order
with the same ID is already pending, it is possible to modify the order. If an entry
order was not filled, but an exit order is generated, the exit order will wait till entry
order is filled and then the exit order is placed. To deactivate an exit order, the
command strategy.cancel or strategy.cancel_all should be used. If the
function strategy.exit is called once, it exits a position only once. If you want to exit
multiple times, the command strategy.exit should be called multiple times. If you use
a stop loss and a trailing stop, their order type is 'stop', so only one of them is placed
(the one that is supposed to be filled first). If all the following parameters 'profit',
'limit', 'loss', 'stop', 'trail_points', 'trail_offset' are 'NaN', the command will fail. To use
market order to exit, the command strategy.close or strategy.close_all should be
used.
SYNTAX
strategy.opentrades.commission()
Returns the sum of entry and exit fees paid in the open trade, expressed
in strategy.account_currency.
SYNTAX
// 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(tradeOpenGrossPL())
SEE ALSO
strategystrategy.closedtrades.commission
strategy.opentrades.entry_bar_index()
Returns the bar_index of the open trade's entry.
SYNTAX
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
if (longCondition)
strategy.entry("Long", strategy.long, stop = stopPrice, comment = str.tostring(stopPrice,
"#.####"))
if barstate.islastconfirmedhistory or barstate.isrealtime
table.cell(testTable, 0, 0, 'Last entry stats')
table.cell(testTable, 0, 1, "Order stop price value: " + strategy.opentrades.entry_commen
t(strategy.opentrades - 1))
table.cell(testTable, 0, 2, "Actual Entry Price: " + str.tostring(strategy.opentrades.ent
ry_price(strategy.opentrades - 1)))
SEE ALSO
strategystrategy.entrystrategy.opentrades
strategy.opentrades.entry_id()
Returns the id of the open trade's entry.
SYNTAX
// We enter a long position when 14 period sma crosses over 28 period sma.
// We enter a short position when 14 period sma crosses under 28 period sma.
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
// Strategy calls to enter a long or short position when the corresponding condition is met.
if longCondition
strategy.entry("Long entry at bar #" + str.tostring(bar_index), strategy.long)
if shortCondition
strategy.entry("Short entry at bar #" + str.tostring(bar_index), strategy.short)
strategy.opentrades.entry_price()
Returns the price of the open trade's entry.
SYNTAX
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if ta.crossover(close, ta.sma(close, 14))
strategy.entry("Long", strategy.long)
// 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(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
// 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")
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
// 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")
// 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
for tradeNo = 0 to strategy.opentrades - 1
maxDrawdown := math.max(maxDrawdown, strategy.opentrades.max_drawdown(tradeNo))
result = maxDrawdown
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
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
// 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 biggest max trade runup value from all of the open trades.
maxOpenTradeRunUp() =>
maxRunup = 0.0
for tradeNo = 0 to strategy.opentrades - 1
maxRunup := math.max(maxRunup, strategy.opentrades.max_runup(tradeNo))
result = maxRunup
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
strategy.opentrades.profit()
Returns the profit/loss of the open trade, expressed in strategy.account_currency.
Losses are expressed as negative values.
SYNTAX
strategy.opentrades.profit_percent()
Returns the profit/loss of the open trade, expressed as a percentage. Losses are
expressed as negative values.
SYNTAX
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
// 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")
strategy.order()
It is a command to place order. If an order with the same ID is already pending, it is
possible to modify the order. If there is no order with the specified ID, a new order is
placed. To deactivate order, the
command strategy.cancel or strategy.cancel_all should be used. In comparison to the
function strategy.entry, the function strategy.order is not affected by pyramiding. If
both 'limit' and 'stop' parameters are 'NaN', the order type is market order.
SYNTAX
strategy.risk.allow_entry_in()
This function can be used to specify in which market direction
the strategy.entry function is allowed to open positions.
SYNTAX
strategy.risk.allow_entry_in(value) → void
ARGUMENTS
value (simple string) The allowed direction. Possible
values: strategy.direction.all, strategy.direction.long, strategy.direction.short
EXAMPLE
//@version=5
strategy("strategy.risk.allow_entry_in")
strategy.risk.allow_entry_in(strategy.direction.long)
if open > close
strategy.entry("Long", strategy.long)
// Instead of opening a short position with 10 contracts, this command will close long entrie
s.
if open < close
strategy.entry("Short", strategy.short, qty = 10)
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
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
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
strategy.risk.max_intraday_filled_orders(count, alert_message) → void
ARGUMENTS
count (simple int) A required parameter. The maximum number of filled orders per 1
day.
alert_message (simple string) An optional parameter which replaces the
{{strategy.order.alert_message}} placeholder when it is used in the "Create Alert"
dialog box's "Message" field.
EXAMPLE
//@version=5
strategy("risk.max_intraday_filled_orders Demo")
strategy.risk.max_intraday_filled_orders(10) // After 10 orders are filled, no more strategy
orders will be placed (except for a market order to exit current open market position, if the
re is any).
if open > close
strategy.entry("buy", strategy.long)
if open < close
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
// Calculate change of the current equity from the beginning of the current day.
eqChgPct = 100 * ((strategy.equity - eqFromDayStart) / strategy.equity)
// Plot it
plot(eqChgPct)
hline(-lossPct)
EXAMPLE
// Sets the maximum intraday loss using the strategy's cash value.
//@version=5
strategy("strategy.risk.max_intraday_loss Example 2", overlay = false)
// Input for maximum intraday loss in absolute cash value of the symbol.
absCashLoss = input.float(5)
// Store the open price value from the beginning of the day.
beginPrice = ta.valuewhen(ta.change(dayofweek) > 0, open, 0)
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
contracts (simple int/float) A required parameter. Maximum number of
contracts/shares/lots/units in a position.
EXAMPLE
//@version=5
strategy("risk.max_position_size Demo", default_qty_value = 100)
strategy.risk.max_position_size(10)
if open > close
strategy.entry("buy", strategy.long)
plot(strategy.position_size) // max plot value will be 10
string()
4 overloads
Casts na to string
SYNTAX & OVERLOADS
ARGUMENTS
x (const string) The value to convert to the specified type, usually na.
RETURNS
The value of the argument after casting to string.
SEE ALSO
floatintboolcolorlinelabel
syminfo.prefix()
2 overloads
Returns exchange prefix of the symbol, e.g. "NASDAQ".
SYNTAX & 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=5
indicator("syminfo.prefix fun", overlay=true)
i_sym = input.symbol("NASDAQ:AAPL")
pref = syminfo.prefix(i_sym)
tick = syminfo.ticker(i_sym)
t = ticker.new(pref, tick, session.extended)
s = request.security(t, "1D", close)
plot(s)
RETURNS
Returns exchange prefix of the symbol, e.g. "NASDAQ".
REMARKS
The result of the function is used in
the ticker.new/ticker.modify and request.security.
SEE ALSO
syminfo.tickeridsyminfo.tickersyminfo.prefixsyminfo.tickerticker.new
syminfo.ticker()
2 overloads
Returns symbol name without exchange prefix, e.g. "AAPL".
SYNTAX & 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=5
indicator("syminfo.ticker fun", overlay=true)
i_sym = input.symbol("NASDAQ:AAPL")
pref = syminfo.prefix(i_sym)
tick = syminfo.ticker(i_sym)
t = ticker.new(pref, tick, session.extended)
s = request.security(t, "1D", close)
plot(s)
RETURNS
Returns symbol name without exchange prefix, e.g. "AAPL".
REMARKS
The result of the function is used in
the ticker.new/ticker.modify and request.security.
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.
SYNTAX & OVERLOADS
ARGUMENTS
series (series int/float) Series of values to process.
length (series int) Number of bars (length).
offset (simple int/float) Controls tradeoff between smoothness (closer to 1) and
responsiveness (closer to 0).
sigma (simple int/float) Changes the smoothness of ALMA. The larger sigma the
smoother ALMA.
EXAMPLE
//@version=5
indicator("ta.alma", overlay=true)
plot(ta.alma(close, 9, 0.85, 6))
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
plot(pine_atr(14))
RETURNS
Average true range.
REMARKS
na values in the source series are ignored; the function calculates on
the length quantity of non-na values.
SEE ALSO
ta.trta.rma
ta.barssince()
Counts the number of bars since the last time the condition was true.
SYNTAX
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
plot(pineMiddle)
plot(pineUpper)
plot(pineLower)
RETURNS
Bollinger Bands.
REMARKS
na values in the source series are ignored; the function calculates on
the length quantity of non-na values.
SEE ALSO
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
plot(f_bbw(close, 5, 4))
RETURNS
Bollinger Bands Width.
REMARKS
na values in the source series are ignored; the function calculates on
the length quantity of non-na values.
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
source (series int) Source series.
EXAMPLE
//@version=5
indicator('Day and Direction Change', overlay = true)
dailyBarTime = time('1D')
isNewDay = ta.change(dailyBarTime) != 0
bgcolor(isNewDay ? color.new(color.green, 80) : na)
plot(f_cmo(close, 5))
RETURNS
Chande Momentum Oscillator.
REMARKS
na values in the source series are ignored.
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
plot(pine_cog(close, 10))
RETURNS
Center of Gravity.
REMARKS
na values in the source series are ignored.
SEE ALSO
ta.stoch
ta.correlation()
Correlation coefficient. Describes the degree to which two series tend to deviate from
their ta.sma values.
SYNTAX
ta.cross()
SYNTAX
ta.crossover()
The source1-series is defined as having crossed over source2-series if, on the
current bar, the value of source1 is greater than the value of source2, and on the
previous bar, the value of source1 was less than or equal to the value of source2.
SYNTAX
ta.dev()
Measure of difference between the series and it's ta.sma
SYNTAX
ta.dmi()
The dmi function returns the directional movement index.
SYNTAX
ta.falling()
Test if the source series is now falling for length bars long.
SYNTAX
ta.highest()
2 overloads
Highest value for a given number of bars back.
SYNTAX & OVERLOADS
ARGUMENTS
length (series int) Number of bars (length).
RETURNS
Highest value in the series.
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.
na values in the source series are ignored.
SEE ALSO
ta.lowestta.lowestbarsta.highestbarsta.valuewhenta.barssince
ta.highestbars()
2 overloads
Highest value offset for a given number of bars back.
SYNTAX & OVERLOADS
ARGUMENTS
length (series int) Number of bars (length).
RETURNS
Offset to the highest bar.
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.
na values in the source series are ignored.
SEE ALSO
ta.lowestta.highestta.lowestbarsta.barssinceta.valuewhen
ta.hma()
The hma function returns the Hull Moving Average.
SYNTAX
ta.kc()
2 overloads
Keltner Channels. Keltner channel is a technical analysis indicator showing a central
moving average line plus channel lines at a distance above and below.
SYNTAX & OVERLOADS
ta.kc(series, length, mult, useTrueRange) → [series float, series float, series float]
ARGUMENTS
series (series int/float) Series of values to process.
length (simple int) Number of bars (length).
mult (simple int/float) Standard deviation factor.
EXAMPLE
//@version=5
indicator("ta.kc")
plot(pineMiddle)
plot(pineUpper)
plot(pineLower)
RETURNS
Keltner Channels.
REMARKS
na values in the source series are ignored; the function calculates on
the length quantity of non-na values.
SEE ALSO
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.
SYNTAX & OVERLOADS
ARGUMENTS
series (series int/float) Series of values to process.
length (simple int) Number of bars (length).
mult (simple int/float) Standard deviation factor.
EXAMPLE
//@version=5
indicator("ta.kcw")
plot(ta.kcw(close, 5, 4), color=color.yellow)
plot(f_kcw(close, 5, 4, true))
RETURNS
Keltner Channels Width.
REMARKS
na values in the source series are ignored; the function calculates on
the length quantity of non-na values.
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
length (series int) Number of bars (length).
RETURNS
Lowest value in the series.
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.
na values in the source series are ignored.
SEE ALSO
ta.highestta.lowestbarsta.highestbarsta.valuewhenta.barssince
ta.lowestbars()
2 overloads
Lowest value offset for a given number of bars back.
SYNTAX & OVERLOADS
ARGUMENTS
length (series int) Number of bars back.
RETURNS
Offset to the lowest bar.
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.
na values in the source series are ignored.
SEE ALSO
ta.lowestta.highestta.highestbarsta.barssinceta.valuewhen
ta.macd()
MACD (moving average convergence/divergence). It is supposed to reveal changes in
the strength, direction, momentum, and duration of a trend in a stock's price.
SYNTAX
ta.macd(source, fastlen, slowlen, siglen) → [series float, series float, series float]
ARGUMENTS
source (series int/float) Series of values to process.
fastlen (simple int) Fast Length parameter.
slowlen (simple int) Slow Length parameter.
siglen (simple int) Signal Length parameter.
EXAMPLE
//@version=5
indicator("MACD")
[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)
plot(macdLine, color=color.blue)
plot(signalLine, color=color.orange)
plot(histLine, color=color.red, style=plot.style_histogram)
If you need only one value, use placeholders '_' like this:
EXAMPLE
//@version=5
indicator("MACD")
[_, signalLine, _] = ta.macd(close, 12, 26, 9)
plot(signalLine, color=color.orange)
RETURNS
Tuple of three MACD series: MACD line, signal line and histogram line.
REMARKS
na values in the source series are ignored; the function calculates on
the length quantity of non-na values.
SEE ALSO
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
plot(pine_mfi(hlc3, 14))
RETURNS
Money Flow Index.
REMARKS
na values in the source series are ignored; the function calculates on
the length quantity of non-na values.
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
ta.min(source) → series float
ARGUMENTS
source (series int/float) Source used for the calculation.
REMARKS
na occurrences of source are ignored.
ta.mode()
2 overloads
Returns the mode of the series. If there are several values with the same frequency,
it returns the smallest value.
SYNTAX & OVERLOADS
ARGUMENTS
source (series int) Series of values to process.
length (series int) Number of bars (length).
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
ta.percentile_linear_interpolation()
Calculates percentile using method of linear interpolation between the two nearest
ranks.
SYNTAX
ta.percentile_nearest_rank()
Calculates percentile using method of Nearest Rank.
SYNTAX
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
leftbars (series int/float) Left strength.
rightbars (series int/float) Right strength.
EXAMPLE
//@version=5
indicator("PivotHigh", overlay=true)
leftBars = input(2)
rightBars=input(2)
ph = ta.pivothigh(leftBars, rightBars)
plot(ph, style=plot.style_cross, linewidth=3, color= color.red, offset=-rightBars)
RETURNS
Price of the point or 'NaN'.
REMARKS
If parameters 'leftbars' or 'rightbars' are series you should use max_bars_back function
for the 'source' variable.
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
leftbars (series int/float) Left strength.
rightbars (series int/float) Right strength.
EXAMPLE
//@version=5
indicator("PivotLow", overlay=true)
leftBars = input(2)
rightBars=input(2)
pl = ta.pivotlow(close, leftBars, rightBars)
plot(pl, style=plot.style_cross, linewidth=3, color= color.blue, offset=-rightBars)
RETURNS
Price of the point or 'NaN'.
REMARKS
If parameters 'leftbars' or 'rightbars' are series you should use max_bars_back function
for the 'source' variable.
ta.range()
2 overloads
Returns the difference between the min and max values in a series.
SYNTAX & OVERLOADS
ARGUMENTS
source (series int) Series of values to process.
length (series int) Number of bars (length).
RETURNS
The difference between the min and max values in the series.
REMARKS
na values in the source series are ignored; the function calculates on
the length quantity of non-na values.
ta.rising()
Test if the source series is now rising for length bars long.
SYNTAX
ta.rma()
Moving average used in RSI. It is the exponentially weighted moving average with
alpha = 1 / length.
SYNTAX
ta.roc()
Calculates the percentage of change (rate of change) between the current value
of source and its value length bars ago.
It is calculated by the formula: 100 * change(src, length) / src[length].
SYNTAX
plot(pine_rsi(close, 7))
RETURNS
Relative strength index.
REMARKS
na values in the source series are ignored; the function calculates on
the length quantity of non-na values.
SEE ALSO
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
if bar_index == 1
if close > close[1]
isBelow := true
maxMin := high
result := low[1]
else
isBelow := false
maxMin := low
result := high[1]
isFirstTrendBar := true
acceleration := start
if isBelow
if result > low
isFirstTrendBar := true
isBelow := false
result := math.max(high, maxMin)
maxMin := low
acceleration := start
else
if result < high
isFirstTrendBar := true
isBelow := true
result := math.min(low, maxMin)
maxMin := high
acceleration := start
if not isFirstTrendBar
if isBelow
if high > maxMin
maxMin := high
acceleration := math.min(acceleration + inc, max)
else
if low < maxMin
maxMin := low
acceleration := math.min(acceleration + inc, max)
if isBelow
result := math.min(result, low[1])
if bar_index > 1
result := math.min(result, low[2])
else
result := math.max(result, high[1])
if bar_index > 1
result := math.max(result, high[2])
result
ta.supertrend()
The Supertrend Indicator. The Supertrend is a trend following indicator.
SYNTAX
ta.swma()
Symmetrically weighted moving average with fixed length: 4. Weights: [1/6, 2/6, 2/6,
1/6].
SYNTAX
ta.tr()
SYNTAX
ta.tsi()
True strength index. It uses moving averages of the underlying momentum of a
financial instrument.
SYNTAX
ARGUMENTS
condition (series bool) The condition to search for.
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=5
indicator("ta.valuewhen")
slow = ta.sma(close, 7)
fast = ta.sma(close, 14)
// Get value of `close` on second most recent cross
plot(ta.valuewhen(ta.cross(slow, fast), close, 1))
REMARKS
This function requires execution on every bar. It is not recommended to use it inside
a for or while loop structure, where its behavior can be unexpected. Please note that
using this function can cause indicator repainting.
SEE ALSO
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
ta.vwap()
3 overloads
Volume weighted average price.
SYNTAX & OVERLOADS
ARGUMENTS
source (series int/float) Source used for the VWAP calculation.
EXAMPLE
//@version=5
indicator("Simple VWAP")
vwap = ta.vwap(open)
plot(vwap)
EXAMPLE
//@version=5
indicator("Advanced VWAP")
vwapAnchorInput = input.string("Daily", "Anchor", options = ["Daily", "Weekly", "Monthly"])
stdevMultiplierInput = input.float(1.0, "Standard Deviation Multiplier")
anchorTimeframe = switch vwapAnchorInput
"Daily" => "1D"
"Weekly" => "1W"
"Monthly" => "1M"
anchor = timeframe.change(anchorTimeframe)
[vwap, upper, lower] = ta.vwap(open, anchor, stdevMultiplierInput)
plot(vwap)
plot(upper, color = color.green)
plot(lower, color = color.green)
RETURNS
A VWAP series, or a tuple [vwap, upper_band, lower_band] if stdev_mult is
specified.
REMARKS
Calculations only begin the first time the anchor condition becomes true. Until then,
the function returns na.
SEE ALSO
ta.vwap
ta.vwma()
The vwma function returns volume-weighted moving average
of source for length bars back. It is the same as: sma(source * volume, length) /
sma(volume, length).
SYNTAX
ta.wma()
The wma function returns weighted moving average of source for length bars back.
In wma weighting factors decrease in arithmetical progression.
SYNTAX
ta.wpr()
Williams %R. The oscillator shows the current closing price in relation to the high and
low of the past 'length' bars.
SYNTAX
table()
Casts na to table
SYNTAX
table.cell()
The function defines a cell in the table and sets its attributes.
SYNTAX
table.cell_set_bgcolor()
The function sets the background color of the cell.
SYNTAX
table.cell_set_height()
The function sets the height of cell.
SYNTAX
table.cell_set_text()
The function sets the text in the specified cell.
SYNTAX
table.cell_set_text_color()
The function sets the color of the text inside the cell.
SYNTAX
table.cell_set_text_font_family()
The function sets the font family of the text inside the cell.
SYNTAX
table.cell_set_text_halign()
The function sets the horizontal alignment of the cell's text.
SYNTAX
table.cell_set_text_size()
The function sets the size of the cell's text.
SYNTAX
table.cell_set_text_valign()
The function sets the vertical alignment of a cell's text.
SYNTAX
table.cell_set_text_valign(table_id, column, row, text_valign) → void
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_text_haligntable.cell_set_text_sizetable.cell_set_widthtable.cell_set_tooltip
table.cell_set_tooltip()
The function sets the tooltip in the specified cell.
SYNTAX
table.cell_set_width()
The function sets the width of the cell.
SYNTAX
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
table.delete()
The function deletes a table.
SYNTAX
table.delete(table_id) → void
ARGUMENTS
table_id (series table) A table object.
EXAMPLE
//@version=5
indicator("table.delete example")
var testTable = table.new(position = position.top_right, columns = 2, rows = 1, bgcolor = col
or.yellow, border_width = 1)
if barstate.islast
table.cell(table_id = testTable, column = 0, row = 0, text = "Open is " + str.tostring(op
en))
table.cell(table_id = testTable, column = 1, row = 0, text = "Close is " + str.tostring(c
lose), bgcolor=color.teal)
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
table.new()
The function creates a new table.
SYNTAX
table.set_bgcolor()
The function sets the background color of a table.
SYNTAX
table.set_border_color()
The function sets the color of the borders (excluding the outer frame) of the table's
cells.
SYNTAX
table.set_border_color(table_id, border_color) → void
ARGUMENTS
table_id (series table) A table object.
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_bgcolorta
ble.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
table.set_frame_color()
The function sets the color of the outer frame of a table.
SYNTAX
table.set_frame_width()
The function set the width of the outer frame of a table.
SYNTAX
table.set_position()
The function sets the position of a table.
SYNTAX
ticker.heikinashi()
Creates a ticker identifier for requesting Heikin Ashi bar values.
SYNTAX
ticker.inherit()
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
//@variable The `close` price requested using "NASDAQ:MSFT" with inherited modifiers.
secData = request.security(testSymbolHAtickerExtHours, "60", close, ignore_invalid_symbol = t
rue)
//@variable The `close` price requested using "NASDAQ:MSFT" without modifiers.
compareData = request.security(testSymbol, "60", close, ignore_invalid_symbol = true)
ticker.linebreak()
Creates a ticker identifier for requesting Line Break values.
SYNTAX
ticker.modify()
Creates a ticker identifier for requesting additional data for the script.
SYNTAX
ticker.new()
Creates a ticker identifier for requesting additional data for the script.
SYNTAX
ticker.renko()
Creates a ticker identifier for requesting Renko values.
SYNTAX
ticker.standard()
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.
SYNTAX
// Requests data from the chart type the script is running on.
chartTypeValue = request.security(syminfo.tickerid, "1D", close)
// Request data from the standard chart type, regardless of the chart type the script is runn
ing on.
standardChartValue = request.security(ticker.standard(syminfo.tickerid), "1D", close)
// This will not use a standard ticker ID because the `symbol` argument contains only the tic
ker — not the prefix (exchange).
standardChartValue2 = request.security(ticker.standard(syminfo.ticker), "1D", close)
plot(chartTypeValue)
plot(standardChartValue, color = color.green)
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.
SYNTAX & OVERLOADS
ARGUMENTS
timeframe (series string) Timeframe. An empty string is interpreted as the current
timeframe of the chart.
bars_back (series int) If specified, the function will return the calculated timestamp
from the bar N bars back relative to the current timeframe bar. Passing a negative
number from -1 to -500 allows the function to request the expected time of a future
bar. Optional. The default is 0.
EXAMPLE
//@version=5
indicator("Time", overlay=true)
// Try this on chart AAPL,1
timeinrange(res, sess) => not na(time(res, sess, "America/New_York")) ? 1 : 0
plot(timeinrange("1", "1300-1400"), color=color.red)
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.
SYNTAX & OVERLOADS
timeframe.change()
Detects changes in the specified timeframe.
SYNTAX
ARGUMENTS
seconds (simple int) The number of seconds in the timeframe.
EXAMPLE
//@version=5
indicator("HTF Close", "", true)
int chartTf = timeframe.in_seconds()
string tfTimes5 = timeframe.from_seconds(chartTf * 5)
float htfClose = request.security(syminfo.tickerid, tfTimes5, close)
plot(htfClose)
RETURNS
A timeframe string compliant with timeframe string specifications.
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".
All values above 31,622,400 (366 days) return "12M".
SEE ALSO
timeframe.in_secondsrequest.securityrequest.security_lower_tf
timeframe.in_seconds()
2 overloads
Converts a timeframe string into seconds.
SYNTAX & OVERLOADS
ARGUMENTS
timeframe (simple string) Timeframe string in timeframe string
specifications format. Optional. The default is timeframe.period.
EXAMPLE
//@version=5
indicator("`timeframe_in_seconds()`")
plot(secondsInTf)
RETURNS
The "int" representation of the number of seconds in the timeframe string.
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
Function timestamp returns UNIX time of specified date and time.
SYNTAX & OVERLOADS
ARGUMENTS
dateString (const string) A string containing the date and, optionally, the time and
time zone. Its format must comply with either the IETF RFC 2822 or ISO
8601 standards ("DD MMM YYYY hh:mm:ss ±hhmm" or "YYYY-MM-
DDThh:mm:ss±hh:mm", so "20 Feb 2020" or "2020-02-20"). If no time is supplied,
"00:00" is used. If no time zone is supplied, GMT+0 will be used. Note that this
diverges from the usual behavior of the function where it returns time in the
exchange's timezone.
EXAMPLE
//@version=5
indicator("timestamp")
plot(timestamp(2016, 01, 19, 09, 30), linewidth=3, color=color.green)
plot(timestamp(syminfo.timezone, 2016, 01, 19, 09, 30), color=color.blue)
plot(timestamp(2016, 01, 19, 09, 30), color=color.yellow)
plot(timestamp("GMT+6", 2016, 01, 19, 09, 30))
plot(timestamp(2019, 06, 19, 09, 30, 15), color=color.lime)
plot(timestamp("GMT+3", 2019, 06, 19, 09, 30, 15), color=color.fuchsia)
plot(timestamp("Feb 01 2020 22:10:05"))
plot(timestamp("2011-10-10T14:48:00"))
plot(timestamp("04 Dec 1995 00:12:00 GMT+5"))
RETURNS
UNIX time.
REMARKS
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1
January 1970.
SEE ALSO
time
weekofyear()
2 overloads
SYNTAX & OVERLOADS
ARGUMENTS
time (series int) UNIX time in milliseconds.
RETURNS
Week of year (in exchange timezone) for provided UNIX time.
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
SYNTAX & OVERLOADS
ARGUMENTS
time (series int) UNIX time in milliseconds.
RETURNS
Year (in exchange timezone) for provided UNIX time.
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
<field_1> [= <title_1>]
<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=5
indicator("Session highlight", overlay = true)
//@variable A map that accepts fields from the `symbols` enum as keys and "float" values.
map<symbols, float> data = map.new<symbols, float>()
// Put key-value pairs into the `data` map.
data.put(symbols.aapl, request.security(str.tostring(symbols.aapl), timeframe.period, close))
data.put(symbols.tsla, request.security(str.tostring(symbols.tsla), timeframe.period, close))
data.put(symbols.amzn, request.security(str.tostring(symbols.amzn), timeframe.period, close))
// Plot the value from the `data` map accessed by the `symbols.aapl` key.
plot(data.get(symbols.aapl))
export
Used in libraries to prefix the declaration of functions or user-defined type definitions
that will be available from other scripts importing the library.
EXAMPLE
//@version=5
//@description Library of debugging functions.
library("Debugging_library", overlay = true)
//@function Displays a string as a table cell for debugging purposes.
//@param txt String to display.
//@returns Void.
export print(string txt) =>
var table t = table.new(position.middle_right, 1, 1)
table.cell(t, 0, 0, txt, bgcolor = color.yellow)
// Using the function from inside the library to show an example on the published chart.
// This has no impact on scripts using the library.
print("Library Test")
REMARKS
Each library must have at least one exported function or user-defined type (UDT).
Exported functions cannot use variables from the global scope if they are arrays,
mutable variables (reassigned with :=), or variables of 'input' form.
Exported functions cannot use request.*() functions.
Exported functions must explicitly declare each parameter's type and all parameters
must be used in the function's body. By default, all arguments passed to exported
functions are of the series form, unless they are explicitly specified as simple in the
function's signature.
The @description, @function, @param, @type, @field, and @returns compiler
annotations are used to automatically generate the library's description and release
notes, and in the Pine Script® Editor's tooltips.
SEE ALSO
libraryimportsimpleseriestype
for
The 'for' structure allows the repeated execution of a number of statements:
SYNTAX
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)
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
var_declaration - An optional variable declaration that will be assigned the value of
the loop's 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.
array_element - A variable containing each successive array element to be processed
in the loop. The variable is immutable in the loop's body.
array_id - The ID of the array over which the loop is iterated.
statements | continue | break - Any number of statements, or the 'continue' or
'break' keywords, indented by 4 spaces or a tab.
return_expression - The loop's return value assigned to the variable
in var_declaration, if one is present. If the loop exits because of a 'continue' or
'break' keyword, the loop's return value is that of the last variable assigned a value
before the loop's exit.
continue - A keyword that can only be used in loops. It causes the next iteration of
the loop to be executed.
break - A keyword that exits the loop.
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=5
indicator("for...in")
// Here we determine on each bar how many of the bar's OHLC values are greater than the SMA o
f 'close' values
float[] ohlcValues = array.from(open, high, low, close)
qtyGreaterThan(value, array) =>
int result = 0
for currentElement in array
if currentElement > value
result += 1
result
plot(qtyGreaterThan(ta.sma(close, 20), ohlcValues))
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=5
indicator("for...in")
var valuesArray = array.from(4, -8, 11, 78, -16, 34, 7, 99, 0, 55)
var isPos = array.new_bool(10, false)
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(isPos))
Iterate through matrix rows as arrays.
EXAMPLE
//@version=5
indicator("`for ... in` matrix Example")
sum = 0.0
// Loop through every row of the matrix.
for rowArray in matrix1
// Sum values of the every row
sum += array.sum(rowArray)
plot(sum)
SEE ALSO
forwhilearray.sumarray.minarray.max
if
If statement defines what block of statements must be executed when conditions of
the expression are satisfied.
To have access to and use the if statement, one should specify the version >= 2 of
Pine Script® language in the very first line of code, for example: //@version=5
The 4th version of Pine Script® Language allows you to use “else if” syntax.
General code form:
SYNTAX
var_declarationX = if condition
var_decl_then0
var_decl_then1
var_decl_thenN
var_decl_else0
var_decl_else1
var_decl_elseN
else
var_decl_else0
var_decl_else1
var_decl_elseN
return_expression_else
where
var_declarationX — this variable gets the value of the if statement
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.
return_expression_then, return_expression_else — the last expression from the
block then or from the block else will return the final value of the statement. If
declaration of the variable is in the end, its value will be the result.
The type of returning value of the if statement depends on return_expression_then
and return_expression_else type (their types must match: it is not possible to return
an integer value from then, while you have a string value in else block).
EXAMPLE
//@version=5
indicator("if")
// This code compiles
x = if close > open
close
else
open
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
method
This keyword is used to prefix a function declaration, indicating it can then be
invoked using dot notation by appending its name to a variable of the type of its first
parameter and omitting that first parameter. Alternatively, functions declared as
methods can also be invoked like normal user-defined functions. In that case, an
argument must be supplied for its first parameter.
The first parameter of a method declaration must be explicitly typified.
SYNTAX
<functionBlock>
EXAMPLE
//@version=5
indicator("")
prices.maintainArray(50, close)
// The method can also be called like a function, without using dot notation.
// In this case an argument must be supplied for its first parameter.
// maintainArray(prices, 50, close)
// This calls the `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 t
ype.
// Those namespaces are: `array`, `matrix`, `line`, `linefill`, `label`, `box`, and `table`.
plot(prices.avg())
not
Logical negation (NOT). Applicable to boolean expressions.
SYNTAX
not expr1
RETURNS
Boolean value, or series of boolean values.
or
Logical OR. Applicable to boolean expressions.
SYNTAX
expr1 or expr2
RETURNS
Boolean value, or series of boolean values.
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
Switch with an expression:
EXAMPLE
//@version=5
indicator("Switch using an expression")
string i_maType = input.string("EMA", "MA type", options = ["EMA", "SMA", "RMA", "WMA"])
plot(ma)
Switch without an expression:
EXAMPLE
//@version=5
strategy("Switch without an expression", overlay = true)
switch
longCondition => strategy.entry("Long ID", strategy.long)
shortCondition => strategy.entry("Short ID", strategy.short)
RETURNS
The value of the last expression in the local block of statements that is executed.
REMARKS
Only one of the local_block instances or the default_local_block can be
executed. The default_local_block is introduced with the => token alone and is
only executed when none of the preceding blocks are executed. If the result of
the switch statement is assigned to a variable and a default_local_block is not
specified, the statement returns na if no local_block is executed. When assigning
the result of the switch statement to a variable, all local_block instances must
return the same type of value.
SEE ALSO
if?:
type
This keyword allows the declaration of user-defined types (UDT) from which scripts
can instantiate objects. UDTs are composite types that contain an arbitrary number of
fields of any built-in or user-defined type, including the defined UDT itself. The
syntax to define a UDT is:
SYNTAX
…
Once a UDT is defined, scripts can instantiate objects from it with
the UDT_identifier.new() construct. When creating a new type instance, the
fields of the resulting object will initialize with the default values from the UDT's
definition. Any type fields without specified defaults will initialize as na.
Alternatively, users can pass initial values as arguments in the *.new() method to
override the type's defaults. For example, newFooObject = foo.new(x =
true) assigns a new foo object to the newFooObject variable with its x field
initialized using a value of true.
Field declarations can include the varip keyword, in which case the field values
persist between successive script iterations on the same bar.
For more information see the User Manual's sections on defining UDTs and using
objects.
Libraries can export UDTs. See theLibraries page of our User Manual to learn more.
EXAMPLE
//@version=5
indicator("Multi Time Period Chart", overlay = true)
timeframeInput = input.timeframe("1D")
type bar
float o = open
float h = high
float l = low
float c = close
int t = time
if not na(secBar)
// To avoid a runtime error, only process data when an object exists.
if not 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
var box lastBox = na
if na(lastBox) or timeframe.change(timeframeInput)
// On the last bar, only draw a new current box the first time we get there or wh
en HTF changes.
lastBox := drawBox(secBar, time)
else
// On other chart updates, use setters to modify the current box.
updateBox(lastBox, secBar)
var
var is the keyword used for assigning and one-time initializing of the variable.
Normally, a syntax of assignment of variables, which doesn’t include the keyword var,
results in the value of the variable being overwritten with every update of the data.
Contrary to that, when assigning variables with the keyword var, they can “keep the
state” despite the data updating, only changing it when conditions within if-
expressions are met.
SYNTAX
continue
break
return_expression
where:
variable_declaration - An optional variable declaration. The return
expression can provide the initialization value for this variable.
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.
return_expression - An optional line providing the while statement's returning
value.
EXAMPLE
//@version=5
indicator("while")
// This is a simple example of calculating a factorial using a while loop.
int i_n = input.int(10, "Factorial Size", minval=0)
int counter = i_n
int factorial = 1
while counter > 0
factorial := factorial * counter
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=5
indicator("array", overlay=true)
array<float> a = na
a := array.new<float>(1, close)
plot(array.get(a, 0))
REMARKS
Array objects are always of "series" form.
SEE ALSO
varlinelabeltableboxarray.new<type>array.from
bool
Keyword used to explicitly declare the "bool" (boolean) type of a variable or a
parameter. "Bool" variables can have values true, false or na.
EXAMPLE
//@version=5
indicator("bool")
bool b = true // Same as `b = true`
b := na
plot(b ? open : close)
REMARKS
Explicitly mentioning the type in a variable declaration is optional, except when it is
initialized with na. Learn more about Pine Script® types in the User Manual page on
the Type System.
SEE ALSO
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=5
indicator("box")
// Empty `box1` box ID.
var box box1 = na
// `box` type is unnecessary because `box.new()` returns a "box" type.
var box2 = box.new(na, na, na, na)
box3 = box.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time)
REMARKS
Box objects are always of "series" form.
SEE ALSO
varlinelabeltablebox.new
chart.point
Keyword to explicitly declare the type of a variable or parameter as chart.point.
Scripts can produce chart.point instances using
the chart.point.from_time, chart.point.from_index, chart.point.now,
and chart.point.new functions.
FIELDS
index (series int) The x-coordinate of the point, expressed as a bar index value.
time (series float) The x-coordinate of the point, expressed as a UNIX time value, in
milliseconds.
price (series float) The y-coordinate of the point.
SEE ALSO
polyline
color
Keyword used to explicitly declare the "color" type of a variable or a parameter.
EXAMPLE
//@version=5
indicator("color", overlay = true)
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
plot(close, myTitle)
EXAMPLE
//@version=5
indicator("can't assign input to const")
//@variable A variable declared as "const float" that attempts to assign the result of `input
.float()` as its value.
// This declaration causes an error. The "input float" qualified type is stronger th
an "const float".
const float myVar = input.float(2.0)
plot(myVar)
REMARKS
To learn more, see our User Manual's section on type qualifiers.
SEE ALSO
simpleseries
float
Keyword used to explicitly declare the "float" (floating point) type of a variable or a
parameter.
EXAMPLE
//@version=5
indicator("float")
float f = 3.14 // Same as `f = 3.14`
f := na
plot(f)
REMARKS
Explicitly mentioning the type in a variable declaration is optional, except when it is
initialized with na. Learn more about Pine Script® types in the User Manual page on
the Type System.
SEE ALSO
varvaripintboolcolorstring
int
Keyword used to explicitly declare the "int" (integer) type of a variable or a
parameter.
EXAMPLE
//@version=5
indicator("int")
int i = 14 // Same as `i = 14`
i := na
plot(i)
REMARKS
Explicitly mentioning the type in a variable declaration is optional, except when it is
initialized with na. Learn more about Pine Script® types in the User Manual page on
the Type System.
SEE ALSO
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=5
indicator("label")
// Empty `label1` label ID.
var label label1 = na
// `label` type is unnecessary because `label.new()` returns "label" type.
var label2 = label.new(na, na, na)
if barstate.islastconfirmedhistory
label3 = label.new(bar_index, high, text = "label3 text")
REMARKS
Label objects are always of "series" form.
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=5
indicator("line")
// Empty `line1` line ID.
var line line1 = na
// `line` type is unnecessary because `line.new()` returns "line" type.
var line2 = line.new(na, na, na, na)
line3 = line.new(bar_index - 1, high, bar_index, high, extend = extend.right)
REMARKS
Line objects are always of "series" form.
SEE ALSO
varlabelboxline.new
linefill
Keyword used to explicitly declare the "linefill" type of a variable or a parameter.
Linefill objects (or IDs) can be created with the linefill.new function.
EXAMPLE
//@version=5
indicator("linefill", overlay=true)
// Empty `linefill1` line ID.
var linefill linefill1 = na
// `linefill` type is unnecessary because `linefill.new()` returns "linefill" type.
var linefill2 = linefill.new(na, na, na)
if barstate.islastconfirmedhistory
line1 = line.new(bar_index - 10, high+1, bar_index, high+1, extend = extend.right)
line2 = line.new(bar_index - 10, low+1, bar_index, low+1, extend = extend.right)
linefill3 = linefill.new(line1, line2, color = color.new(color.green, 80))
REMARKS
Linefill objects are always of "series" form.
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=5
indicator("map", overlay=true)
map<int, float> a = na
a := map.new<int, float>()
a.put(bar_index, close)
label.new(bar_index, a.get(bar_index), "Current close")
REMARKS
Map objects are always of series form.
SEE ALSO
map.new<type,type>
matrix
Keyword used to explicitly declare the "matrix" type of a variable or a parameter.
Matrix objects (or IDs) can be created with the matrix.new<type> function.
EXAMPLE
//@version=5
indicator("matrix example")
polyline
Keyword to explicitly declare the type of a variable or parameter as polyline.
Scripts can produce polyline instances using the polyline.new function.
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
//@function Finds the highest `source` value over `length` bars, filtered by the `cond` condi
tion.
export conditionalHighest(series float source, series bool cond, series int length) =>
//@variable The highest `source` value from when the `cond` was `true` over `length` bars
.
series float result = na
// Loop to find the highest value.
for i = 0 to length - 1
if cond[i]
value = source[i]
result := math.max(nz(result, value), value)
// Return the `result`.
result
//@variable The highest `close` value from every fifth bar over the last 100 bars.
series float hiValue = conditionalHighest(close, condition, 100)
plot(hiValue)
bgcolor(condition ? color.new(color.teal, 80) : na)
EXAMPLE
//@version=5
indicator("series variable not allowed")
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
//@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 "seri
es int" in `ta.ema()`.
//@returns A tuple of length values.
export ribbonLengths(simple int baseLength) =>
simple int length1 = baseLength
simple int length2 = baseLength * 2
simple int length3 = baseLength * 3
simple int length4 = baseLength * 4
[length1, length2, length3, length4]
plot(myVar)
REMARKS
To learn more, see our User Manual's section on type qualifiers.
SEE ALSO
seriesconst
string
Keyword used to explicitly declare the "string" type of a variable or a parameter.
EXAMPLE
//@version=5
indicator("string")
string s = "Hello World!" // Same as `s = "Hello world!"`
// string s = na // same as ""
plot(na, title=s)
REMARKS
Explicitly mentioning the type in a variable declaration is optional, except when it is
initialized with na. Learn more about Pine Script® types in the User Manual page on
the Type System.
SEE ALSO
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=5
indicator("table")
// Empty `table1` table ID.
var table table1 = na
// `table` type is unnecessary because `table.new()` returns "table" type.
var table2 = table.new(position.top_left, na, na)
if barstate.islastconfirmedhistory
var table3 = table.new(position = position.top_right, columns = 1, rows = 1, bgcolor = co
lor.yellow, border_width = 1)
table.cell(table_id = table3, column = 0, row = 0, text = "table3 text")
REMARKS
Table objects are always of "series" form.
SEE ALSO
varlinelabelboxtable.new
Operators
-
Subtraction or unary minus. Applicable to numerical expressions.
SYNTAX
expr1 - expr2
RETURNS
Returns integer or float value, or series of values:
Binary - returns expr1 minus expr2.
Unary - returns the negation of expr.
REMARKS
You may use arithmetic operators with numbers as well as with series variables. In
case of usage with series the operators are applied elementwise.
-=
Subtraction assignment. Applicable to numerical expressions.
SYNTAX
expr1 -= expr2
EXAMPLE
//@version=5
indicator("-=")
// Equals to expr1 = expr1 - expr2.
a = 2
b = 3
a -= b
// Result: a = -1.
plot(a)
RETURNS
Integer or float value, or series of values.
:=
Reassignment operator. It is used to assign a new value to a previously declared
variable.
SYNTAX
<var_name> := <new_value>
EXAMPLE
//@version=5
indicator("My script")
myVar = 10
plot(myVar)
!=
Not equal to. Applicable to expressions of any type.
SYNTAX
expr1 != expr2
RETURNS
Boolean value, or series of boolean values.
?:
Ternary conditional operator.
SYNTAX
[]
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=5
indicator("[]")
// [] can be used to "save" variable value between bars
a = 0.0 // declare `a`
a := a[1] // immediately set current value to the same as previous. `na` in the beginning of
history
if high == low // if some condition - change `a` value to another
a := low
plot(a)
RETURNS
A series of values.
SEE ALSO
math.floor
*
Multiplication. Applicable to numerical expressions.
SYNTAX
expr1 * expr2
RETURNS
Integer or float value, or series of values.
*=
Multiplication assignment. Applicable to numerical expressions.
SYNTAX
expr1 *= expr2
EXAMPLE
//@version=5
indicator("*=")
// Equals to expr1 = expr1 * expr2.
a = 2
b = 3
a *= b
// Result: a = 6.
plot(a)
RETURNS
Integer or float value, or series of values.
/
Division. Applicable to numerical expressions.
SYNTAX
expr1 / expr2
RETURNS
Integer or float value, or series of values.
/=
Division assignment. Applicable to numerical expressions.
SYNTAX
expr1 /= expr2
EXAMPLE
//@version=5
indicator("/=")
// Equals to expr1 = expr1 / expr2.
a = 3
b = 3
a /= b
// Result: a = 1.
plot(a)
RETURNS
Integer or float value, or series of values.
%
Modulo (integer remainder). Applicable to numerical expressions.
SYNTAX
expr1 % expr2
RETURNS
Integer or float value, or series of values.
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.
Example: -1 % 9 = -1 - 9 * int(-1/9) = -1 - 9 * int(-0.111) = -1 -
9 * 0 = -1.
%=
Modulo assignment. Applicable to numerical expressions.
SYNTAX
expr1 %= expr2
EXAMPLE
//@version=5
indicator("%=")
// Equals to expr1 = expr1 % expr2.
a = 3
b = 3
a %= b
// Result: a = 0.
plot(a)
RETURNS
Integer or float value, or series of values.
+
Addition or unary plus. Applicable to numerical expressions or strings.
SYNTAX
expr1 + expr2
RETURNS
Binary + for strings returns concatenation of expr1 and expr2
For numbers returns integer or float value, or series of values:
Binary + returns expr1 plus expr2.
Unary + returns expr (does nothing added just for the symmetry with the unary -
operator).
REMARKS
You may use arithmetic operators with numbers as well as with series variables. In
case of usage with series the operators are applied elementwise.
+=
Addition assignment. Applicable to numerical expressions or strings.
SYNTAX
expr1 += expr2
EXAMPLE
//@version=5
indicator("+=")
// Equals to expr1 = expr1 + expr2.
a = 2
b = 3
a += b
// Result: a = 5.
plot(a)
RETURNS
For strings returns concatenation of expr1 and expr2. For numbers returns integer or
float value, or series of values.
REMARKS
You may use arithmetic operators with numbers as well as with series variables. In
case of usage with series the operators are applied elementwise.
<
Less than. Applicable to numerical expressions.
SYNTAX
expr1 == expr2
RETURNS
Boolean value, or series of boolean values.
=>
The '=>' operator is used in user-defined function declarations and
in switch statements.
The function declaration syntax is:
SYNTAX
<local_block>
<function_result>
A <local_block> is zero or more Pine Script® statements.
The <function_result> is a variable, an expression, or a tuple.
EXAMPLE
//@version=5
indicator("=>")
// single-line function
f1(x, y) => x + y
// multi-line function
f2(x, y) =>
sum = x + y
sumChange = ta.change(sum, 10)
// Function automatically returns the last expression used in it
plot(f1(30, 8) + f2(1, 3))
REMARKS
You can learn more about user-defined functions in the User Manual's pages
on Declaring functions and Libraries.
>
Greater than. Applicable to numerical expressions.
SYNTAX
@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=5
indicator("Session highlight", overlay = true)
@field
If placed above a type or enum declaration, it adds a custom description for a field of
the type/enum. After the annotation, users should specify the field name, followed
by its description.
The Pine Editor's autosuggest uses this description and displays it when a user hovers
over the type/enum or field name. When used in library scripts, the descriptions of all
types/enums using the export keyword will pre-fill the "Description" field in the
publication dialogue.
EXAMPLE
//@version=5
indicator("New high over the last 20 bars", overlay = true)
//@variable If the current `high` is the highest over the last 20 bars, returns a new `Point`
instance, `na` otherwise.
Point highest = na
if ta.highestbars(high, 20) == 0
highest := Point.new(bar_index, high)
label.new(highest.index, highest.price, str.tostring(highest.price))
@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=5
// @description Provides a tool to quickly output a label on the chart.
library("MyLibrary")
@param
If placed above a function declaration, it adds a custom description for a function
parameter. After the annotation, users should specify the parameter name, then its
description.
The Pine Editor's autosuggest uses this description and displays it when a user hovers
over the function name. When used in library scripts, the descriptions of all functions
using the export keyword will pre-fill the "Description" field in the publication
dialogue.
EXAMPLE
//@version=5
// @description Provides a tool to quickly output a label on the chart.
library("MyLibrary")
@returns
If placed above a function declaration, it adds a custom description for what that
function returns.
The Pine Editor's autosuggest uses this description and displays it when a user hovers
over the function name. When used in library scripts, the descriptions of all functions
using the export keyword will pre-fill the "Description" field in the publication
dialogue.
EXAMPLE
//@version=5
// @description Provides a tool to quickly output a label on the chart.
library("MyLibrary")
@strategy_alert_message
If used within a strategy script, it provides a default message to pre-fill the "Message"
field in the alert creation dialogue.
EXAMPLE
//@version=5
strategy("My strategy", overlay=true, margin_long=100, margin_short=100)
//@strategy_alert_message Strategy alert on symbol {{ticker}}
@type
If placed above a type declaration, it adds a custom description for the type.
The Pine Editor's autosuggest uses this description and displays it when a user hovers
over the type name. When used in library scripts, the descriptions of all types using
the export keyword will pre-fill the "Description" field in the publication dialogue.
EXAMPLE
//@version=5
indicator("New high over the last 20 bars", overlay = true)
//@type A point on a chart.
//@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` otherwise.
Point highest = na
if ta.highestbars(high, 20) == 0
highest := Point.new(bar_index, high)
label.new(highest.index, highest.price, str.tostring(highest.price))
@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=5
indicator("New high over the last 20 bars", overlay = true)
//@variable If the current `high` is the highest over the last 20 bars, returns a new `Point`
instance, `na` otherwise.
Point highest = na
if ta.highestbars(high, 20) == 0
highest := Point.new(bar_index, high)
label.new(highest.index, highest.price, str.tostring(highest.price))
@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=5
indicator("Pine v5 Indicator")
plot(close)
EXAMPLE
//This indicator has no version annotation, so it will try to use v1.
//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.