You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This document provides a concise reference for Pine Script, a programming language specifically designed for trading strategies and indicators within TradingView.
Operators
Arithmetic Operators
Operator
Description
+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulus (Remainder of integer division)
Comparison Operators
Operator
Description
==
Equal to
!=
Not equal to
>
Greater than
<
Less than
>=
Greater than or equal to
<=
Less than or equal to
Logical Operators
Operator
Description
and
Logical AND
or
Logical OR
not
Logical NOT
?:
Ternary operator (conditional expression)
Assignment Operators
Operator
Description
=
Assignment
:=
Re-assignment
+=
Addition assignment
-=
Subtraction assignment
*=
Multiplication assignment
/=
Division assignment
%=
Modulus assignment
Keywords
These keywords are reserved in Pine Script and cannot be used as variable names.
Keyword
Description
import
Imports a function from another script.
export
Exports a function for use in other scripts.
method
Defines a method within a user-defined type.
type
Creates a user-defined type (similar to a class).
matrix
Namespace for matrix-related functions.
var
Declares a variable.
varip
Declares a variable with intrabar persistence (value retained across bars).
Reserved Keywords:Catch, Class, Do, Ellipse, In, Is, Polygon, Range, Return, Struct, Text, Throw, Try
Storage Methods
These methods define the structure in which data is stored. string is used as an example type here.
Storage Method
Description
matrix<string>
Two-dimensional structure (rows and columns).
array<string>
One-dimensional structure (ordered list).
string[]
Shorthand notation for an array (legacy).
string
Single data point.
Built-in Types
Pine Script offers these fundamental data types.
Type
Description
string
Textual data.
int
Integer (whole number).
float
Floating-point number (decimal).
bool
Boolean (true/false).
color
Represents a color using different formats.
line
Line object.
linefill
Line fill object.
box
Box object.
label
Label object.
table
Table object.
User-Defined Types
These types, created with the type keyword, extend the language's capabilities by defining custom data structures. Methods can be defined externally.
Type
Description
type <name>
Creates a user-defined type with a given name.
<name>.new()
Creates a new instance (object) of the user-defined type.
<name>.<field>
Accesses a field (property) of the user-defined type.
type ExampleType
float fieldname1 = 0.0 // allowed default
string fieldname2 // allowed default but unused
array<int> fieldname3 // NOT allowed default
matrix<bool> fieldname4 // NOT allowed default
ExampleType field_udt // NOT allowed default
Variables and Constants
Pine Script is loosely typed; you don't have to explicitly declare the type of a variable. The type is inferred during assignment. You cannot change the type of a variable after it has been assigned.
a = 1 // a is an integer
b = 1.2 // b is a float
c = "1.2" // c is a string
d = true // d is a boolean
e = color.new(color.red, 50) // e is a color
Built-in Functions
Technical Analysis Functions
The ta namespace provides a wide array of indicators. Here's a selection:
Function/Var
Description
ta.accdist
Accumulation/Distribution line.
ta.alma()
Arnaud Legoux Moving Average.
ta.atr()
Average True Range.
ta.bb()
Bollinger Bands.
ta.bbw()
Bollinger Width.
ta.cci()
Commodity Channel Index.
ta.cmo()
Chande Momentum Oscillator.
ta.cog()
Center of Gravity.
ta.dmi()
Directional Movement Index.
ta.ema()
Exponential Moving Average.
ta.hma()
Hull Moving Average.
ta.iii
Intraday Intensity Index.
ta.kc()
Keltner Channels.
ta.kcw()
Keltner Channels Width.
ta.linreg()
Linear Regression Overlay.
ta.macd()
Moving Average Convergence/Divergence.
ta.mfi()
Money Flow Index.
ta.mom()
Momentum.
ta.nvi
Negative Volume Index.
ta.obv
On-Balance Volume.
ta.pvi
Positive Volume Index.
ta.pvt
Price Volume Trend.
ta.rma()
Roughness Moving Average.
ta.roc()
Rate of Change.
ta.rsi(source, length)
Relative Strength Index.
ta.sar()
Parabolic Stop and Reverse.
ta.sma()
Simple Moving Average.
ta.stoch()
Stochastic Oscillator.
ta.supertrend()
Supertrend.
ta.swma(source)
Smoothed Weighted Moving Average.
ta.tr
True Range.
ta.tsi()
True Strength Index.
ta.vwap
Volume Weighted Average Price.
ta.vwma()
Volume Weighted Moving Average.
ta.wad
Williams Accumulation/Distribution.
ta.wma()
Weighted Moving Average.
ta.wpr()
Williams %R.
ta.wvad
Volume Accumulation/Distribution.
Supporting Functions
These functions provide various utilities for Pine Script development.
Function
Description
ta.barsince()
Number of bars since a condition was true.
ta.change()
Percent change from the previous bar's close.
ta.correlation(source1, source2, length)
Pearson's correlation coefficient between two prices.
ta.cross(source1, source2)
Checks for a crossover (source1 crosses source2 upwards).
ta.crossover(source1, source2)
Same as ta.cross.
ta.crossunder(source1, source2)
Checks for a crossunder (source1 crosses source2 downwards).
ta.cum(source)
Cumulative sum of a source.
ta.dev()
Standard deviation.
ta.falling()
True if the current bar's close is lower than the previous bar's close.
ta.highest()
Highest value from a source.
ta.highestbars()
Highest value within a specified number of bars.
ta.lowest()
Lowest value from a source.
ta.lowestbars()
Lowest value within a specified number of bars.
ta.median()
Median value of a source.
ta.mode()
Mode value of a source.
ta.percentile_linear_interpolation()
Percentile of data using linear interpolation.
ta.percentile_nearest_rank()
Percentile of data using nearest rank.
ta.percentrank(n)
Percentile rank within a specified number of bars.
ta.pivothigh()
Highest high/low preceding the current bar.
ta.pivotlow()
Lowest high/low preceding the current bar.
ta.range()
High to low range of a source.
ta.rising()
True if the current bar's close is higher than the previous bar's close.
ta.stdev()
Standard deviation of a source.
ta.valuewhen()
Last value of a source when a condition was true.
ta.variance()
Variance of a source.
Math Functions
The math namespace offers common mathematical operations.
Function
Description
math.abs(number)
Absolute value.
math.acos(number)
Arc cosine.
math.asin(number)
Arc sine.
math.atan(number)
Arc tangent.
math.avg()
Average of a list of numbers.
math.ceil(number)
Ceiling (round up to the nearest integer).
math.cos(angle)
Cosine of an angle.
math.exp(number)
Exponential.
math.floor(number)
Floor (round down to the nearest integer).
math.log(number)
Natural logarithm.
math.log10(number)
Base-10 logarithm.
math.max()
Maximum value.
math.min()
Minimum value.
math.pow()
Exponentiation (raise to a power).
math.random()
Random number between 0 and 1.
math.round(number, precision)
Round to a specified number of decimal places.
math.round_to_mintick(number)
Round to the smallest increment allowed by the broker.
math.sign(number)
Sign of a number (1 for positive, -1 for negative, 0 for zero).
math.sin(angle)
Sine of an angle.
math.sqrt(number)
Square root.
math.sum()
Sum of a list of numbers.
math.tan(angle)
Tangent of an angle.
math.todegrees()
Convert radians to degrees.
math.toradians()
Convert degrees to radians.
Requesting External Data
The request namespace enables you to fetch data from external sources.
Function
Description
request.financial()
Financial data like P/E ratio and market cap.
request.quandl()
Quandl datasets.
request.security(<...>, timeframe, <...>)
Data for a different security.
request.splits()
Stock splits data.
request.dividends()
Dividend information.
request.earnings()
Earnings data.
Ticker Functions
The ticker namespace is used to create and work with different chart types.
Function
Description
ticker.heikinashi()
Create a Heikin-Ashi chart.
ticker.kagi()
Create a Kagi chart.
ticker.linebreak()
Create a Line Break chart.
ticker.pointfigure()
Create a Point & Figure chart.
ticker.renko()
Create a Renko chart.
ticker.new()
Create a new ticker object.
Array Functions
The array namespace provides functions for manipulating arrays.
Function
Description
array.abs()
Absolute value of each element.
array.avg()
Average of array elements.
array.binary_search()
Search for a value in a sorted array.
array.binary_search_leftmost()
Index of the leftmost matching element.
array.binary_search_rightmost()
Index of the rightmost matching element.
array.clear()
Remove all elements.
array.concat()
Concatenate two arrays.
array.copy()
Create a copy of an array.
array.covariance()
Covariance of array elements.
array.every()
Check if all elements pass a test.
array.fill()
Fill the array with a value.
array.first()
First element.
array.from()
Create an array from a list of values.
array.get()
Get element at a specified index.
array.includes()
Check if an array contains a value.
array.indexof()
Index of the first occurrence of a value.
array.insert()
Insert a new element at a given index.
array.join()
Concatenate array elements into a string.
array.last()
Last element.
array.lastindexof()
Index of the last occurrence of a value.
array.max()
Maximum value in the array.
array.median()
Median value of array elements.
array.min()
Minimum value in the array.
array.mode()
Mode value of array elements.
array.new<bool>()
Create a new array of booleans.
array.new<box>()
Create a new array of boxes.
array.new<color>()
Create a new array of colors.
array.new<float>()
Create a new array of floats.
array.new<int>()
Create a new array of integers.
array.new<label>()
Create a new array of labels.
array.new<line>()
Create a new array of lines.
array.new<linefill>()
Create a new array of linefills.
array.new<string>()
Create a new array of strings.
array.new<table>()
Create a new array of tables.
array.new<type>()
Create a new array of a specified type.
array.percentile_linear_interpolation()
Percentile using linear interpolation.
array.percentile_nearest_rank()
Percentile using nearest rank.
array.percentrank()
Percentile rank of a value.
array.pop()
Remove and return the last element.
array.push()
Add elements to the end.
array.range()
Create an array with a range of numbers.
array.remove()
Remove an element at a specified index.
array.reverse()
Reverse the order of elements.
array.set()
Set the value of an element at a given index.
array.shift()
Remove and return the first element.
array.size()
Number of elements in the array.
array.slice()
Extract a section of the array.
array.some()
Check if at least one element passes a test.
array.sort()
Sort array elements in place.
array.sort_indices()
Indices of sorted elements.
array.splice()
Add or remove elements.
array.standardize()
Standardize array elements.
array.stdev()
Standard deviation of array elements.
array.sum()
Sum of array elements.
array.unshift()
Add elements to the beginning.
array.variance()
Variance of array elements.
Color Functions
Function
Description
color.a
Alpha component (transparency).
color.b
Blue component.
color.g
Green component.
color.r
Red component.
color.rgb
Create a color from red, green, blue, and transparency values.
Matrix Functions
The matrix namespace provides functions and methods for matrix operations.
Function/Method
Description
matrix.add_col
Add a column.
matrix.add_row
Add a row.
matrix.avg
Average of matrix elements.
matrix.col
Get a column from a matrix.
matrix.columns
Number of columns.
matrix.concat
Concatenate two matrices.
matrix.copy
Copy a matrix.
matrix.det
Determinant of a matrix.
matrix.diff
Difference of a matrix.
matrix.eigenvalues
Eigenvalues of a matrix.
matrix.eigenvectors
Eigenvectors of a matrix.
matrix.elements_count
Number of elements.
matrix.fill
Fill a matrix with a value.
matrix.get
Get the value of a matrix element.
matrix.inv
Inverse of a matrix.
matrix.is_antidiagonal
Check if a matrix is antidiagonal.
matrix.is_antisymmetric
Check if a matrix is antisymmetric.
matrix.is_binary
Check if a matrix is binary.
matrix.is_diagonal
Check if a matrix is diagonal.
matrix.is_identity
Check if a matrix is the identity matrix.
matrix.is_square
Check if a matrix is square.
matrix.is_stochastic
Check if a matrix is stochastic.
matrix.is_symmetric
Check if a matrix is symmetric.
matrix.is_triangular
Check if a matrix is triangular.
matrix.is_zero
Check if a matrix is the zero matrix.
matrix.kron
Kronecker product of two matrices.
matrix.max
Maximum value in a matrix.
matrix.median
Median value of matrix elements.
matrix.min
Minimum value in a matrix.
matrix.mode
Mode value of matrix elements.
matrix.mult
Product of two matrices.
matrix.new<type>
Create a new matrix of a specific type.
matrix.pinv
Pseudoinverse of a matrix.
matrix.pow
Power of a matrix.
matrix.rank
Rank of a matrix.
matrix.remove_col
Remove a column.
matrix.remove_row
Remove a row.
matrix.reshape
Reshape a matrix.
matrix.reverse
Reverse the order of elements.
matrix.row
Get a row from a matrix.
matrix.rows
Number of rows.
matrix.set
Set the value of a matrix element.
matrix.sort
Sort matrix elements.
matrix.submatrix
Get a submatrix.
matrix.sum
Sum of matrix elements.
matrix.swap_columns
Swap two columns.
matrix.swap_rows
Swap two rows.
matrix.trace
Trace of a matrix.
matrix.transpose
Transpose of a matrix.
Time Functions
Function
Description
time.dayofmonth
Day of the month.
time.dayofweek
Day of the week.
time.dayofyear
Day of the year.
time.hour
Hour.
time.isdst
Daylight saving time flag.
time.millisecond
Millisecond.
time.minute
Minute.
time.month
Month.
time.second
Second.
time.timezone
Time zone.
time.tzoffset
Time zone offset.
time.year
Year.
Notes on Pine Script
Storage Methods: Storage methods like TYPE, TYPE[], matrix<TYPE>, and array<TYPE> define how data is structured in variables and function parameters.
User Defined Types (UDTs): UDTs allow you to define custom data structures by combining fields (variables) of various types. They enhance code organization and reusability.
Function Declaration: Functions are defined with a name, parameters (with types and optional default values), and a return type. They can be exported for use in other scripts.
Annotations: Annotations (comments starting with //@) provide documentation and metadata for scripts, UDTs, functions, parameters, and variables.
Comments: Comments in Pine Script start with // and continue to the end of the line.
Default Values: Default values can be used for function parameters, allowing flexibility in how functions are called. Default values are only allowed for simple types (like int, float, string, bool) and not for complex structures (arrays, matrices, or UDTs).
Storage methods are methods that are used in type declarations.
TYPE is a built in type, or a user defined type,
identifier format is a letter or underscore followed by any number of letters, numbers, and underscores.
the type might have a class name prefix, which is a letter or underscore followed by any number of letters, numbers, and underscores, followed by a '.'
storage methods can be:
TYPE
TYPE []
matrix<TYPE>
array<TYPE>
UDT - User defined types:
The User Defined Types (UDTs) are the types that are defined in the source code, and are used in the function declarations.
a UDT FIELD is a name, which is a letter or underscore followed by any number of letters, numbers, and underscores,
A UDT is a User Defined Type that consists of:
OPTIONAL annotations:
@type tag = description of the UDT
@field tag = name of field, description of a contained field
Type declaration:
"export" keyword is optional (only for Library Scripts, no in strategy or indicator scripts)
"type" keyword is required
name of the UDT bbeing created
Fields
fields of the UDT, each field is a storage method followed by a field name, and optional default value on [ string, boolean, int, float, color ] types.
each field consists of:
an indent exactly 1 level deep.
a storage declaration (see above, "Storage methods")
a field name, which cannor start with a number and can only contain letters, numbers, and underscores
OPTIONAL :
default value, which is "=" followed by a value of the type of the field
FUNCTION declaration consists of:
OPTIONAL annotations:
@function tag = description of the function
@param tag = name of parameer, optional storage method, description of a parameter
@return tag = description of the return value
function declaration:
"export" keyword is optional on Library scripts, not Indicator or strategy.
"method" keyword is optional second keyword
NAME is a letter or underscore followed by any number of letters, numbers, and underscores
'(' PARAMS ')'
PARAMS is a comma separated list of PARAMS, and may be multiline where lines have an offset of 2 spaces
optional "series" or "simple"
optional storage method
NAME of parameter
optional default value, which is "=" followed by a value of the type of the field
DEFAULT only allowed if TYPE is specified
DEFAULT not permitted for array, matrix, or UDT type
PARAMS with default values must be at the end of the list
'=>'
denotes start of code
SINGLE_LINE_RETURN or NEW_LINE + INDENTED_BLOCK
SINGLE_LINE_RETURN is a single line of code
NEW_LINE + INDENTED_BLOCK is a block of code statements
Annotations:
Script:
for the script "library" declaration, the annotation is linked to the script itself.
it is also useful on "indicator" and "strategy" declarations, but not required.
the tag is "@description" for the script description
the tag is "@version=" for the pinescript version and mandatory
Exaample:
`@description this is a script`
UDT (user defined type):
for a udt (user defined type) declaration, the tag is "@type" and conttent is a description of the type.
for udt fields, the tag is "@field" and the content is:
(req) name of the field
(opt) storage type of the field
(opt) a description of the field.
Exaample:
`@field myfield int this is my field`
Function:
for function declaration, the tag is "@function" and the content is a description of the function. for any other function annotators, it is required
Exaample:
`@function this is my function`
for function parameters, the tag is "@param" and the content is a description of the parameter.
(req) name of the parameter
(opt) storage type of the parameter
(opt) a default value for the parameter.
(opt) a description of the parameter.
Example:
@param myparam string this is my parameter@param myparam matrix<lib.type> this is my parameter
for function return values, the tag is "@returns" and the content is a description of the return value. - (opt) storage type of the return value - (opt) a description of the return value.
Example:
`@returns int this is my return value`
variable declarations (optional)
for variable declarations, the tag is "@variable" and the content is a description of the variable.
- (req) name of the variable
- (opt) storage type of the variable
- (opt) a description of the variable.
Example:
`@variable myvar int this is my variable`
`@variable myvar matrix<implib.udtimp> this is my variable`
`@variable myvar array<int> this is my variable`
Statements:
Statements are commands that are used to execute actions or to assign values to variables.
Assignment statement:
assigns a value to a variable
consists of a variable name, an assignment operator, and a value
the value can be a literal, a variable, or an expression
Control statement:
used to control the flow of the program
consists of a keyword, followed by a condition, and a block of code
Function call statement:
calls a function
consists of a function name, followed by a list of arguments
the regex Pattern to capture a statement:
summary of the declaration rules:
User defined types:
- a UDT must have a name
- a UDT must have at least one field
- a UDT field must have a name
- a UDT field must have a type
- a UDT field name cannot start with a number
- a UDT field name can only contain letters, numbers, and underscores
- a UDT field type can only be a TYPE or a TYPE[] or matrix or array
- a UDT field name cannot be a storage type
- a UDT field type can be the UDT itself in any of the above forms
- a UDT field doed not require a default value
- a UDT field with a UDT type can not have a default value
- a UDT definition ends after the fields when a newline begins with a character hat is no a commentt or whitespac
user defined functions
- a FUNCION must have a name
- a FUNCTION may be a method
- a FUNCTION wiht method must have the TYPE specified for fisrt parameter
- a FUNCTION must have at least one parameter
- a FUNCTION parameter must have a name
- a FUNCTION parameter must have a type
- a FUNCTION parameter name cannot start with a number
- a FUNCTION parameter name can only contain letters, numbers, and underscores
- a FUNCTION parameter type can only be a TYPE or a TYPE[] or matrix or array
- a FUNCTION parameter name cannot be a storage type
- a FUNCTION parameter type can be the UDT itself in any of the above forms
- a FUNCTION parameter doed not require a default value
- a FUNCTION parameter with a UDT type can not have a default value
- a FUNCTION definition ends after the return value when a newline begins with a character hat is no a commentt or whitespac
annotations
- annotations must start a line by themselves
- annotations must start with '//' and a '@' character
- annotations must be followed by a tag, which is a specified comment from the list here:
- @description - script description before the "library" or "indicator" or "strategy" script declaration witth a '(' and string title first arg
- @type - description a UDT definition
- @field - description of a field in a UDT definition
- @function - description of a function
- @param - description of a parameter
- @return - description of a return value
- annotations of fields and parameters must be followed by the name, then description
- annotations description is any text following until code on a new line or the next annotation.
- annotations may include markdown formatting on several lines, each starting with '//' after the @tag line
comments
- comments start with twwo slashes : '//'
- comments may start a line or follow anything else
- comments run from slash to line end, and end a line
storage types
storage types can be:
TYPE
TYPE[]
matrix<TYPE>
array<TYPE>
map<BUILTIN_TYPE, TYPE>
Any UDT in place of TYPE above
storage types can not be:
TYPE[] []
matrix []
array<TYPEenter code here> []
matrix matrix
array matrix
matrix array
array array
default values
- values can be:
- a number
- a string
- a boolean
- na
- a system variable
- values cannot be:
- a matrix
- an array
- a function
- a UDT
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(r) code that uses this variable could calculate differently on history and real-time data.
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(r) code that uses this variable could calculate differently on history and real-time data.
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.
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.
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.
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.
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.
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.
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 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.
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.
Returns a unix timestamp indicating the expected time of the next earnings report, 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.
bar index of the last chart bar. bar indices begin at zero on the first bar.
Type
series int
Example
//@version=5strategy("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 chart, 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.
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.
a keyword signifying "not available", indicating that a variable has no assigned value.
Type
simple na
Example
//@version=5indicator("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 10and 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.
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
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
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
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.
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
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.
session.ismarket
Returns true if the current bar is a part of the regular trading hours (i.e. market hours), false otherwise
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=5strategy("Margin call management", overlay = true, margin_long = 25, margin_short = 25,
default_qty_type = strategy.percent_of_equity, default_qty_value = 395)
float maFast = ta.sma(close, 14)
float maslow = ta.sma(close, 28)
if ta.crossover(maFast, maslow)
strategy.entry("Long", strategy.long)
if ta.crossunder(maFast, maslow)
strategy.entry("short", strategy.short)
changepercent(v1, v2) =>
float result = (v1 - v2) * 100 / math.abs(v2)
// 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.
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).
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
Currency for the current symbol. Returns currency code: 'usD', 'EuR', etc.
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](#var_syminfo.minmove) / [syminfo.pricescale](#var_syminfo.pricescale) = [syminfo.mintick](#var_syminfo.mintick).
prefix of current symbol name (i.e. for 'CME_EOD:TickER' prefix is 'CME_EOD').
Type
simple string
Example
//@version=5indicator("syminfo.prefix")
// if current chart symbol is 'baTs:MsFT' then syminfo.prefix is 'baTs'.
if barstate.islastconfirmedhistory
label.new(bar_index, high, text=syminfo.prefix)
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](#var_syminfo.minmove) / [syminfo.pricescale](#var_syminfo.pricescale) = [syminfo.mintick](#var_syminfo.mintick).
Root for derivatives like futures contract. For other symbols returns the same value as syminfo.ticker.
Type
simple string
Example
//@version=5indicator("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)
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.
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.
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".
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.
//@version=5indicator("intraday intensity index")
plot(ta.iii, color=color.yellow)
// the same on pine
f_iii() =>
(2* close - high - low) / ((high - low) * volume)plot(f_iii())
//@version=5indicator("On balance Volume")
plot(ta.obv, color=color.yellow)
// the same on pine
f_obv() =>
ta.cum(math.sign(ta.change(close)) * volume)plot(f_obv())
//@version=5indicator("price-Volume trend")
plot(ta.pvt, color=color.yellow)
// the same on pine
f_pvt() =>
ta.cum((ta.change(close) / close[1]) * volume)plot(f_pvt())
ta.tr
true range. same as tr(false). it is max(high - low, abs(high - close[1]), abs(low - close[1]))
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.
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.
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 EuRusD the Monday session will start on sunday, 17:00). 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.
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).
a string representation of the chart's timeframe. the returned string's format is "[;][;]", where ; and ; are in some cases absent. ; is the number of units, but it is absent if that number is 1. ; is "s" for seconds, "D" for days, "W" for weeks, "M" for months, but it is absent for minutes. No ; 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.
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.
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.
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
alert(message, freq) - void
Arguments
message
(seriesstring)
Message sent when the alert triggers. Required argument.
freq (input string) the triggering frequency. possible values are: alert.freq_all (all function calls trigger the alert), alert.freq_once_per_bar (the first function call during the bar triggers the alert), alert.freq_once_per_bar_close (the function call triggers the alert only when it occurs during the last script iteration of the real-time bar, when it closes). the default is alert.freq_once_per_bar.
Example
//@version=5indicator("`alert()` example", "", true)
ma = ta.sma(close, 14)
xup = ta.crossover(close, ma)
if xup
// trigger the alert the first time a cross occurs during the real-time bar.
alert("price (" + str.tostring(close) + ") crossed over Ma (" + str.tostring(ma) + ").", alert.freq_once_per_bar)
plot(ma)
plotchar(xup, "xup", "a-2", location.top, size = size.tiny)
Remarks
the Help center explains how to create such alerts.
Creates alert condition, that is available in Create alert dialog. please note, that alertcondition does NOT create an alert, it just gives you more options in Create alert dialog. also, alertcondition effect is invisible on chart.
Syntax
alertcondition(condition, title, message) - void
Arguments
condition
(seriesbool)
series of boolean values that is used for alert. true values mean alert fire, false - no alert. Required argument.
title
(conststring)
title of the alert condition. optional argument.
message
(conststring)
Message to display when alert fires. optional argument.
Example
//@version=5indicator("alertcondition", overlay=true)
alertcondition(close >= open, title='alert on Green bar', message='Green bar!')
Remarks
please note that an alertcondition call generates an additional plot. all such calls are taken into account when we calculate the number of the output series per script.
a binary search works on arrays pre-sorted in ascending order. it begins by comparing an element in the middle of the array with the target value. if the element matches the target value, its position in the array is returned. if the element's value is greater than the target value, the search continues in the lower half of the array. if the element's value is less than the target value, the search continues in the upper half of the array. by doing this recursively, the algorithm progressively eliminates smaller and smaller portions of the array in which the target value cannot lie.
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_leftmost(id, val) → series int
//@version=5indicator("array.binary_search_leftmost, repetitive elements")
a = array.from(4, 5, 5, 5)
// Returns the index of the first instance.
position = array.binary_search_leftmost(a, 5)
plot(position) // plots 1
Remarks
a binary search works on arrays pre-sorted in ascending order. it begins by comparing an element in the middle of the array with the target value. if the element matches the target value, its position in the array is returned. if the element's value is greater than the target value, the search continues in the lower half of the array. if the element's value is less than the target value, the search continues in the upper half of the array. by doing this recursively, the algorithm progressively eliminates smaller and smaller portions of the array in which the target value cannot lie.
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.binary_search_rightmost(id, val) → series int
//@version=5indicator("array.binary_search_rightmost, repetitive elements")
a = array.from(4, 5, 5, 5)
// Returns the index of the last instance.
position = array.binary_search_rightmost(a, 5)
plot(position) // plots 3
Remarks
a binary search works on sorted arrays in ascending order. it begins by comparing an element in the middle of the array with the target value. if the element matches the target value, its position in the array is returned. if the element's value is greater than the target value, the search continues in the lower half of the array. if the element's value is less than the target value, the search continues in the upper half of the array. by doing this recursively, the algorithm progressively eliminates smaller and smaller portions of the array in which the target value cannot lie.
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.concat(id1, id2) - array;
Arguments
id1
(anyarraytype)
the first array object.
id2
(anyarraytype)
the second array object.
Example
//@version=5indicator("array.concat example")
a = array.new_float(0,0)
b = array.new_float(0,0)
for i = 0 to 4
array.push(a, high[i])
array.push(b, low[i])
c = array.concat(a,b)
plot(array.size(a))
plot(array.size(b))
plot(array.size(c))
Returns
the first array with merged elements from the second array.
the function returns the covariance of two arrays.
Syntax
array.covariance(id1, id2, biased) → series float
Arguments
id1
(int[])
an array object.
id2
(int[])
an array object.
biased
(seriesbool)
Determines which estimate should be used. optional. the default is true.
Example
//@version=5indicator("array.covariance example")
a = array.new_float(0)
b = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
array.push(b, open[i])
plot(array.covariance(a, b))
Returns
the covariance of two arrays.
Remarks
if `biased` is true, function will calculate using a biased estimate of the entire population, if false - unbiased estimate of a sample.
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.
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.
the function creates a new array object of label type elements.
Syntax
array.new_label(size, initial_value) - label[]
Arguments
size
(seriesint)
initial size of an array. optional. the default is 0.
initial_value
(serieslabel)
initial value of all array elements. optional. the default is 'na'.
Example
//@version=5indicator("array.new_label example")
var a = array.new_label()
l = label.new(bar_index, close, "some text")
array.push(a, l)
if close > close[1] and close[1] > close[2]
// remove all labels
size = array.size(a) - 1fori = 0 to size
lb = array.get(a, i)
label.delete(lb)
Returns
the iD of an array object which may be used in other array.*() functions.
//@version=5indicator("array.new<color> example")
a = array.new<color>()
array.push(a, color.red)
array.push(a, color.green)
plot(close, color = array.get(a, close > open ? 1 : 0))
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.
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.
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
(anyarraytype)
an array object.
Example
//@version=5indicator("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))
the function returns the number of elements in an array.
Syntax
array.size(id) → series int
Arguments
id
(anyarraytype)
an array object.
Example
//@version=5indicator("array.size example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
// note that changes in slice also modify original array
slice = array.slice(a, 0, 5)
array.push(slice, open)
// size was changed in slice and in original array
plot(array.size(a))
plot(array.size(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.slice(id, index_from, index_to) - array;
Arguments
id
(anyarraytype)
an array object.
index_from
(seriesint)
Zero-based index at which to begin extraction.
index_to
(seriesint)
Zero-based index before which to end extraction. the function extracts up to but not including the element with this index.
Example
//@version=5indicator("array.slice example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
// take elements from 0 to 4
// *note that changes in slice also modify original arrayslice = array.slice(a, 0, 5)
plot(array.sum(a) / 10)
plot(array.sum(slice) / 5)
the sort order: order.ascending (default) or order.descending.
Example
//@version=5indicator("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))
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.sort_indices(id, order) - int[]
Arguments
id
(float[])
an array object.
order
(seriessort_order)
the sort order: order.ascending or order.descending. optional. the default is order.ascending.
//@version=5indicator("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))
color of bars. You can use constants like 'red' or '#ff001a' as well as complex expressions like 'close >= open ? color.green : color.red'. Required argument.
offset
(seriesint)
shifts the color series to the left or to the right on the given number of bars. Default is 0.
editable
(constbool)
if true then barcolor style will be editable in format dialog. Default is true.
show_last
(inputint)
if set, defines the number of bars (from the last bar back to the past) to fill on chart.
color of the filled background. You can use constants like 'red' or '#ff001a' as well as complex expressions like 'close >= open ? color.green : color.red'. Required argument.
offset
(seriesint)
shifts the color series to the left or to the right on the given number of bars. Default is 0.
editable
(constbool)
if true then bgcolor style will be editable in format dialog. Default is true.
show_last
(inputint)
if set, defines the number of bars (from the last bar back to the past) to fill on chart.
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
(seriescolor)
color of the four borders. optional. the default is color.blue.
border_width
(seriesint)
Width of the four borders, in pixels. optional. the default is 1 pixel.
border_style
(seriesstring)
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
(seriesstring)
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
(seriesstring)
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
(seriescolor)
background color of the box. optional. the default is color.blue.
text
(seriesstring)
the text to be displayed inside the box. optional. the default is empty string.
text_size
(seriesstring)
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
(seriescolor)
the color of the text. optional. the default is color.black.
text_halign
(seriesstring)
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
(seriesstring)
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
(seriesstring)
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
(seriesstring)
the font family of the text. optional. the default value is font.family_default. possible values: font.family_default, font.family_monospace.
Example
//@version=5indicator("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.
sets extending type of the border of this box object. When extend.none is used, the horizontal borders start at the left border and end at the right border. With extend.left or extend.right, the horizontal borders are extended indefinitely to the left or right of the box, respectively. With extend.both, the horizontal borders are extended on both sides.
//@version=5indicator("Example of setting the box font")
if barstate.islastconfirmedhistory
b = box.new(bar_index, open-ta.tr, bar_index-50, open-ta.tr*5, text="monospace")
box.set_text_font_family(b, font.family_monospace)
the x-coordinate of the point, expressed as a bar index value.
price
(seriesint/float)
the y-coordinate of the point.
Remarks
the `time` field values of chart.point instances returned from this function will be na, meaning drawing objects with `xloc` values set to `xloc.bar_time` will not work with them.
chart.point.from_time
Returns a chart.point object with `time` as its x-coordinate and `price` as its y-coordinate.
Syntax
chart.point.from_time(time, price) - chart.point
Arguments
time
(seriesint)
the x-coordinate of the point, expressed as a unix time value.
price
(seriesint/float)
the y-coordinate of the point.
Remarks
the `index` field values of chart.point instances returned from this function will be na, meaning drawing objects with `xloc` values set to `xloc.bar_index` will not work with them.
chart.point.new
Creates a new chart.point object with the specified `time`, `index`, and `price`.
Syntax
chart.point.new(time, index, price) - chart.point
Arguments
time
(seriesint)
the x-coordinate of the point, expressed as a unix time value.
index
(seriesint)
the x-coordinate of the point, expressed as a bar index value.
price
(seriesint/float)
the y-coordinate of the point.
Remarks
Whether a drawing object uses a point's `time` or `index` field as an x-coordinate depends on the `xloc` type used in the function call that returned the drawing.
it's important to note that this function does not verify that the `time` and `index` values refer to the same bar.
Returns a chart.point object with `price` as the y-coordinate
Syntax
chart.point.now(price) - chart.point
Arguments
price
(seriesint/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.
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
color.from_gradient(value, bottom_value, top_value, bottom_color, top_color) → series color
Arguments
value
(seriesint/float)
Value to calculate the position-dependent color.
bottom_value
(seriesint/float)
bottom position value corresponding to bottom_color.
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.
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.
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.
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.
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
(conststring)
title of the created fill object. optional argument.
editable
(constbool)
if true then fill style will be editable in format dialog. Default is true.
fillgaps
(constbool)
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.
//@version=5indicator("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=5indicator("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
//@version=5indicator("input.hline", overlay=true)
hline(3.14, title='pi', color=color.blue, linestyle=hline.style_dotted, linewidth=2)
// You may fill the background between any two hlines with a fill() function:
h1 = hline(20)
h2 = hline(10)
fill(h1, h2, color=color.new(color.green, 90))
the title of the script. it is displayed on the chart when no `shorttitle` argument is used, and becomes the publication's default title when publishing the script.
shorttitle
(conststring)
the script's display name on charts. if specified, it will replace the `title` argument in most chart-related windows. optional. the default is the argument used for `title`.
overlay
(constbool)
if true, the indicator will be displayed over the chart. if false, it will be added in a separate pane. optional. the default is false.
specifies the number of digits after the floating point of the script's displayed values. Must be a non-negative integer no greater than 16. if `format` is set to format.inherit and `precision` is specified, the format will instead be set to format.price. optional. the default is inherited from the precision of the chart's symbol.
scale
(constscale_type)
the price scale used. possible values: scale.right, scale.left, scale.none. the scale.none value can only be applied in combination with `overlay = true`. optional. by default, the script uses the same scale as the chart.
max\_bars\_back
(constint)
the length of the historical buffer the script keeps for every variable and function, which determines how many past values can be referenced using the \[\] history-referencing operator. the required buffer size is automatically detected by the pine script(r) runtime. using this parameter is only necessary when a runtime error occurs because automatic detection fails. More information on the underlying mechanics of the historical buffer can be found in our Help center. optional. the default is 0.
timeframe
(conststring)
adds multi-timeframe functionality to simple scripts. When used, a "timeframe" field will be added to the script's "settings/inputs" tab. the field's default value will be the argument supplied, whose format must conform to timeframe string specifications. To specify the chart's timeframe, use an empty string or the timeframe.period variable. the parameter cannot be used with scripts using pine script(r) drawings. optional. the default is timeframe.period.
timeframe_gaps
(constbool)
specifies how the indicator's values are displayed on chart bars when the `timeframe` is higher than the chart's. if true, a value only appears on a chart bar when the higher `timeframe` value becomes available, otherwise na is returned (thus a "gap" occurs). With false, what would otherwise be gaps are filled with the latest known value returned, avoiding na values. When used, a "Gaps" checkbox will appear in the indicator's "settings/inputs" tab. optional. the default is true.
explicit\_plot\_zorder
(constbool)
specifies the order in which the script's plots, fills, and hlines are rendered. if true, plots are drawn in the order in which they appear in the script's code, each newer plot being drawn above the previous ones. this only applies to `plot*()` functions, fill, and hline. optional. the default is false.
max\_lines\_count
(constint)
the number of last line drawings displayed. possible values: 1-500. the count is approximate; more drawings than the specified count may be displayed. optional. the default is 50.
max\_labels\_count
(constint)
the number of last label drawings displayed. possible values: 1-500. the count is approximate; more drawings than the specified count may be displayed. optional. the default is 50.
max\_boxes\_count
(constint)
the number of last box drawings displayed. possible values: 1-500. the count is approximate; more drawings than the specified count may be displayed. optional. the default is 50.
max\_polylines\_count
(constint)
the number of last polyline drawings displayed. possible values: 1-100. the count is approximate; more drawings than the specified count may be displayed. optional. the default is 50.
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.
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
(conststring)
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
(conststring)
the string that will be shown to the user when hovering over the tooltip icon.
inline
(conststring)
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
(conststring)
Creates a header above all inputs using the same group argument string. the string is also used as the header's text.
display
(constplot_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.
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.
Determines the default value of the input variable proposed in the script's "settings/inputs" tab, from where the user can change it.
title
(conststring)
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
(conststring)
the string that will be shown to the user when hovering over the tooltip icon.
inline
(conststring)
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
(conststring)
Creates a header above all inputs using the same group argument string. the string is also used as the header's text.
confirm
(constbool)
if true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
display
(constplot_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.
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.color(defval, title, tooltip, inline, group, confirm, display) → input color
Arguments
defval
(constcolor)
Determines the default value of the input variable proposed in the script's "settings/inputs" tab, from where the user can change it.
title
(conststring)
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
(conststring)
the string that will be shown to the user when hovering over the tooltip icon.
inline
(conststring)
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
(conststring)
Creates a header above all inputs using the same group argument string. the string is also used as the header's text.
confirm
(constbool)
if true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
display
(constplot_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.
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.
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
(conststring)
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
(tupleofconstint/floatvalues: [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
(conststring)
the string that will be shown to the user when hovering over the tooltip icon.
inline
(conststring)
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
(conststring)
Creates a header above all inputs using the same group argument string. the string is also used as the header's text.
confirm
(constbool)
if true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
display
(constplot_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.
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.
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
(conststring)
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
(tupleofconstintvalues: [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
(conststring)
the string that will be shown to the user when hovering over the tooltip icon.
inline
(conststring)
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
(conststring)
Creates a header above all inputs using the same group argument string. the string is also used as the header's text.
confirm
(constbool)
if true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
display
(constplot_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.
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.
Determines the default value of the input variable proposed in the script's "settings/inputs" tab, from where the user can change it.
title
(conststring)
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
(conststring)
the string that will be shown to the user when hovering over the tooltip icon.
inline
(conststring)
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
(conststring)
Creates a header above all inputs using the same group argument string. the string is also used as the header's text.
confirm
(constbool)
if true, the interactive input mode is enabled and the selection is done by clicking on the chart when the indicator is added to the chart, or by selecting the indicator and moving the selection after that. optional. the default is false.
display
(constplot_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.
When using interactive mode, a time input can be combined with a price input if both function calls use the same argument for their `inline` parameter.
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.
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
(conststring)
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
(tupleofconststringvalues: [val1, val2, ...])
a list of options to choose from.
tooltip
(conststring)
the string that will be shown to the user when hovering over the tooltip icon.
inline
(conststring)
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
(conststring)
Creates a header above all inputs using the same group argument string. the string is also used as the header's text.
confirm
(constbool)
if true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
display
(constplot_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=5indicator("input.session", overlay=true)
i_sess = input.session("1300-1700", "session", options=["0930-1600", "1300-1700", "1700-2100"])
t = time(timeframe.period, i_sess)
bgcolor(time == t ? color.green : na)
Returns
Value of input variable.
Remarks
Result of input.session function always should be assigned to a variable, see examples above.
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.source(defval, title, tooltip, inline, group, display) → series float
Arguments
defval
(open/high/low/close/hl2/hlc3/ohlc4/hlcc4)
Determines the default value of the input variable proposed in the script's "settings/inputs" tab, from where the user can change it.
title
(conststring)
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
(conststring)
the string that will be shown to the user when hovering over the tooltip icon.
inline
(conststring)
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
(conststring)
Creates a header above all inputs using the same group argument string. the string is also used as the header's text.
display
(constplot_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.
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.
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
(conststring)
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
(tupleofconststringvalues: [val1, val2, ...])
a list of options to choose from.
tooltip
(conststring)
the string that will be shown to the user when hovering over the tooltip icon.
inline
(conststring)
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
(conststring)
Creates a header above all inputs using the same group argument string. the string is also used as the header's text.
confirm
(constbool)
if true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
display
(constplot_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.
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.
Determines the default value of the input variable proposed in the script's "settings/inputs" tab, from where the user can change it.
title
(conststring)
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
(conststring)
the string that will be shown to the user when hovering over the tooltip icon.
inline
(conststring)
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
(conststring)
Creates a header above all inputs using the same group argument string. the string is also used as the header's text.
confirm
(constbool)
if true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
display
(constplot_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.
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.
Determines the default value of the input variable proposed in the script's "settings/inputs" tab, from where the user can change it.
title
(conststring)
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
(conststring)
the string that will be shown to the user when hovering over the tooltip icon.
group
(conststring)
Creates a header above all inputs using the same group argument string. the string is also used as the header's text.
confirm
(constbool)
if true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
display
(constplot_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=5indicator("input.text_area")
i_text = input.text_area(defval = "HelloWorld!", 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.
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.time(defval, title, tooltip, inline, group, confirm, display) → input int
Arguments
defval
(constint)
Determines the default value of the input variable proposed in the script's "settings/inputs" tab, from where the user can change it. the value can be a timestamp function, but only if it uses a date argument in const string format.
title
(conststring)
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
(conststring)
the string that will be shown to the user when hovering over the tooltip icon.
inline
(conststring)
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
(conststring)
Creates a header above all inputs using the same group argument string. the string is also used as the header's text.
confirm
(constbool)
if true, the interactive input mode is enabled and the selection is done by clicking on the chart when the indicator is added to the chart, or by selecting the indicator and moving the selection after that. optional. the default is false.
display
(constplot_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.
When using interactive mode, a price input can be combined with a time input if both function calls use the same argument for their `inline` parameter.
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.
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
(conststring)
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
(tupleofconststringvalues: [val1, val2, ...])
a list of options to choose from.
tooltip
(conststring)
the string that will be shown to the user when hovering over the tooltip icon.
inline
(conststring)
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
(conststring)
Creates a header above all inputs using the same group argument string. the string is also used as the header's text.
confirm
(constbool)
if true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
display
(constplot_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.
//@version=5indicator('Last 100 bars highest/lowest', overlay = true)
Lookback = 100highest = 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.new
label.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_text(id) → series string
### Arguments
- `id`
> (`series` `label`)
> label object.
### Example
//@version=5indicator("label.get_text")
my_label = label.new(time, open, text="Open bar text", xloc=xloc.bar_time)
a = label.get_text(my_label)
label.new(time, close, text = a + " new", xloc=xloc.bar_time)
//@version=5indicator("Example of setting the label font")
if barstate.islastconfirmedhistory
l = label.new(bar_index, 0, "monospace", yloc=yloc.abovebar)
label.set_text_font_family(l, font.family_monospace)
sets bar index or bar time (depending on the xloc) of the label position.
Syntax
label.set_x(id, x) - void
Arguments
id
(serieslabel)
label object.
x
(seriesint)
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.
sets bar index/time and price of the label position.
Syntax
label.set_xy(id, x, y) - void
Arguments
id
(serieslabel)
label object.
x
(seriesint)
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.
Declaration statement identifying a script as a library.
Syntax
library(title, overlay) - void
Arguments
title
(conststring)
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
(constbool)
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.0plot(sinh(0))
//@version=5indicator('Last 100 bars price range', overlay = true)
Lookback = 100highest = ta.highest(Lookback)
lowest = ta.lowest(Lookback)
if barstate.islastconfirmedhistory
var lineTop = line.new(bar_index[Lookback], highest, bar_index, highest, color = color.green)
var linebottom = line.copy(lineTop)
line.set_y1(linebottom, lowest)
line.set_y2(linebottom, lowest)
line.set_color(linebottom, color.red)
### Returns
New line iD object which may be passed to line.setXXX and line.getXXX functions.
### See also
line.new
line.delete
## 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_price(id, x) → series float
### Arguments
- `id`
> (`series` `line`)
> line object.
- `x`
> (`series` `int`)
> bar index forwhich price is required.
### Example
//@version=5indicator("Getprice", overlay=true)
var line l = na
if bar_index == 10
l := line.new(0, high[5], bar_index, high)
plot(line.get_price(l, bar_index), color=color.green)
Returns
price value of line 'id' at bar index 'x'.
Remarks
the line is considered to have been created using 'extend=extend.both'.
this function can only be called for lines created using 'xloc.bar_index'. if you try to call it for a line created with 'xloc.bar_time', it will generate an error.
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.
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.
deletes the specified linefill object. if it has already been deleted, does nothing.
Syntax
linefill.delete(id) - void
Arguments
id
(serieslinefill)
a linefill object.
linefill.get_line1
Returns the iD of the first line used in the `id` linefill.
Syntax
linefill.get_line1(id) → series line
Arguments
id
(serieslinefill)
a linefill object.
linefill.get_line2
Returns the iD of the second line used in the `id` linefill.
Syntax
linefill.get_line2(id) → series line
Arguments
id
(serieslinefill)
a linefill object.
linefill.new
Creates a new linefill object and displays it on the chart, filling the space between `line1` and `line2` with the color specified in `color`.
Syntax
linefill.new(line1, line2, color) → series linefill
Arguments
line1
(seriesline)
First line object.
line2
(seriesline)
second line object.
color
(seriescolor)
the color used to fill the space between the lines.
Returns
the iD of a linefill object that can be passed to other linefill.*() functions.
Remarks
if any line of the two is deleted, the linefill object is also deleted. if the lines are moved (e.g. via line.set_xy functions), the linefill object is also moved.
if both lines are extended in the same direction relative to the lines themselves (e.g. both have extend.right as the value of their `extend=` parameter), the space between line extensions will also be filled.
linefill.set_color
the function sets the color of the linefill object passed to it.
Syntax
linefill.set_color(id, color) - void
Arguments
id
(serieslinefill)
a linefill object.
color
(seriescolor)
the color of the linefill object.
log.error
+1 overload
Converts the formatting string and value(s) into a formatted string, and sends the result to the "pine Logs" menu tagged with the "error" debug level.
the formatting string can contain literal text and one placeholder in curly braces {} for each value to be formatted. Each placeholder consists of the index of the required argument (beginning at 0) that will replace it, and an optional format specifier. the index represents the position of that argument in the function's argument list.
//@version=5strategy("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)")
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)
limitLevel = close * 1.01
log.info("Long limit order has been placed at {0}", limitLevel)
strategy.order("My Long Entry id", strategy.long, limit = limitLevel)
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 = bracketticksizeinput)
if strategy.opentrades > 10
log.warning("{0} positions opened in the same direction in a row. try adjusting `bracketticksizeinput`", strategy.opentrades)
last10perc = strategy.initial_capital / 10 > strategy.equity
if (last10perc andnot last10perc[1])
log.error("the strategy has lost 90% of the initial capital!")
Returns
the formatted string.
Remarks
any curly braces within an unquoted pattern must be balanced. For example, "ab {0} de" and "ab '}' de" are valid patterns, but "ab {0'}' de", "ab } de" and "''{''" are not.
the function can apply additional formatting to some values inside of the {}. the list of additional formatting options can be found in the EXaMpLE section of the str.format article.
the "pine Logs..." button is accessible from the "More" dropdown in the pine Editor and from the "More" dropdown in the status line of any script that uses `log.*()` functions.
log.info
+1 overload
Converts the formatting string and value(s) into a formatted string, and sends the result to the "pine Logs" menu tagged with the "info" debug level.
the formatting string can contain literal text and one placeholder in curly braces {} for each value to be formatted. Each placeholder consists of the index of the required argument (beginning at 0) that will replace it, and an optional format specifier. the index represents the position of that argument in the function's argument list.
//@version=5strategy("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)")
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)
limitLevel = close * 1.01
log.info("Long limit order has been placed at {0}", limitLevel)
strategy.order("My Long Entry id", strategy.long, limit = limitLevel)
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 = bracketticksizeinput)
if strategy.opentrades > 10
log.warning("{0} positions opened in the same direction in a row. try adjusting `bracketticksizeinput`", strategy.opentrades)
last10perc = strategy.initial_capital / 10 > strategy.equity
if (last10perc andnot last10perc[1])
log.error("the strategy has lost 90% of the initial capital!")
Returns
the formatted string.
Remarks
any curly braces within an unquoted pattern must be balanced. For example, "ab {0} de" and "ab '}' de" are valid patterns, but "ab {0'}' de", "ab } de" and "''{''" are not.
the function can apply additional formatting to some values inside of the {}. the list of additional formatting options can be found in the EXaMpLE section of the str.format article.
the "pine Logs..." button is accessible from the "More" dropdown in the pine Editor and from the "More" dropdown in the status line of any script that uses `log.*()` functions.
log.warning
+1 overload
Converts the formatting string and value(s) into a formatted string, and sends the result to the "pine Logs" menu tagged with the "warning" debug level.
the formatting string can contain literal text and one placeholder in curly braces {} for each value to be formatted. Each placeholder consists of the index of the required argument (beginning at 0) that will replace it, and an optional format specifier. the index represents the position of that argument in the function's argument list.
//@version=5strategy("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)")
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)
limitLevel = close * 1.01
log.info("Long limit order has been placed at {0}", limitLevel)
strategy.order("My Long Entry id", strategy.long, limit = limitLevel)
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 = bracketticksizeinput)
if strategy.opentrades > 10
log.warning("{0} positions opened in the same direction in a row. try adjusting `bracketticksizeinput`", strategy.opentrades)
last10perc = strategy.initial_capital / 10 > strategy.equity
if (last10perc andnot last10perc[1])
log.error("the strategy has lost 90% of the initial capital!")
Returns
the formatted string.
Remarks
any curly braces within an unquoted pattern must be balanced. For example, "ab {0} de" and "ab '}' de" are valid patterns, but "ab {0'}' de", "ab } de" and "''{''" are not.
the function can apply additional formatting to some values inside of the {}. the list of additional formatting options can be found in the EXaMpLE section of the str.format article.
the "pine Logs..." button is accessible from the "More" dropdown in the pine Editor and from the "More" dropdown in the status line of any script that uses `log.*()` functions.
map.clear
Clears the map, removing all key-value pairs from it.
Returns true if the `key` was found in the `id` map, false otherwise.
Syntax
map.contains(id, key) → series bool
Arguments
id
(anymaptype)
a map object.
key
(series <typeofthemap'selements>;)
the key to search in the map.
Example
//@version=5indicator("map.includes example")
a = map.new<string, float>()
a.put("open", open)
p = close
if map.contains(a, "open")
p := a.get("open")
plot(p)
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 only be a primitive type, i.e., one of the following: 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.
the iD of a map object which may be used in other map.*() functions.
Remarks
Each key is unique and can only appear once. When adding a new value with a key that the map already contains, that value replaces the old value associated with the key.
maps maintain insertion order. Note that the order does not change when inserting a pair with a `key` that's already in the map. the new pair replaces the existing pair with the `key` in such cases.
the previous value associated with `key` if the key was already present in the map, or na if the key is new.
Remarks
maps maintain insertion order. Note that the order does not change when inserting a pair with a `key` that's already in the map. the new pair replaces the existing pair with the `key` in such cases.
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
math.random(min, max, seed) → series float
Arguments
min
(seriesint/float)
the lower bound of the range of random values. the value is not included in the range. the default is 0.
max
(seriesint/float)
the upper bound of the range of random values. the value is not included in the range. the default is 1.
seed
(simpleint)
optional argument. When the same seed is used, allows successive calls to the function to produce a repeatable set of values.
Returns
a random value.
math.round
+7 overloads
Returns the value of `number` rounded to the nearest integer, with ties rounding up. if the `precision` parameter is used, returns a float value rounded to that amount of decimal places.
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.
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=5indicator("`matrix.add_col()` Example 1")
// Create a 2x3 "int" matrix containing values `0`.
m = matrix.new<int>(2, 3, 0)
// add a column with `na` values to the matrix.
matrix.add_col(m)
// Display matrix elements.
if barstate.islastconfirmedhistory
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Matrix elements:")
table.cell(t, 0, 1, str.tostring(m))
adding an array as a column to the matrix
Example
//@version=5indicator("`matrix.add_col()` Example 2")
if barstate.islastconfirmedhistory
// Create an empty matrix object.
var m = matrix.new<int>()
// Create an array with values `1` and `3`.
var a = array.from(1, 3)
// add the `a` array as the first column of the empty matrix.
matrix.add_col(m, 0, a)
// Display matrix elements.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Matrix elements:")
table.cell(t, 0, 1, str.tostring(m))
Remarks
Rather than add columns to an empty matrix, it is far more efficient to declare a matrix with explicit dimensions and fill it with values. adding a column is also much slower than adding a row with the matrix.add_row function.
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=5indicator("`matrix.add_row()` Example 1")
// Create a 2x3 "int" matrix containing values `0`.
m = matrix.new<int>(2, 3, 0)
// add a row with `na` values to the matrix.
matrix.add_row(m)
// Display matrix elements.
if barstate.islastconfirmedhistory
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Matrix elements:")
table.cell(t, 0, 1, str.tostring(m))
adding an array as a row to the matrix
Example
//@version=5indicator("`matrix.add_row()` Example 2")
if barstate.islastconfirmedhistory
// Create an empty matrix object.
var m = matrix.new<int>()
// Create an array with values `1` and `2`.
var a = array.from(1, 2)
// add the `a` array as the first row of the empty matrix.
matrix.add_row(m, 0, a)
// Display matrix elements.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Matrix elements:")
table.cell(t, 0, 1, str.tostring(m))
Remarks
indexing of rows and columns starts at zero. Rather than add rows to an empty matrix, it is far more efficient to declare a matrix with explicit dimensions and fill it with values.
//@version=5indicator("`matrix.avg()` 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)
// Get the average value of the matrix.
var x = matrix.avg(m)
plot(x, 'Matrix average value')
the function creates a one-dimensional array from the elements of a matrix column.
Syntax
matrix.col(id, column) - type[]
Arguments
id
(anymatrixtype)
a matrix object.
column
(seriesint)
index of the required column.
Example
//@version=5indicator("`matrix.col()` Example", "", true)
// Create a 2x3 "float" matrix from `hlc3` values.
m = matrix.new<float>(2, 3, hlc3)
// Return an array with the values of the first column of matrix `m`.
a = matrix.col(m, 0)
// plot the first value from the array `a`.
plot(array.get(a, 0))
Returns
an array iD containing the `column` values of the `id` matrix.
the function returns the number of columns in the matrix.
Syntax
matrix.columns(id) → series int
Arguments
id
(anymatrixtype)
a matrix object.
Example
//@version=5indicator("`matrix.columns()` Example")
// Create a 2x6 matrix with values `0`.
var m = matrix.new<int>(2, 6, 0)
// Get the quantity of columns in matrix `m`.
var x = matrix.columns(m)
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, "columns: " + str.tostring(x) + "" + str.tostring(m))
the function creates a new matrix which is a copy of the original.
Syntax
matrix.copy(id) - matrix;
Arguments
id
(anymatrixtype)
a matrix object to copy.
Example
//@version=5indicator("`matrix.copy()` Example")
// Forefficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 "float" matrix with `1` values.
var m1 = matrix.new<float>(2, 3, 1)
// Copy the matrix to a new one.
// Note that unlike what `matrix.copy()` does,
// the simple assignment operation `m2 = m1`
// would NOT create a new copy of the `m1` matrix.
// it would merely create a copy of its iD referencing the same matrix.
var m2 = matrix.copy(m1)
// Display using a table.
var t = table.new(position.top_right, 5, 2, color.green)
table.cell(t, 0, 0, "Original Matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "Matrix Copy:")
table.cell(t, 1, 1, str.tostring(m2))
//@version=5indicator("`matrix.det` Example")
// Create a 2x2 matrix.
var m = matrix.new<float>(2, 2, na)
// Fill the matrix with values.
matrix.set(m, 0, 0, 3)
matrix.set(m, 0, 1, 7)
matrix.set(m, 1, 0, 1)
matrix.set(m, 1, 1, -4)
// Get the determinant of the matrix.
var x = matrix.det(m)
plot(x, 'Matrix determinant')
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).
//@version=5indicator("`matrix.diff()` Example 1")
// Forefficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix containing values `5`.
var m1 = matrix.new<float>(2, 3, 5)
// Create a 2x3 matrix containing values `4`.
var m2 = matrix.new<float>(2, 3, 4)
// Create a new matrix containing the difference between matrices `m1` and `m2`.
var m3 = matrix.diff(m1, m2)
// Display using a table.
var t = table.new(position.top_right, 1, 2, color.green)
table.cell(t, 0, 0, "Difference between two matrices:")
table.cell(t, 0, 1, str.tostring(m3))
Difference between a matrix and a scalar value
Example
//@version=5indicator("`matrix.diff()` Example 2")
// Forefficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix with values `4`.
var m1 = matrix.new<float>(2, 3, 4)
// Create a new matrix containing the difference between the `m1` matrix and the "int" value `1`.
var m2 = matrix.diff(m1, 1)
// Display using a table.
var t = table.new(position.top_right, 1, 2, color.green)
table.cell(t, 0, 0, "Difference between a matrix and a scalar:")
table.cell(t, 0, 1, str.tostring(m2))
Returns
a new matrix object containing the difference between `id2` and `id1`.
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`.
Row index from which the fill will begin (inclusive). optional. the default value is 0.
to_row
(seriesint)
Row index where the fill will end (not inclusive). optional. the default value is matrix.rows.
from_column
(seriesint)
column index from which the fill will begin (inclusive). optional. the default value is 0.
to_column
(seriesint)
column index where the fill will end (non inclusive). optional. the default value is matrix.columns.
Example
//@version=5indicator("`matrix.fill()` Example")
// Create a 4x5 "int" matrix containing values `0`.
m = matrix.new<float>(4, 5, 0)
// Fill the intersection of rows 1 to 2and columns 2 to 3 of the matrix with `hl2` values.
matrix.fill(m, hl2, 0, 2, 1, 3)
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(m))
the function returns the element with the specified index of the matrix.
Syntax
matrix.get(id, row, column) - <matrix_type>;
Arguments
id
(anymatrixtype)
a matrix object.
row
(seriesint)
index of the required row.
column
(seriesint)
index of the required column.
Example
//@version=5indicator("`matrix.get()` Example", "", true)
// Create a 2x3 "float" matrix from the `hl2` values.
m = matrix.new<float>(2, 3, hl2)
// Return the value of the element at index [0, 0] of matrix `m`.
x = matrix.get(m, 0, 0)
plot(x)
Returns
the value of the element at the `row` and `column` index of the `id` matrix.
//@version=5indicator("`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)
// Get the maximum value in the matrix.
var x = matrix.max(m)
plot(x, 'Matrix maximum value')
//@version=5indicator("`matrix.median()` Example")
// Create a 2x2 matrix.
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)
// Get the median of the matrix.
x = matrix.median(m)
plot(x, 'Median of the matrix')
Remarks
Note that na elements of the matrix are not considered when calculating the median.
//@version=5indicator("`matrix.min()` 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)
// Get the minimum value from the matrix.
var x = matrix.min(m)
plot(x, 'Matrix minimum value')
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.
//@version=5indicator("`matrix.mode()` Example")
// Create a 2x2 matrix.
var m = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m, 0, 0, 0)
matrix.set(m, 0, 1, 0)
matrix.set(m, 1, 0, 1)
matrix.set(m, 1, 1, 1)
// Get the mode of the matrix.
var x = matrix.mode(m)
plot(x, 'Mode of the matrix')
Returns
the most frequently occurring value from the `id` matrix. if none exists, returns the smallest value instead.
Remarks
Note that na elements of the matrix are not considered when calculating the mode.
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).
//@version=5indicator("`matrix.mult()` Example 1")
// Forefficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 6x2 matrix containing values `5`.
var m1 = matrix.new<float>(6, 2, 5)
// Create a 2x3 matrix containing values `4`.
// Note that it must have the same quantity of rows as there are columns in the first matrix.
var m2 = matrix.new<float>(2, 3, 4)
// Create a new matrix from the multiplication of the two matrices.
var m3 = matrix.mult(m1, m2)
// Display using a table.
var t = table.new(position.top_right, 1, 2, color.green)
table.cell(t, 0, 0, "product of two matrices:")
table.cell(t, 0, 1, str.tostring(m3))
product of a matrix and a scalar
Example
//@version=5indicator("`matrix.mult()` Example 2")
// Forefficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix containing values `4`.
var m1 = matrix.new<float>(2, 3, 4)
// Create a new matrix from the product of the two matrices.
scalar = 5
var m2 = matrix.mult(m1, scalar)
// Display using a table.
var t = table.new(position.top_right, 5, 2, color.green)
table.cell(t, 0, 0, "Matrix 1:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, "x")
table.cell(t, 2, 0, "scalar:")
table.cell(t, 2, 1, str.tostring(scalar))
table.cell(t, 3, 1, "=")
table.cell(t, 4, 0, "Matrix 2:")
table.cell(t, 4, 1, str.tostring(m2))
product of a matrix and an array vector
Example
//@version=5indicator("`matrix.mult()` Example 3")
// Forefficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix containing values `4`.
var m1 = matrix.new<int>(2, 3, 4)
// Create an array of three elements.
var int[] a = array.from(1, 1, 1)
// Create a new matrix containing the product of the `m1` matrix and the `a` array.
var m3 = matrix.mult(m1, a)
// Display using a table.
var t = table.new(position.top_right, 5, 2, color.green)
table.cell(t, 0, 0, "Matrix 1:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, "x")
table.cell(t, 2, 0, "Value:")
table.cell(t, 2, 1, str.tostring(a, " "))
table.cell(t, 3, 1, "=")
table.cell(t, 4, 0, "Matrix 3:")
table.cell(t, 4, 1, str.tostring(m3))
Returns
a new matrix object containing the product of `id2` and `id1`.
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 (";").
initial row count of the matrix. optional. the default value is 0.
columns
(seriesint)
initial column count of the matrix. optional. the default value is 0.
initial\_value
(<matrix`_type`>;)
initial value of all matrix elements. optional. the default is 'na'.
Create a matrix of elements with the same initial value
Example
//@version=5indicator("`matrix.new<type>()` Example 1")
// Create a 2x3 (2 rows x 3 columns) "int" matrix with values zero.
var m = matrix.new<int>(2, 3, 0)
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(m))
Create a matrix from array values
Example
//@version=5indicator("`matrix.new<type>()` Example 2")
// 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)
fori = 0 to rows <= 0 ? na : rows - 1forj = 0 to columns <= 0 ? na : columns - 1
matrix.set(m, i, j, array.get(data, i * columns + j))
m
// Create a 3x3 matrix from an array of values.
var m1 = matrixFromarray(3, 3, array.from(1, 2, 3, 4, 5, 6, 7, 8, 9))
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(m1))
Create a matrix from an `input.text_area()` field
Example
//@version=5indicator("`matrix.new<type>()` Example 3")
// Function to create a matrix from a text string.
// Values in a row must be separated by a space. Each line is one row.
matrixFrominputarea(stringOfValues) =>
var rowsarray = str.split(stringOfValues, "")
var rows = array.size(rowsarray)
var cols = array.size(str.split(array.get(rowsarray, 0), " "))
var matrix = matrix.new<float>(rows, cols, na)
row = 0forrowstring in rowsarray
col = 0
values = str.split(rowstring, " ")
forval in values
matrix.set(matrix, row, col, str.tonumber(val))
col += 1
row += 1
matrix
stringinput = input.text_area("1 2 34 5 67 8 9")
var m = matrixFrominputarea(stringinput)
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(m))
Create matrix from random values
Example
//@version=5indicator("`matrix.new<type>()` Example 4")
// Function to create a matrix with random values (0.0 to 1.0).
matrixRandom(int rows, int columns)=>
result = matrix.new<float>(rows, columns)
fori = 0 to rows - 1forj = 0 to columns - 1
matrix.set(result, i, j, math.random())
result
// Create a 2x3 matrix with random values.
var m = matrixRandom(2, 3)
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(m))
//@version=5indicator("`matrix.pinv()` Example")
// Forefficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix.
var m1 = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
// pseudoinverse of the matrix.
var m2 = matrix.pinv(m1)
// Display matrix elements.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original Matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "pseudoinverse matrix:")
table.cell(t, 1, 1, str.tostring(m2))
Returns
a new matrix containing the pseudoinverse of the `id` matrix.
Remarks
the function is calculated using a Moore-penrose inverse formula based on singular-value decomposition of a matrix. For non-singular square matrices this function returns the result of matrix.inv.
the number of times the matrix will be multiplied by itself.
Example
//@version=5indicator("`matrix.pow()` Example")
// Display using a table.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix.
var m1 = matrix.new<int>(2, 2, 2)
// Calculate the power of three of the matrix.
var m2 = matrix.pow(m1, 3)
// Display matrix elements.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original Matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "MatrixA3:")
table.cell(t, 1, 1, str.tostring(m2))
Returns
the product of the `id` matrix by itself `power` times.
//@version=5indicator("`matrix.rank()` Example")
// Forefficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix.
var m1 = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
// Get the rank of the matrix.
r = matrix.rank(m1)
// Display matrix elements.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Matrix elements:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "Rank of the matrix:")
table.cell(t, 1, 1, str.tostring(r))
the function removes the column at `column` index of the `id` matrix and returns an array containing the removed column's values.
Syntax
matrix.remove_col(id, column) - type[]
Arguments
id
(anymatrixtype)
a matrix object.
column
(seriesint)
the index of the column to be removed. optional. the default value is matrix.columns.
Example
//@version=5indicator("matrix_remove_col", overlay = true)
// Create a 2x2 matrix with ones.
var matrixOrig = matrix.new<int>(2, 2, 1)
// set values to the 'matrixOrig' matrix.
matrix.set(matrixOrig, 0, 1, 2)
matrix.set(matrixOrig, 1, 0, 3)
matrix.set(matrixOrig, 1, 1, 4)
// Create a copy of the 'matrixOrig' matrix.
matrixCopy = matrix.copy(matrixOrig)
// Remove the first column from the `matrixCopy` matrix.
arr = matrix.remove_col(matrixCopy, 0)
// Display matrix elements.
if barstate.islastconfirmedhistory
var t = table.new(position.top_right, 3, 2, color.green)
table.cell(t, 0, 0, "Original Matrix:")
table.cell(t, 0, 1, str.tostring(matrixOrig))
table.cell(t, 1, 0, "Removed elements:")
table.cell(t, 1, 1, str.tostring(arr))
table.cell(t, 2, 0, "Result Matrix:")
table.cell(t, 2, 1, str.tostring(matrixCopy))
Returns
an array containing the elements of the column removed from the `id` matrix.
Remarks
indexing of rows and columns starts at zero. it is far more efficient to declare matrices with explicit dimensions than to build them by adding or removing columns. deleting a column is also much slower than deleting a row with the matrix.remove_row function.
the function removes the row at `row` index of the `id` matrix and returns an array containing the removed row's values.
Syntax
matrix.remove_row(id, row) - type[]
Arguments
id
(anymatrixtype)
a matrix object.
row
(seriesint)
the index of the row to be deleted. optional. the default value is matrix.rows.
Example
//@version=5indicator("matrix_remove_row", overlay = true)
// Create a 2x2 "int" matrix containing values `1`.
var matrixOrig = matrix.new<int>(2, 2, 1)
// set values to the 'matrixOrig' matrix.
matrix.set(matrixOrig, 0, 1, 2)
matrix.set(matrixOrig, 1, 0, 3)
matrix.set(matrixOrig, 1, 1, 4)
// Create a copy of the 'matrixOrig' matrix.
matrixCopy = matrix.copy(matrixOrig)
// Remove the first row from the matrix `matrixCopy`.
arr = matrix.remove_row(matrixCopy, 0)
// Display matrix elements.
if barstate.islastconfirmedhistory
var t = table.new(position.top_right, 3, 2, color.green)
table.cell(t, 0, 0, "Original Matrix:")
table.cell(t, 0, 1, str.tostring(matrixOrig))
table.cell(t, 1, 0, "Removed elements:")
table.cell(t, 1, 1, str.tostring(arr))
table.cell(t, 2, 0, "Result Matrix:")
table.cell(t, 2, 1, str.tostring(matrixCopy))
Returns
an array containing the elements of the row removed from the `id` matrix.
Remarks
indexing of rows and columns starts at zero. it is far more efficient to declare matrices with explicit dimensions than to build them by adding or removing rows.
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
(anymatrixtype)
a matrix object.
Example
//@version=5indicator("`matrix.reverse()` Example")
// Forefficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Copy the matrix to a new one.
var m1 = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
// Copy matrix elements to a new matrix.
var m2 = matrix.copy(m1)
// Reverse the `m2` copy of the original matrix.
matrix.reverse(m2)
// Display using a table.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "Reversed matrix:")
table.cell(t, 1, 1, str.tostring(m2))
the function creates a one-dimensional array from the elements of a matrix row.
Syntax
matrix.row(id, row) - type[]
Arguments
id
(anymatrixtype)
a matrix object.
row
(seriesint)
index of the required row.
Example
//@version=5indicator("`matrix.row()` Example", "", true)
// Create a 2x3 "float" matrix from `hlc3` values.
m = matrix.new<float>(2, 3, hlc3)
// Return an array with the values of the first row of the matrix.
a = matrix.row(m, 0)
// plot the first value from the array `a`.
plot(array.get(a, 0))
Returns
an array iD containing the `row` values of the `id` matrix.
the function returns the number of rows in the matrix.
Syntax
matrix.rows(id) → series int
Arguments
id
(anymatrixtype)
a matrix object.
Example
//@version=5indicator("`matrix.rows()` Example")
// Create a 2x6 matrix with values `0`.
var m = matrix.new<int>(2, 6, 0)
// Get the quantity of rows in the matrix.
var x = matrix.rows(m)
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, "Rows: " + str.tostring(x) + "" + str.tostring(m))
the function assigns `value` to the element at the `row` and `column` of the `id` matrix.
Syntax
matrix.set(id, row, column, value) - void
Arguments
id
(anymatrixtype)
a matrix object.
row
(seriesint)
the row index of the element to be modified.
column
(seriesint)
the column index of the element to be modified.
value
(series <typeofthematrix'selements>;)
the new value to be set.
Example
//@version=5indicator("`matrix.set()` Example")
// Create a 2x3 "int" matrix containing values `4`.
m = matrix.new<int>(2, 3, 4)
// Replace the value of element at row 1and column 2 with value `3`.
matrix.set(m, 0, 1, 3)
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(m))
//@version=5indicator("`matrix.sort()` Example")
// Forefficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix.
var m1 = matrix.new<float>(2, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 3)
matrix.set(m1, 0, 1, 4)
matrix.set(m1, 1, 0, 1)
matrix.set(m1, 1, 1, 2)
// Copy the matrix to a new one.
var m2 = matrix.copy(m1)
// sort the rows of `m2` using the default arguments (first column and ascending order).
matrix.sort(m2)
// Display using a table.
if barstate.islastconfirmedhistory
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "sorted matrix:")
table.cell(t, 1, 1, str.tostring(m2))
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).
//@version=5indicator("`matrix.sum()` Example 1")
// Forefficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix containing values `5`.
var m1 = matrix.new<float>(2, 3, 5)
// Create a 2x3 matrix containing values `4`.
var m2 = matrix.new<float>(2, 3, 4)
// Create a new matrix that sums matrices `m1` and `m2`.
var m3 = matrix.sum(m1, m2)
// Display using a table.
var t = table.new(position.top_right, 1, 2, color.green)
table.cell(t, 0, 0, "sum of two matrices:")
table.cell(t, 0, 1, str.tostring(m3))
sum of a matrix and scalar
Example
//@version=5indicator("`matrix.sum()` Example 2")
// Forefficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix with values `4`.
var m1 = matrix.new<float>(2, 3, 4)
// Create a new matrix containing the sum of the `m1` matrix with the "int" value `1`.
var m2 = matrix.sum(m1, 1)
// Display using a table.
var t = table.new(position.top_right, 1, 2, color.green)
table.cell(t, 0, 0, "sum of a matrix and a scalar:")
table.cell(t, 0, 1, str.tostring(m2))
Returns
a new matrix object containing the sum of `id2` and `id1`.
the function swaps the columns at the index `column1` and `column2` in the `id` matrix.
Syntax
matrix.swap_columns(id, column1, column2) - void
Arguments
id
(anymatrixtype)
a matrix object.
column1
(seriesint)
index of the first column to be swapped.
column2
(seriesint)
index of the second column to be swapped.
Example
//@version=5indicator("`matrix.swap_columns()` Example")
// Forefficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix with aEUR~naaEUR(tm) values.
var m1 = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
// Copy the matrix to a new one.
var m2 = matrix.copy(m1)
// swap the first and second columns of the matrix copy.
matrix.swap_columns(m2, 0, 1)
// Display using a table.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "swapped columns in copy:")
table.cell(t, 1, 1, str.tostring(m2))
the function swaps the rows at the index `row1` and `row2` in the `id` matrix.
Syntax
matrix.swap_rows(id, row1, row2) - void
Arguments
id
(anymatrixtype)
a matrix object.
row1
(seriesint)
index of the first row to be swapped.
row2
(seriesint)
index of the second row to be swapped.
Example
//@version=5indicator("`matrix.swap_rows()` Example")
// Forefficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 3x2 matrix with aEUR~naaEUR(tm) values.
var m1 = matrix.new<int>(3, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
matrix.set(m1, 2, 0, 5)
matrix.set(m1, 2, 1, 6)
// Copy the matrix to a new one.
var m2 = matrix.copy(m1)
// swap the first and second rows of the matrix copy.
matrix.swap_rows(m2, 0, 1)
// Display using a table.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "swapped rows in copy:")
table.cell(t, 1, 1, str.tostring(m2))
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(r) 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(r) 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
(seriesbool)
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
(constint)
History buffer size which is the number of bars that could be referenced for variable 'var'.
Example
//@version=5indicator("max_bars_back")
close_() => close
depth() => 400d = 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.
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.
//@version=5indicator("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))
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
(inputint)
Width of the plotted line. Default value is 1. Not applicable to every style.
if true then plot style will be editable in format dialog. Default is true.
show_last
(inputint)
if set, defines the number of bars (from the last bar back to the past) to plot on chart.
display
(inputplot_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.
Example
//@version=5indicator("plot")
plot(high+low, title='title', color=color.new(#00ffaa, 70), linewidth=2, style=plot.style_area, offset=15, trackprice=true)
// You may fill the background between any two plots with a fill() function:
p1 = plot(open)
p2 = plot(close)
fill(p1, p2, color=color.new(color.green, 90))
#00ffaa, 70), linewidth=2, style=plot.style_area, offset=15, trackprice=true)// You may fill the background between any two plots with a fill() function:p1 = plot(open)p2 = plot(close)fill(p1, p2, color=color.new(color.green, 90))
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.
series of data to be plotted as arrows. Required argument.
title
(conststring)
title of the plot.
colorup
(seriescolor)
color of the up arrows. optional argument.
colordown
(seriescolor)
color of the down arrows. optional argument.
offset
(seriesint)
shifts arrows to the left or to the right on the given number of bars. Default is 0.
minheight
(inputint)
Minimal possible arrow height in pixels. Default is 5.
maxheight
(inputint)
Maximum possible arrow height in pixels. Default is 100.
editable
(constbool)
if true then plotarrow style will be editable in format dialog. Default is true.
show_last
(inputint)
if set, defines the number of arrows (from the last bar back to the past) to plot on chart.
display
(inputplot_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.
Example
//@version=5indicator("plotarrow example", overlay=true)
codiff = close - open
plotarrow(codiff, colorup=color.new(color.teal,40), colordown=color.new(color.orange, 40))
Remarks
use plotarrow function in conjunction with 'overlay=true' indicator parameter!
Open series of data to be used as open values of bars. Required argument.
high
(seriesint/float)
High series of data to be used as high values of bars. Required argument.
low
(seriesint/float)
Low series of data to be used as low values of bars. Required argument.
close
(seriesint/float)
Close series of data to be used as close values of bars. Required argument.
title
(conststring)
title of the plotbar. optional argument.
color
(seriescolor)
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
(constbool)
if true then plotbar style will be editable in format dialog. Default is true.
show_last
(inputint)
if set, defines the number of bars (from the last bar back to the past) to plot on chart.
display
(inputplot_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.
Example
//@version=5indicator("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'.
Open series of data to be used as open values of candles. Required argument.
high
(seriesint/float)
High series of data to be used as high values of candles. Required argument.
low
(seriesint/float)
Low series of data to be used as low values of candles. Required argument.
close
(seriesint/float)
Close series of data to be used as close values of candles. Required argument.
title
(conststring)
title of the plotcandles. optional argument.
color
(seriescolor)
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
(seriescolor)
the color of the wick of candles. an optional argument.
editable
(constbool)
if true then plotcandle style will be editable in format dialog. Default is true.
show_last
(inputint)
if set, defines the number of candles (from the last bar back to the past) to plot on chart.
bordercolor
(seriescolor)
the border color of candles. an optional argument.
display
(inputplot_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.
Example
//@version=5indicator("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'.
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.
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
(seriesint)
shifts shapes to the left or to the right on the given number of bars. Default is 0.
text
(conststring)
Text to display with the shape. You can use multiline text, to separate lines use '\n' escape sequence. Example: 'line one\nline two'.
textcolor
(seriescolor)
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
(constbool)
if true then plotchar style will be editable in format dialog. Default is true.
if set, defines the number of chars (from the last bar back to the past) to plot on chart.
display
(inputplot_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.
Example
//@version=5indicator("plotchar example", overlay=true)
data = close >= open
plotchar(data, char='a,,')
Remarks
use plotchar function in conjunction with 'overlay=true' indicator parameter!
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.
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
(seriesint)
shifts shapes to the left or to the right on the given number of bars. Default is 0.
text
(conststring)
Text to display with the shape. You can use multiline text, to separate lines use '\n' escape sequence. Example: 'line one\nline two'.
textcolor
(seriescolor)
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
(constbool)
if true then plotshape style will be editable in format dialog. Default is true.
if set, defines the number of shapes (from the last bar back to the past) to plot on chart.
display
(inputplot_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.
Example
//@version=5indicator("plotshape example 1", overlay=true)
data = close >= open
plotshape(data, style=shape.xcross)
Remarks
use plotshape function in conjunction with 'overlay=true' indicator parameter!
deletes the specified polyline object. it has no effect if the `id` doesn't exist.
Syntax
polyline.delete(id) - void
Arguments
id
(seriespolyline)
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.
an array of chart.point objects for the drawing to sequentially connect.
curved
(seriesbool)
if true, the drawing will connect all points from the `points` array using curved line segments. optional. the default is false.
closed
(seriesbool)
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
(seriesstring)
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
(seriescolor)
the color of the line segments. optional. the default is color.blue.
fill_color
(seriescolor)
the fill color of the polyline. optional. the default is na.
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.currency_rate(from, to, ignore_invalid_currency) → series float
Arguments
from
(simplestring)
the currency in which the value to be converted is expressed. possible values: a three-letter string with the currency code in the isO 4217 format (e.g. "usD"), or one of the built-in variables that return currency codes, like syminfo.currency or currency.usD.
Determines the behavior of the function if a conversion rate between the two currencies cannot be calculated: if false, the script will halt and return a runtime error; if true, the function will return na and execution will continue. optional. the default is false.
Example
//@version=5indicator("Close in british pounds")
rate = request.currency_rate(syminfo.currency, "Gbp")
plot(close * rate)
Remarks
if `from` and `to` arguments are equal, function returns 1. please note that using this variable/function can cause indicator repainting.
request.dividends
Requests dividends data for the specified symbol.
Syntax
request.dividends(ticker, field, gaps, lookahead, ignore_invalid_symbol, currency) → series float
Arguments
ticker
(simplestring)
symbol. Note that the symbol should be passed with a prefix. For example: "NasDaq:aapL" instead of "aapL". using syminfo.ticker will cause an error. use syminfo.tickerid instead.
Merge strategy for the requested data (requested data automatically merges with the main series OHLC data). possible values: barmerge.gaps_on, barmerge.gaps_off. barmerge.gaps_on - requested data is merged with possible gaps (na values). barmerge.gaps_off - requested data is merged continuously without gaps, all the gaps are filled with the previous nearest existing values. Default value is barmerge.gaps_off.
an optional parameter. Determines the behavior of the function if the specified symbol is not found: if false, the script will halt and return a runtime error; if true, the function will return na and execution will continue. the default value is false.
currency
(simplestring)
Currency into which the symbol's currency-related dividends values (e.g. dividends.gross) are to be converted. the conversion rates used are based on the FX_iDC pairs' daily rates of the previous day (relative to the bar where the calculation is done). optional. the default is syminfo.currency. possible values: a three-letter string with the currency code in the isO 4217 format (e.g. "usD") or one of the constants in the currency.* namespace, e.g. currency.usD.
request.earnings(ticker, field, gaps, lookahead, ignore_invalid_symbol, currency) → series float
Arguments
ticker
(simplestring)
symbol. Note that the symbol should be passed with a prefix. For example: "NasDaq:aapL" instead of "aapL". using syminfo.ticker will cause an error. use syminfo.tickerid instead.
Merge strategy for the requested data (requested data automatically merges with the main series OHLC data). possible values: barmerge.gaps_on, barmerge.gaps_off. barmerge.gaps_on - requested data is merged with possible gaps (na values). barmerge.gaps_off - requested data is merged continuously without gaps, all the gaps are filled with the previous nearest existing values. Default value is barmerge.gaps_off.
an optional parameter. Determines the behavior of the function if the specified symbol is not found: if false, the script will halt and return a runtime error; if true, the function will return na and execution will continue. the default value is false.
currency
(simplestring)
Currency into which the symbol's currency-related earnings values (e.g. earnings.actual) are to be converted. the conversion rates used are based on the FX_iDC pairs' daily rates of the previous day (relative to the bar where the calculation is done). optional. the default is syminfo.currency. possible values: a three-letter string with the currency code in the isO 4217 format (e.g. "usD") or one of the constants in the currency.* namespace, e.g. currency.usD.
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.economic(country_code, field, gaps, ignore_invalid_symbol) → series float
Arguments
country_code
(simplestring)
the code of the country (e.g. "us") or the region (e.g. "Eu") for which the economic data is requested. the Help center article lists the countries and their codes. the countries for which information is available vary with metrics. the Help center article for each metric lists the countries for which the metric is available.
field
(simplestring)
the code of the requested economic metric (e.g., "GDp"). the Help center article lists the metrics and their codes.
gaps
(simplebarmerge_gaps)
specifies how the returned values are merged on chart bars. possible values: barmerge.gaps_off, barmerge.gaps_on. With barmerge.gaps_on, a value only appears on the current chart bar when it first becomes available from the function's context, otherwise na is returned (thus a "gap" occurs). With barmerge.gaps_off, what would otherwise be gaps are filled with the latest known value returned, avoiding na values. optional. the default is barmerge.gaps_off.
ignore\_invalid\_symbol
(inputbool)
Determines the behavior of the function if the specified symbol is not found: if false, the script will halt and return a runtime error; if true, the function will return na and execution will continue. optional. the default is false.
Example
//@version=5indicator("us GDp")
e = request.economic("us", "GDp")
plot(e)
Returns
Requested series.
Remarks
Economic data can also be accessed from charts, just like a regular symbol. use "ECONOMiC" as the exchange name and {country_code}{field} as the ticker. the name of us GDp data is thus "ECONOMiC:usGDp".
request.financial(symbol, financial_id, period, gaps, ignore_invalid_symbol, currency) → series float
Arguments
symbol
(simplestring)
symbol. Note that the symbol should be passed with a prefix. For example: "NasDaq:aapL" instead of "aapL".
financial_id
(simplestring)
Financial identifier. You can find the list of available ids via our Help center.
period
(simplestring)
Reporting period. possible values are "ttM", "FY", "Fq", "FH".
gaps
(simplebarmerge_gaps)
Merge strategy for the requested data (requested data automatically merges with the main series: OHLC data). possible values include: barmerge.gaps_on, barmerge.gaps_off. barmerge.gaps_on - requested data is merged with possible gaps (na values). barmerge.gaps_off - requested data is merged continuously without gaps, all the gaps are filled with the previous, nearest existing values. Default value is barmerge.gaps_off.
ignore\_invalid\_symbol
(inputbool)
an optional parameter. Determines the behavior of the function if the specified symbol is not found: if false, the script will halt and return a runtime error; if true, the function will return na and execution will continue. the default value is false.
currency
(simplestring)
Currency into which the symbol's financial metrics (e.g. Net income) are to be converted. the conversion rates used are based on the FX_iDC pairs' daily rates of the previous day (relative to the bar where the calculation is done). optional. the default is syminfo.currency. possible values: a three-letter string with the currency code in the isO 4217 format (e.g. "usD") or one of the constants in the currency.* namespace, e.g. currency.usD.
Example
//@version=5indicator("request.financial")
f = request.financial("NasDaq:MsFT", "aCCOuNTs_paYabLE", "FY")
plot(f)
request.quandl(ticker, gaps, index, ignore_invalid_symbol) → series float
Arguments
ticker
(simplestring)
symbol. Note that the name of a time series and quandl data feed should be divided by a forward slash. For example: "CFTC/sb_FO_aLL".
gaps
(simplebarmerge_gaps)
Merge strategy for the requested data (requested data automatically merges with the main series: OHLC data). possible values include: barmerge.gaps_on, barmerge.gaps_off. barmerge.gaps_on - requested data is merged with possible gaps (na values). barmerge.gaps_off - requested data is merged continuously without gaps, all the gaps are filled with the previous, nearest existing values. Default value is barmerge.gaps_off.
index
(simpleint)
a quandl time-series column index.
ignore\_invalid\_symbol
(inputbool)
an optional parameter. Determines the behavior of the function if the specified symbol is not found: if false, the script will halt and return a runtime error; if true, the function will return na and execution will continue. the default value is false.
Example
//@version=5indicator("request.quandl")
f = request.quandl("CFTC/sb_FO_aLL", barmerge.gaps_off, 0)
plot(f)
Returns
Requested series.
Remarks
You can learn more about how to find ticker and index values in our Help center.
Requests data from another symbol and/or timeframe.
Syntax
request.security(symbol, timeframe, expression, gaps, lookahead, ignore_invalid_symbol, currency) → series ;
Arguments
symbol
(simplestring)
symbol to request the data from. use syminfo.tickerid to request data from the chart's symbol. To request data with additional parameters (extended sessions, dividend adjustments, or a non-standard chart type like Heikin ashi or Renko), a custom ticker identifier must first be created using functions in the `ticker.*` namespace.
timeframe
(simplestring)
timeframe of the requested data. To use the chart's timeframe, use an empty string or the timeframe.period variable. Valid timeframe strings are documented in the user Manual's timeframes page.
an expression to be calculated and returned from the request.security call's context. it can be a built-in variable like close, an expression such as `ta.sma(close, 100)`, a non-mutable user-defined variable previously calculated in the script, a function call that does not use pine script(r) 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.
gaps
(simplebarmerge_gaps)
specifies how the returned values are merged on chart bars. possible values: barmerge.gaps_on, barmerge.gaps_off. With barmerge.gaps_on a value only appears on the current chart bar when it first becomes available from the function's context, otherwise na is returned (thus a "gap" occurs). With barmerge.gaps_off what would otherwise be gaps are filled with the latest known value returned, avoiding na values. optional. the default is barmerge.gaps_off.
lookahead
(simplebarmerge_lookahead)
On historical bars only, returns data from the timeframe before it elapses. possible values: barmerge.lookahead_on, barmerge.lookahead_off. Has no effect on realtime values. optional. the default is barmerge.lookahead_off starting from pine script(r) v3. the default is barmerge.lookahead_on in v1 and v2. WaRNiNG: using barmerge.lookahead_on at timeframes higher than the chart's without offsetting the `expression` argument like in `close[1]` will introduce future leak in scripts, as the function will then return the `close` price before it is actually known in the current context. as is explained in the user Manual's page on Repainting this will produce misleading results.
ignore\_invalid\_symbol
(inputbool)
Determines the behavior of the function if the specified symbol is not found: if false, the script will halt and throw a runtime error; if true, the function will return na and execution will continue. optional. the default is false.
currency
(simplestring)
Currency into which values expressed in currency units (open, high, low, close, etc.) or expressions using such values are to be converted. the conversion rates used are based on the FX_iDC pairs' daily rates of the previous day (relative to the bar where the calculation is done). possible values: a three-letter string with the currency code in the isO 4217 format (e.g. "usD") or one of the constants in the currency.* namespace, e.g. currency.usD. Note that literal values such as `200` are not converted. optional. the default is syminfo.currency.
Example
//@version=5indicator("simple `request.security()` calls")
// Returns 1D close of the current symbol.
dailyClose = request.security(syminfo.tickerid, "1D", close)
plot(dailyClose)
// 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=5indicator("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 forexecution in the context of the "aapL" symbol at a "240" (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 only returns a value from the higher timeframe on the bar after it completes:
indexHighTF = barstate.isrealtime ? 1 : 0indexCurrtF = barstate.isrealtime ? 0 : 1nonRepaintingClose = 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 = adjustment.dividends)
aaplExtadj = request.security(extendedticker, "60", close)
plot(aaplExtadj)
// Returns the result of a user-defined function.
// the `max` variable is mutable, but we can pass it to `request.security()` because it is wrapped in a function.
alltimeHigh(source) =>
var max = source
max := math.max(max, source)
alltimeHigh1D = request.security(syminfo.tickerid, "1D", alltimeHigh(high))
// by using a tuple `expression`, we obtain several values with only one `request.security()` call.
> [open1D, high1D, low1D, close1D, ema1D] = request.security(syminfo.tickerid, "1D", [open, high, low, 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.get(ohlcarray, 3))
Returns
a result determined by `expression`.
Remarks
pine script(r) 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.
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.
symbol to request the data from. use syminfo.tickerid to request data from the chart's symbol. To request data with additional parameters (extended sessions, dividend adjustments, or a non-standard chart type like Heikin ashi or Renko), a custom ticker identifier must first be created using functions in the `ticker.*` namespace.
timeframe
(simplestring)
timeframe of the requested data. To use the chart's timeframe, use an empty string or the timeframe.period variable. Valid timeframe strings are documented in the user Manual's timeframes page.
an expression to be calculated and returned from the function call's context. it can be a built-in variable like close, an expression such as `ta.sma(close, 100)`, a non-mutable user-defined variable previously calculated in the script, a function call that does not use pine script(r) drawings, arrays or matrices, 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
(constbool)
Determines the behavior of the function if the specified symbol is not found: if false, the script will halt and throw a runtime error; if true, the function will return na and execution will continue. optional. the default is false.
currency
(simplestring)
Currency into which values expressed in currency units (open, high, low, close, etc.) or expressions using such values are to be converted. the conversion rates used are based on the FX_iDC pairs' daily rates of the previous day (relative to the bar where the calculation is done). possible values: a three-letter string with the currency code in the isO 4217 format (e.g. "usD") or one of the constants in the currency.* namespace, e.g. currency.usD. Note that literal values such as `200` are not converted. optional. the default is syminfo.currency.
ignore\_invalid\_timeframe
(constbool)
Determines the behavior of the function when the chart's timeframe is smaller than the `timeframe` used in the function call. if false, the script will halt and throw a runtime error. if true, the function will return na and execution will continue. optional. the default is false.
Example
//@version=5indicator("`request.security_lower_tf()` Example", overlay = true)
// if the current chart timeframe is set to 120 minutes, then the `arrayClose` array will contain two 'close' values from the 60 minute timeframe foreach 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(r) 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.
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) → series ;
Arguments
source
(simplestring)
Name of the Github repository.
symbol
(simplestring)
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(r) 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
(inputbool)
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.
Example
//@version=5indicator("bTC Development activity")
> [devact, devactsMa] = request.seed("seed_crypto_santiment", "bTC_DEV_aCTiViTY", [close, ta.sma(close, 10)])
plot(devact, "bTC Development activity")
plot(devactsMa, "bTC Development activity sMa10", color = color.yellow)
Returns
Requested series or tuple of series, which may include array/matrix iDs.
request.splits
Requests splits data for the specified symbol.
Syntax
request.splits(ticker, field, gaps, lookahead, ignore_invalid_symbol) → series float
Arguments
ticker
(simplestring)
symbol. Note that the symbol should be passed with a prefix. For example: "NasDaq:aapL" instead of "aapL". using syminfo.ticker will cause an error. use syminfo.tickerid instead.
Merge strategy for the requested data (requested data automatically merges with the main series OHLC data). possible values: barmerge.gaps_on, barmerge.gaps_off. barmerge.gaps_on - requested data is merged with possible gaps (na values). barmerge.gaps_off - requested data is merged continuously without gaps, all the gaps are filled with the previous nearest existing values. Default value is barmerge.gaps_off.
an optional parameter. Determines the behavior of the function if the specified symbol is not found: if false, the script will halt and return a runtime error; if true, the function will return na and execution will continue. the default value is false.
//@version=5indicator("str.contains")
// if the current chart is a continuous futures chart, e.g aEURoebTC1!aEUR, 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.
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.
//@version=5indicator("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.3label.new(bar_index, close, text=s1)
// - Round a float value to an integer:
s2 = str.format("{0,number,integer}", 1.34) // returns: 1label.new(bar_index - 1, close, text=s2)
// - Display a number in currency:
s3 = str.format("{0,number,currency}", 1.34) // returns: $1.34label.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 4s5 = str.format("Number {0} is not {1} to {2}", 1, "equal", 4)
label.new(bar_index - 4, close, text=s5)
// returns: 1.34 != 1.3s6 = 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 2s7 = 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.00s8 = 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
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
str.format_time(time, format, timezone) → series string
Arguments
time
(seriesint)
unix time, in milliseconds.
format
(seriesstring)
a format string specifying the date/time representation of the `time` in the returned string. all letters used in the string, except those escaped by single quotation marks ', are considered formatting tokens and will be used as a formatting instruction. Refer to the Remarks section for a list of the most useful tokens. optional. the default is "yyyy-MM-dd'T'HH:mm:ssZ", which represents the isO 8601 standard.
timezone
(seriesstring)
allows adjusting the returned value to a time zone specified in either uTC/GMT notation (e.g., "uTC-5", "GMT+0530") or as an iaNa time zone database name (e.g., "america/New_York"). optional. the default is syminfo.timezone.
the `M`, `d`, `h`, `H`, `m` and `s` tokens can all be doubled to generate leading zeroes. For example, the month of January will display as `1` with `M`, or `01` with `MM`.
the most frequently used formatting tokens are:
y - Year. use \yy\ to output the last two digits of the year or \yyyy\ to output all four. Year 2000 will be `00` with \yy\ or `2000` with \yyyy\.
M - Month. Not to be confused with lowercase `m`, which stands for minute.
d - Day of the month.
a - aM/pM postfix.
h - Hour in the 12-hour format. the last hour of the day will be `11` in this format.
H - Hour in the 24-hour format. the last hour of the day will be `23` in this format.
m - Minute.
s - second.
s - Fractions of a second.
Z - timezone, the HHmm offset from uTC, preceded by either + or -.
str.length
+2 overloads
Returns an integer corresponding to the amount of chars in that string.
the regular expression to which this string is to be matched.
Example
//@version=5indicator("str.match")
s = input.string("it's time to sell some NasDaq:aapL!")
// finding first substring that matches regular expression "[\w]+:[\w]+"var string tickerid = str.match(s, "[\w]+:[\w]+")
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 the`regex` string needs to be escaped with additional backslash, e.g. "\d" stands for regular expression "\d".
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.
Value or array iD whose elements are converted to a string.
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 zeroes.
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.upper
+2 overloads
Returns a new string with all letters converted to uppercase.
the title of the script. it is displayed on the chart when no `shorttitle` argument is used, and becomes the publication's default title when publishing the script.
shorttitle
(conststring)
the script's display name on charts. if specified, it will replace the `title` argument in most chart-related windows. optional. the default is the argument used for `title`.
overlay
(constbool)
if true, the strategy will be displayed over the chart. if false, it will be added in a separate pane. strategy-specific labels that display entries and exits will be displayed over the main chart regardless of this setting. optional. the default is false.
specifies the number of digits after the floating point of the script's displayed values. Must be a non-negative integer no greater than 16. if `format` is set to format.inherit and `precision` is specified, the format will instead be set to format.price. optional. the default is inherited from the precision of the chart's symbol.
scale
(constscale_type)
the price scale used. possible values: scale.right, scale.left, scale.none. the scale.none value can only be applied in combination with `overlay = true`. optional. by default, the script uses the same scale as the chart.
pyramiding
(constint)
the maximum number of entries allowed in the same direction. if the value is 0, only one entry order in the same direction can be opened, and additional entry orders are rejected. this setting can also be changed in the strategy's "settings/properties" tab. optional. the default is 0.
calc\_on\_order_fills
(constbool)
specifies whether the strategy should be recalculated after an order is filled. if true, the strategy recalculates after an order is filled, as opposed to recalculating only when the bar closes. this setting can also be changed in the strategy's "settings/properties" tab. optional. the default is false.
calc\_on\_every_tick
(constbool)
specifies whether the strategy should be recalculated on each realtime tick. if true, when the strategy is running on a realtime bar, it will recalculate on each chart update. if false, the strategy only calculates when the realtime bar closes. the argument used does not affect strategy calculation on historical data. this setting can also be changed in the strategy's "settings/properties" tab. optional. the default is false.
max\_bars\_back
(constint)
the length of the historical buffer the script keeps for every variable and function, which determines how many past values can be referenced using the \[\] history-referencing operator. the required buffer size is automatically detected by the pine script(r) runtime. using this parameter is only necessary when a runtime error occurs because automatic detection fails. More information on the underlying mechanics of the historical buffer can be found in our Help center. optional. the default is 0.
backtest\_fill\_limits_assumption
(constint)
limit order execution threshold in ticks. When it is used, limit orders are only filled if the market price exceeds the order's limit level by the specified number of ticks. optional. the default is 0.
default\_qty\_type
(conststring)
specifies the units used for `default_qty_value`. possible values are: strategy.fixed for contracts/shares/lots, strategy.cash for currency amounts, or strategy.percent_of_equity for a percentage of available equity. this setting can also be changed in the strategy's "settings/properties" tab. optional. the default is strategy.fixed.
default\_qty\_value
(constint/float)
the default quantity to trade, in units determined by the argument used with the `default_qty_type` parameter. this setting can also be changed in the strategy's "settings/properties" tab. optional. the default is 1.
initial_capital
(constint/float)
the amount of funds initially available for the strategy to trade, in units of `currency`. optional. the default is 1000000.
currency
(conststring)
Currency used by the strategy in currency-related calculations. market positions are still opened by converting `currency` into the chart symbol's currency. the conversion rates used are based on the FX_iDC pairs' daily rates of the previous day (relative to the bar where the calculation is done). this setting can also be changed in the strategy's "settings/properties" tab. optional. the default is currency.NONE, in which case the chart's currency is used. possible values: one of the constants in the `currency.*` namespace, e.g. currency.usD.
slippage
(constint)
slippage expressed in ticks. this value is added to or subtracted from the fill price of market/stop orders to make the fill price less favorable for the strategy. E.g., if syminfo.mintick is 0.01 and `slippage` is set to 5, a long market order will enter at 5 * 0.01 = 0.05 points above the actual price. this setting can also be changed in the strategy's "settings/properties" tab. optional. the default is 0.
Commission applied to the strategy's orders in units determined by the argument passed to the `commission_type` parameter. this setting can also be changed in the strategy's "settings/properties" tab. optional. the default is 0.
process\_orders\_on_close
(constbool)
When set to true, generates an additional attempt to execute orders after a bar closes and strategy calculations are completed. if the orders are market orders, the broker emulator executes them before the next bar's open. if the orders are price-dependent, they will only be filled if the price conditions are met. this option is useful if you wish to close positions on the current bar. this setting can also be changed in the strategy's "settings/properties" tab. optional. the default is false.
close\_entries\_rule
(conststring)
Determines the order in which trades are closed. possible values are: "FiFO" (First-in, First-Out) if the earliest exit order must close the earliest entry order, or "aNY" if the orders are closed based on the `from_entry` parameter of the strategy.exit function. "FiFO" can only be used with stocks, futures and us forex (NFa Compliance Rule 2-43b), while "aNY" is allowed in non-us forex. optional. the default is "FiFO".
margin_long
(constint/float)
Margin long is the percentage of the purchase price of a security that must be covered by cash or collateral for long positions. Must be a non-negative number. the logic used to simulate margin calls is explained in the Help center. this setting can also be changed in the strategy's "settings/properties" tab. optional. the default is 0, in which case the strategy does not enforce any limits on position size.
margin_short
(constint/float)
Margin short is the percentage of the purchase price of a security that must be covered by cash or collateral for short positions. Must be a non-negative number. the logic used to simulate margin calls is explained in the Help center. this setting can also be changed in the strategy's "settings/properties" tab. optional. the default is 0, in which case the strategy does not enforce any limits on position size.
explicit\_plot\_zorder
(constbool)
specifies the order in which the script's plots, fills, and hlines are rendered. if true, plots are drawn in the order in which they appear in the script's code, each newer plot being drawn above the previous ones. this only applies to `plot*()` functions, fill, and hline. optional. the default is false.
max\_lines\_count
(constint)
the number of last line drawings displayed. possible values: 1-500. optional. the default is 50.
max\_labels\_count
(constint)
the number of last label drawings displayed. possible values: 1-500. optional. the default is 50.
max\_boxes\_count
(constint)
the number of last box drawings displayed. possible values: 1-500. optional. the default is 50.
risk\_free\_rate
(constint/float)
the risk-free rate of return is the annual percentage change in the value of an investment with minimal or zero risk. it is used to calculate the sharpe and sortino ratios. optional. the default is 2.
use\_bar\_magnifier
(constbool)
When true, the broker emulator uses lower timeframe data during history backtesting to achieve more realistic results. optional. the default is false. Only premium accounts have access to this feature.
max\_polylines\_count
(constint)
the number of last polyline drawings displayed. possible values: 1-100. the count is approximate; more drawings than the specified count may be displayed. optional. the default is 50.
Example
//@version=5strategy("My strategy", overlay = true, margin_long = 100, margin_short = 100)
// Enter long by market if current open is greater than previous high.
if open > high[1]
strategy.entry("Long", strategy.long, 1)
// Generate a full exit bracket (profit 10 points, loss 5 points per contract) from the entry named "Long".
strategy.exit("Exit", "Long", profit = 10, loss = 5)
Remarks
You can learn more about strategies in our user Manual.
Every strategy script must have one strategy call.
strategies using `calc_on_every_tick = true` parameter may calculate differently on historical and realtime bars, which causes repainting.
strategies always use the chart's prices to enter and exit positions. using them on non-standard chart types (Heikin ashi, Renko, etc.) will produce misleading results, as their prices are synthetic. backtesting on non-standard charts is thus not recommended.
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
(seriesstring)
a required parameter. the order identifier. it is possible to cancel an order by referencing its identifier.
Example
//@version=5strategy(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
ifnot 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=5strategy(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 conditionForbuy1 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(id, comment, qty, qty_percent, alert_message, immediately, disable_alert) → void
### Arguments
- `id`
> (`series` `string`)
> a required parameter. the order identifier. it is possible to close an order by referencing its identifier.
- `comment`
> (`series` `string`)
> an optional parameter. additional notes on the order.
- `qty`
> (`series` `int`/`float`)
> an optional parameter. Number of contracts/shares/lots/units to exit a trade with. the default value is 'NaN'.
- `qty_percent`
> (`series` `int`/`float`)
> Defines the percentage (0-100) of the position to close. its priority is lower than that of the 'qty' parameter. optional. the default is 100.
- `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.
- `immediately`
> (`series` `bool`)
> an optional parameter. if true, the closing order will be executed on the tick where it has been placed, ignoring the strategy parameters that restrict the order execution to the open of the next bar. the default is false.
- `disable_alert`
> (`series` `bool`)
> if true when the function creates an order, the strategy alert will not fire upon the execution of that order. the parameter accepts a 'series bool' argument, allowing users to control which orders will trigger alerts when they fill. optional. the default is false.
### Example
//@version=5strategy("closeEntry Demo", overlay=false)
if open > close
strategy.entry("buy", strategy.long)
if open < close
strategy.close("buy", qty_percent = 50, comment = "close buy entry for 50%")
plot(strategy.position_size)
strategy.close_all
+1 overload
Exits the current market position, making it flat.
an optional parameter. additional notes on the order.
alert_message
(seriesstring)
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=5strategy("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.closedtrades.commission(trade_num) → series float
Arguments
trade_num
(seriesint)
the trade number of the closed trade. the number of the first trade is zero.
Example
//@version=5strategy("`strategy.closedtrades.commission` Example", commission_type = strategy.commission.percent, commission_value = 0.1)
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// plot total fees forthe latest closed trade.
plot(strategy.closedtrades.commission(strategy.closedtrades - 1))
Returns the bar_index of the closed trade's entry.
Syntax
strategy.closedtrades.entry_bar_index(trade_num) → series int
Arguments
trade_num
(seriesint)
the trade number of the closed trade. the number of the first trade is zero.
Example
//@version=5strategy("strategy.closedtrades.entry_bar_index Example")
// Enter long trades on three rising bars; exit on two falling bars.if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Function that calculates the average amount of bars in a trade.
avgbarspertrade() =>
sumbarspertrade = 0fortradeNo = 0 to strategy.closedtrades - 1
// Loop through all closed trades, starting with the oldest.
sumbarspertrade += strategy.closedtrades.exit_bar_index(tradeNo) - strategy.closedtrades.entry_bar_index(tradeNo) + 1
result = nz(sumbarspertrade / strategy.closedtrades)
plot(avgbarspertrade())
strategy.closedtrades.entry_id(trade_num) → series string
Arguments
trade_num
(seriesint)
the trade number of the closed trade. the number of the first trade is zero.
Example
//@version=5strategy("strategy.closedtrades.entry_id Example", overlay = true)
// Enter a short position and close at the previous to last bar.
if bar_index == 1
strategy.entry("short at bar #" + str.tostring(bar_index), strategy.short)
if bar_index == last_bar_index - 2
strategy.close_all()
// Display iD of the last entry position.
if barstate.islastconfirmedhistory
label.new(last_bar_index, high, "Last Entry iD is: " + strategy.closedtrades.entry_id(strategy.closedtrades - 1))
#" + str.tostring(bar_index), strategy.short)if bar_index == last_bar_index - 2 strategy.close_all() // Display iD of the last entry position.if barstate.islastconfirmedhistory label.new(last_bar_index, high, "Last Entry iD is: " + strategy.closedtrades.entry_id(strategy.closedtrades - 1))
Returns
Returns the id of the closed trade's entry.
Remarks
the function returns na if trade_num is not in the range: 0 to strategy.closedtrades-1.
strategy.closedtrades.entry_price(trade_num) → series float
Arguments
trade_num
(seriesint)
the trade number of the closed trade. the number of the first trade is zero.
Example
//@version=5strategy("strategy.closedtrades.entry_price Example 1")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Return the entry price forthe latest entry.
entryprice = strategy.closedtrades.entry_price(strategy.closedtrades - 1)
plot(entryprice, "Long entry price")
Example
// Calculates the average profit percentage for all closed trades.
//@version=5
strategy("strategy.closedtrades.entry_price Example 2")
// strategy calls to create single short and long trades
if bar_index == last_bar_index - 15
strategy.entry("Long Entry", strategy.long)
else if bar_index == last_bar_index - 10
strategy.close("Long Entry")
strategy.entry("short", strategy.short)
else if bar_index == last_bar_index - 5
strategy.close("short")
// Calculate profit for both closed trades.
profitpct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
entryp = strategy.closedtrades.entry_price(tradeNo)
exitp = strategy.closedtrades.exit_price(tradeNo)
profitpct += (exitp - entryp) / entryp * strategy.closedtrades.size(tradeNo) * 100
// Calculate average profit percent for both closed trades.
avgprofitpct = nz(profitpct / strategy.closedtrades)
plot(avgprofitpct)
Returns the unix time of the closed trade's entry.
Syntax
strategy.closedtrades.entry_time(trade_num) → series int
Arguments
trade_num
(seriesint)
the trade number of the closed trade. the number of the first trade is zero.
Example
//@version=5strategy("strategy.closedtrades.entry_time Example", overlay = true)
// 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")
// Calculate the average trade duration
avgtradeDuration() =>
sumtradeDuration = 0fori = 0 to strategy.closedtrades - 1
sumtradeDuration += strategy.closedtrades.exit_time(i) - strategy.closedtrades.entry_time(i)
result = nz(sumtradeDuration / strategy.closedtrades)
// 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")
strategy.closedtrades.exit_bar_index(trade_num) → series int
Arguments
trade_num
(seriesint)
the trade number of the closed trade. the number of the first trade is zero.
Example
//@version=5strategy("strategy.closedtrades.exit_bar_index Example 1")
// 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")
// Calculate the amount of bars since the last closed trade.
barssinceClosed = strategy.closedtrades > 0 ? bar_index - strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1) : na
plot(barssinceClosed, "bars since last closed trade")
Example
// Calculates the average amount of bars per trade.
//@version=5
strategy("strategy.closedtrades.exit_bar_index Example 2")
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Function that calculates the average amount of bars per trade.
avgbarspertrade() =>
sumbarspertrade = 0
for tradeNo = 0 to strategy.closedtrades - 1
// Loop through all closed trades, starting with the oldest.
sumbarspertrade += strategy.closedtrades.exit_bar_index(tradeNo) - strategy.closedtrades.entry_bar_index(tradeNo) + 1
result = nz(sumbarspertrade / strategy.closedtrades)
plot(avgbarspertrade())
strategy.closedtrades.exit_id(trade_num) → series string
Arguments
trade_num
(seriesint)
the trade number of the closed trade. the number of the first trade is zero.
Example
//@version=5strategy("strategy.closedtrades.exit_id Example", overlay = true)
// strategy calls to create single short and long trades
if bar_index == last_bar_index - 15
strategy.entry("Long Entry", strategy.long)
else if bar_index == last_bar_index - 10
strategy.entry("short Entry", strategy.short)
// 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)
possign = strategy.opentrades.size(strategy.opentrades - 1)
strategy.exit(possign > 0 ? "sL Long Exit" : "sL short Exit", strategy.opentrades.entry_id(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)
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.
strategy.closedtrades.exit_price(trade_num) → series float
Arguments
trade_num
(seriesint)
the trade number of the closed trade. the number of the first trade is zero.
Example
//@version=5strategy("strategy.closedtrades.exit_price Example 1")
// We are creating a long trade every 5 bars
if bar_index % 5 == 0
strategy.entry("Long", strategy.long)
strategy.close("Long")
// Return the exit price from the latest closed trade.
exitprice = strategy.closedtrades.exit_price(strategy.closedtrades - 1)
plot(exitprice, "Long exit price")
Example
// Calculates the average profit percentage for all closed trades.
//@version=5
strategy("strategy.closedtrades.exit_price Example 2")
// strategy calls to create single short and long trades.
if bar_index == last_bar_index - 15
strategy.entry("Long Entry", strategy.long)
else if bar_index == last_bar_index - 10
strategy.close("Long Entry")
strategy.entry("short", strategy.short)
else if bar_index == last_bar_index - 5
strategy.close("short")
// Calculate profit for both closed trades.
profitpct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
entryp = strategy.closedtrades.entry_price(tradeNo)
exitp = strategy.closedtrades.exit_price(tradeNo)
profitpct += (exitp - entryp) / entryp * strategy.closedtrades.size(tradeNo) * 100
// Calculate average profit percent for both closed trades.
avgprofitpct = nz(profitpct / strategy.closedtrades)
plot(avgprofitpct)
strategy.closedtrades.exit_time(trade_num) → series int
Arguments
trade_num
(seriesint)
the trade number of the closed trade. the number of the first trade is zero.
Example
//@version=5strategy("strategy.closedtrades.exit_time Example 1")
// 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")
// Calculate the average trade duration.
avgtradeDuration() =>
sumtradeDuration = 0fori = 0 to strategy.closedtrades - 1
sumtradeDuration += strategy.closedtrades.exit_time(i) - strategy.closedtrades.entry_time(i)
result = nz(sumtradeDuration / strategy.closedtrades)
// 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")
#.##") + " seconds")
Example
// Reopens a closed trade after X seconds.
//@version=5
strategy("strategy.closedtrades.exit_time Example 2")
// strategy calls to emulate a single long trade at the first bar.
if bar_index == 0
strategy.entry("Long", strategy.long)
reopenpositionafter(timesec) =>
if strategy.closedtrades > 0
if time - strategy.closedtrades.exit_time(strategy.closedtrades - 1) >= timesec * 1000
strategy.entry("Long", strategy.long)
// Reopen last closed position after 120 sec.
reopenpositionafter(120)
if ta.change(strategy.opentrades)
strategy.exit("Long", stop = low * 0.9, profit = high * 2.5)
Returns the maximum drawdown of the closed trade, i.e., the maximum possible loss during the trade, expressed in strategy.account_currency.
Syntax
strategy.closedtrades.max_drawdown(trade_num) → series float
Arguments
trade_num
(seriesint)
the trade number of the closed trade. the number of the first trade is zero.
Example
//@version=5strategy("`strategy.closedtrades.max_drawdown` Example")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Get the biggest max trade drawdown value from all of the closed trades.
maxtradeDrawDown() =>
maxDrawdown = 0.0fortradeNo = 0 to strategy.closedtrades - 1
maxDrawdown := math.max(maxDrawdown, strategy.closedtrades.max_drawdown(tradeNo))
result = maxDrawdown
plot(maxtradeDrawDown(), "biggest max drawdown")
Remarks
the function returns na if trade_num is not in the range: 0 to strategy.closedtrades - 1.
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.closedtrades.max_runup(trade_num) → series float
Arguments
trade_num
(seriesint)
the trade number of the closed trade. the number of the first trade is zero.
Example
//@version=5strategy("`strategy.closedtrades.max_runup` Example")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Get the biggest max trade runup value from all of the closed trades.
maxtradeRunup() =>
maxRunup = 0.0fortradeNo = 0 to strategy.closedtrades - 1
maxRunup := math.max(maxRunup, strategy.closedtrades.max_runup(tradeNo))
result = maxRunup
plot(maxtradeRunup(), "Max trade runup")
Returns the profit/loss of the closed trade. Losses are expressed as negative values.
Syntax
strategy.closedtrades.profit(trade_num) → series float
Arguments
trade_num
(seriesint)
the trade number of the closed trade. the number of the first trade is zero.
Example
//@version=5strategy("`strategy.closedtrades.profit` Example")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate average gross profit by adding the difference between gross profit and commission.
avgGrossprofit() =>
sumGrossprofit = 0.0fortradeNo = 0 to strategy.closedtrades - 1
sumGrossprofit += strategy.closedtrades.profit(tradeNo) - strategy.closedtrades.commission(tradeNo)
result = nz(sumGrossprofit / strategy.closedtrades)
plot(avgGrossprofit(), "average gross profit")
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
strategy.closedtrades.size(trade_num) → series float
Arguments
trade_num
(seriesint)
the trade number of the closed trade. the number of the first trade is zero.
Example
//@version=5strategy("`strategy.closedtrades.size` Example 1")
// We calculate the max amt of shares we can buy.
amtshares = math.floor(strategy.equity / close)
// 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, qty = amtshares)
if bar_index % 20 == 0
strategy.close("Long")
// plot the number of contracts traded in the last closed trade.
plot(strategy.closedtrades.size(strategy.closedtrades - 1), "Number of contracts traded")
Example
// Calculates the average profit percentage for all closed trades.
//@version=5
strategy("`strategy.closedtrades.size` Example 2")
// 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 profit for both closed trades.
profitpct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
entryp = strategy.closedtrades.entry_price(tradeNo)
exitp = strategy.closedtrades.exit_price(tradeNo)
profitpct += (exitp - entryp) / entryp * strategy.closedtrades.size(tradeNo) * 100
// Calculate average profit percent for both closed trades.
avgprofitpct = nz(profitpct / strategy.closedtrades)
plot(avgprofitpct)
//@version=5strategy("`strategy.convert_to_symbol` Example", currency = currency.EuR)
// Calculate the max qty we can buy using current chart's currency.
calcContracts(accountMoney) =>
math.floor(strategy.convert_to_symbol(accountMoney) / syminfo.pointvalue / close)
// Return max qty we can buy using 300 euros
qt = calcContracts(300)
// 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")
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
strategy.default_entry_qty(fill_price) → series float
Arguments
fill_price
(seriesint/float)
the fill price for which to calculate the default order quantity.
Example
//@version=5strategy("supertrend strategy", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 15)
//@variable the length of the atr calculation.
atrperiod = input(10, "atr Length")
//@variable the atr multiplier.
factor = input.float(3.0, "Factor", step = 0.01)
//@variable the tick offset of the stop order.
stopOffsetinput = input.int(100, "Tick offset for entry stop")
// Get the direction of the supertrend.
> [_, direction] = ta.supertrend(factor, atrperiod)
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 reflect 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}Expected qty at {0}: {1}", math.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.
a required parameter. the order identifier. it is possible to cancel or modify an order by referencing its identifier.
direction
(seriesstrategy_direction)
a required parameter. market position direction: 'strategy.long' is for long, 'strategy.short' is for short.
qty
(seriesint/float)
an optional parameter. Number of contracts/shares/lots/units to trade. the default value is 'NaN'.
limit
(seriesint/float)
an optional parameter. limit price of the order. if it is specified, the order type is either 'limit', or 'stop-limit'. 'NaN' should be specified for any other order type.
stop
(seriesint/float)
an optional parameter. stop price of the order. if it is specified, the order type is either 'stop', or 'stop-limit'. 'NaN' should be specified for any other order type.
oca_name
(seriesstring)
an optional parameter. Name of the OCa group the order belongs to. if the order should not belong to any particular OCa group, there should be an empty string.
oca_type
(inputstring)
an optional parameter. Type of the OCa group. the allowed values are: strategy.oca.none - the order should not belong to any particular OCa group; strategy.oca.cancel - the order should belong to an OCa group, where as soon as an order is filled, all other orders of the same group are cancelled; strategy.oca.reduce - the order should belong to an OCa group, where if X number of contracts of an order is filled, number of contracts for each other order of the same OCa group is decreased by X.
comment
(seriesstring)
an optional parameter. additional notes on the order.
alert_message
(seriesstring)
an optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create alert" dialog box's "Message" field.
disable_alert
(seriesbool)
if true when the function creates an order, the strategy alert will not fire upon the execution of that order. the parameter accepts a 'series bool' argument, allowing users to control which orders will trigger alerts when they fill. optional. the default is false.
Example
//@version=5strategy(title = "simple strategy entry example")
if open > high[1]
strategy.entry("enter long", strategy.long, 1) // enter long by market if current open great then previous high
if open < low[1]
strategy.entry("enter short", strategy.short, 1) // enter short by market if current open less then previous low
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.
a required parameter. the order identifier. it is possible to cancel or modify an order by referencing its identifier.
from_entry
(seriesstring)
an optional parameter. the identifier of a specific entry order to exit from it. To exit all entries an empty string should be used. the default values is empty string.
qty
(seriesint/float)
an optional parameter. Number of contracts/shares/lots/units to exit a trade with. the default value is 'NaN'.
qty_percent
(seriesint/float)
Defines the percentage of (0-100) the position to close. its priority is lower than that of the 'qty' parameter. optional. the default is 100.
profit
(seriesint/float)
an optional parameter. profit target (specified in ticks). if it is specified, a limit order is placed to exit market position when the specified amount of profit (in ticks) is reached. the default value is 'NaN'.
limit
(seriesint/float)
an optional parameter. profit target (requires a specific price). if it is specified, a limit order is placed to exit market position at the specified price (or better). priority of the parameter 'limit' is higher than priority of the parameter 'profit' ('limit' is used instead of 'profit', if its value is not 'NaN'). the default value is 'NaN'.
loss
(seriesint/float)
an optional parameter. stop loss (specified in ticks). if it is specified, a stop order is placed to exit market position when the specified amount of loss (in ticks) is reached. the default value is 'NaN'.
stop
(seriesint/float)
an optional parameter. stop loss (requires a specific price). if it is specified, a stop order is placed to exit market position at the specified price (or worse). priority of the parameter 'stop' is higher than priority of the parameter 'loss' ('stop' is used instead of 'loss', if its value is not 'NaN'). the default value is 'NaN'.
trail_price
(seriesint/float)
an optional parameter. trailing stop activation level (requires a specific price). if it is specified, a trailing stop order will be placed when the specified price level is reached. the offset (in ticks) to determine initial price of the trailing stop order is specified in the 'trail_offset' parameter: X ticks lower than activation level to exit long position; X ticks higher than activation level to exit short position. the default value is 'NaN'.
trail_points
(seriesint/float)
an optional parameter. trailing stop activation level (profit specified in ticks). if it is specified, a trailing stop order will be placed when the calculated price level (specified amount of profit) is reached. the offset (in ticks) to determine initial price of the trailing stop order is specified in the 'trail_offset' parameter: X ticks lower than activation level to exit long position; X ticks higher than activation level to exit short position. the default value is 'NaN'.
trail_offset
(seriesint/float)
an optional parameter. trailing stop price (specified in ticks). the offset in ticks to determine initial price of the trailing stop order: X ticks lower than 'trail_price' or 'trail_points' to exit long position; X ticks higher than 'trail_price' or 'trail_points' to exit short position. the default value is 'NaN'.
oca_name
(seriesstring)
an optional parameter. Name of the OCa group (oca_type = strategy.oca.reduce) the profit target, the stop loss / the trailing stop orders belong to. if the name is not specified, it will be generated automatically.
comment
(seriesstring)
additional notes on the order. if specified, displays near the order marker on the chart. optional. the default is na.
comment_profit
(seriesstring)
additional notes on the order if the exit was triggered by crossing profit or limit specifically. if specified, supercedes the comment parameter and displays near the order marker on the chart. optional. the default is na.
comment_loss
(seriesstring)
additional notes on the order if the exit was triggered by crossing stop or loss specifically. if specified, supercedes the comment parameter and displays near the order marker on the chart. optional. the default is na.
comment_trailing
(seriesstring)
additional notes on the order if the exit was triggered by crossing trail_offset specifically. if specified, supercedes the comment parameter and displays near the order marker on the chart. optional. the default is na.
alert_message
(seriesstring)
Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create alert" dialog. optional. the default is na.
alert_profit
(seriesstring)
Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create alert" dialog. Only replaces the text if the exit was triggered by crossing profit or limit specifically. optional. the default is na.
alert_loss
(seriesstring)
Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create alert" dialog. Only replaces the text if the exit was triggered by crossing stop or loss specifically. optional. the default is na.
alert_trailing
(seriesstring)
Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create alert" dialog. Only replaces the text if the exit was triggered by crossing trail_offset specifically. optional. the default is na.
disable_alert
(seriesbool)
if true when the function creates an order, the strategy alert will not fire upon the execution of that order. the parameter accepts a 'series bool' argument, allowing users to control which orders will trigger alerts when they fill. optional. the default is false.
Example
//@version=5strategy(title = "simple strategy exit example")
if open > high[1]
strategy.entry("long", strategy.long, 1) // enter long by market if current open great then previous high
strategy.exit("exit", "long", profit = 10, loss = 5) // generate full exit bracket (profit 10 points, loss 5 points per contract) from entry with name "long"
strategy.opentrades.commission
Returns the sum of entry and exit fees paid in the open trade, expressed in strategy.account_currency.
Syntax
strategy.opentrades.commission(trade_num) → series float
Arguments
trade_num
(seriesint)
the trade number of the open trade. the number of the first trade is zero.
Example
// Calculates the gross profit or loss for the current open position.
//@version=5
strategy("`strategy.opentrades.commission` Example", commission_type = strategy.commission.percent, commission_value = 0.1)
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate gross profit or loss for open positions only.
tradeOpenGrosspL() =>
sumOpenGrosspL = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumOpenGrosspL += strategy.opentrades.profit(tradeNo) - strategy.opentrades.commission(tradeNo)
result = sumOpenGrosspL
plot(tradeOpenGrosspL())
strategy.opentrades.entry_bar_index(trade_num) → series int
Arguments
trade_num
(seriesint)
the trade number of the open trade. the number of the first trade is zero.
Example
// Wait 10 bars and then close the position.
//@version=5
strategy("`strategy.opentrades.entry_bar_index` Example")
barssinceLastEntry() =>
strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) : na
// Enter a long position if there are no open positions.
if strategy.opentrades == 0
strategy.entry("Long", strategy.long)
// Close the long position after 10 bars.
if barssinceLastEntry() >= 10
strategy.close("Long")
strategy.opentrades.entry_id(trade_num) → series string
Arguments
trade_num
(seriesint)
the trade number of the open trade. the number of the first trade is zero.
Example
//@version=5strategy("`strategy.opentrades.entry_id` Example", overlay = true)
// We enter a long position when 14 period sma crosses over 28 period sma.
// We enter a short position when 14 period sma crosses under 28 period sma.
longCondition = 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)
// Display iD of the latest open position.
if barstate.islastconfirmedhistory
label.new(bar_index, high + (2* ta.tr), "Last opened position is" + strategy.opentrades.entry_id(strategy.opentrades - 1))
#" + str.tostring(bar_index), strategy.long)if shortcondition strategy.entry("short entry at bar #" + str.tostring(bar_index), strategy.short)// Display iD of the latest open position.if barstate.islastconfirmedhistory label.new(bar_index, high + (2 * ta.tr), "Last opened position is
" + strategy.opentrades.entry_id(strategy.opentrades - 1))
Returns
Returns the id of the open trade's entry.
Remarks
the function returns na if trade_num is not in the range: 0 to strategy.opentrades-1.
strategy.opentrades.entry_price(trade_num) → series float
Arguments
trade_num
(seriesint)
the trade number of the open trade. the number of the first trade is zero.
Example
//@version=5strategy("strategy.opentrades.entry_price Example 1", overlay = true)
// 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)
// Return the entry price forthe latest closed trade.
currEntryprice = strategy.opentrades.entry_price(strategy.opentrades - 1)
currExitprice = currEntryprice * 1.05if high >= currExitprice
strategy.close("Long")
plot(currEntryprice, "Long entry price", style = plot.style_linebr)
plot(currExitprice, "Long exit price", color.green, style = plot.style_linebr)
Example
// Calculates the average price for the open position.
//@version=5
strategy("strategy.opentrades.entry_price Example 2", pyramiding = 2)
// 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")
// Calculates the average price for the open position.
avgOpenpositionprice() =>
sumOpenpositionprice = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumOpenpositionprice += strategy.opentrades.entry_price(tradeNo) * strategy.opentrades.size(tradeNo) / strategy.position_size
result = nz(sumOpenpositionprice / strategy.opentrades)
plot(avgOpenpositionprice())
strategy.opentrades.entry_time(trade_num) → series int
Arguments
trade_num
(seriesint)
the trade number of the open trade. the number of the first trade is zero.
Example
//@version=5strategy("strategy.opentrades.entry_time Example")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculates duration in milliseconds since the last position was opened.
timesinceLastEntry()=>
strategy.opentrades > 0 ? (time - strategy.opentrades.entry_time(strategy.opentrades - 1)) : na
plot(timesinceLastEntry() / 1000* 60 * 60 * 24, "Days since last entry")
Returns the maximum drawdown of the open trade, i.e., the maximum possible loss during the trade, expressed in strategy.account_currency.
Syntax
strategy.opentrades.max_drawdown(trade_num) → series float
Arguments
trade_num
(seriesint)
the trade number of the open trade. the number of the first trade is zero.
Example
//@version=5strategy("strategy.opentrades.max_drawdown Example 1")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// plot the max drawdown of the latest open trade.
plot(strategy.opentrades.max_drawdown(strategy.opentrades - 1), "Max drawdown of the latest open trade")
Example
// Calculates the max trade drawdown value for all open trades.
//@version=5
strategy("`strategy.opentrades.max_drawdown` Example 2", pyramiding = 100)
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
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
plot(maxtradeDrawDown(), "biggest max drawdown")
Remarks
the function returns na if trade_num is not in the range: 0 to strategy.closedtrades - 1.
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.opentrades.max_runup(trade_num) → series float
Arguments
trade_num
(seriesint)
the trade number of the open trade. the number of the first trade is zero.
Example
//@version=5strategy("strategy.opentrades.max_runup Example 1")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// plot the max runup of the latest open trade.
plot(strategy.opentrades.max_runup(strategy.opentrades - 1), "Max runup of the latest open trade")
Example
// Calculates the max trade runup value for all open trades.
//@version=5
strategy("strategy.opentrades.max_runup Example 2", pyramiding = 100)
// Enter a long position every 30 bars.
if bar_index % 30 == 0
strategy.entry("Long", strategy.long)
// Calculate biggest max trade runup value from all of the open trades.
maxOpentradeRunup() =>
maxRunup = 0.0
for tradeNo = 0 to strategy.opentrades - 1
maxRunup := math.max(maxRunup, strategy.opentrades.max_runup(tradeNo))
result = maxRunup
plot(maxOpentradeRunup(), "biggest max runup of all open trades")
Returns the profit/loss of the open trade, expressed in strategy.account_currency. Losses are expressed as negative values.
Syntax
strategy.opentrades.profit(trade_num) → series float
Arguments
trade_num
(seriesint)
the trade number of the open trade. the number of the first trade is zero.
Example
// Returns the profit of the last open trade.
//@version=5
strategy("`strategy.opentrades.profit` Example 1", commission_type = strategy.commission.percent, commission_value = 0.1)
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
plot(strategy.opentrades.profit(strategy.opentrades - 1), "profit of the latest open trade")
Example
// Calculates the profit for all open trades.
//@version=5
strategy("`strategy.opentrades.profit` Example 2", pyramiding = 5)
// strategy calls to enter 5 long positions every 2 bars.
if bar_index % 2 == 0
strategy.entry("Long", strategy.long, qty = 5)
// Calculate open profit or loss for the open positions.
tradeOpenpL() =>
sumprofit = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumprofit += strategy.opentrades.profit(tradeNo)
result = sumprofit
plot(tradeOpenpL(), "profit of all open trades")
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.opentrades.size(trade_num) → series float
Arguments
trade_num
(seriesint)
the trade number of the open trade. the number of the first trade is zero.
Example
//@version=5strategy("`strategy.opentrades.size` Example 1")
// We calculate the max amt of shares we can buy.
amtshares = math.floor(strategy.equity / close)
// 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, qty = amtshares)
if bar_index % 20 == 0
strategy.close("Long")
// plot the number of contracts in the latest open trade.
plot(strategy.opentrades.size(strategy.opentrades - 1), "amount of contracts in latest open trade")
Example
// Calculates the average profit percentage for all open trades.
//@version=5
strategy("`strategy.opentrades.size` Example 2")
// 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 profit for all open trades.
profitpct = 0.0
for tradeNo = 0 to strategy.opentrades - 1
entryp = strategy.opentrades.entry_price(tradeNo)
exitp = close
profitpct += (exitp - entryp) / entryp * strategy.opentrades.size(tradeNo) * 100
// Calculate average profit percent for all open trades.
avgprofitpct = nz(profitpct / strategy.opentrades)
plot(avgprofitpct)
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.
a required parameter. the order identifier. it is possible to cancel or modify an order by referencing its identifier.
direction
(seriesstrategy_direction)
a required parameter. Order direction: 'strategy.long' is for buy, 'strategy.short' is for sell.
qty
(seriesint/float)
an optional parameter. Number of contracts/shares/lots/units to trade. the default value is 'NaN'.
limit
(seriesint/float)
an optional parameter. limit price of the order. if it is specified, the order type is either 'limit', or 'stop-limit'. 'NaN' should be specified for any other order type.
stop
(seriesint/float)
an optional parameter. stop price of the order. if it is specified, the order type is either 'stop', or 'stop-limit'. 'NaN' should be specified for any other order type.
oca_name
(seriesstring)
an optional parameter. Name of the OCa group the order belongs to. if the order should not belong to any particular OCa group, there should be an empty string.
oca_type
(inputstring)
an optional parameter. Type of the OCa group. the allowed values are: strategy.oca.none - the order should not belong to any particular OCa group; strategy.oca.cancel - the order should belong to an OCa group, where as soon as an order is filled, all other orders of the same group are cancelled; strategy.oca.reduce - the order should belong to an OCa group, where if X number of contracts of an order is filled, number of contracts for each other order of the same OCa group is decreased by X.
comment
(seriesstring)
an optional parameter. additional notes on the order.
alert_message
(seriesstring)
an optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create alert" dialog box's "Message" field.
disable_alert
(seriesbool)
if true when the function creates an order, the strategy alert will not fire upon the execution of that order. the parameter accepts a 'series bool' argument, allowing users to control which orders will trigger alerts when they fill. optional. the default is false.
Example
//@version=5strategy(title = "simple strategy order example")
if open > high[1]
strategy.order("buy", strategy.long, 1) // buy by market if current open great then previous high
if open < low[1]
strategy.order("sell", strategy.short, 1) // sell by market if current open less then previous low
## 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=5strategy("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 entries.
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.
a required parameter. the allowed number of consecutive days with losses.
alert_message
(simplestring)
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=5strategy("risk.max_cons_loss_days Demo 1")
strategy.risk.max_cons_loss_days(3) // No orders will be placed after 3 days, if each day is with loss.
plot(strategy.position_size)
strategy.risk.max_drawdown
the purpose of this rule is to determine maximum drawdown. the rule affects the whole strategy. Once the maximum drawdown value is reached, all pending orders are cancelled, all open positions are closed and no new orders can be placed.
a required parameter. the maximum drawdown value. it is specified either in money (base currency), or in percentage of maximum equity. For % of equity the range of allowed values is from 0 to 100.
type
(simplestring)
a required parameter. the type of the value. please specify one of the following values: strategy.percent_of_equity or strategy.cash. Note: if equity drops down to zero or to a negative and the 'strategy.percent_of_equity' is specified, all pending orders are cancelled, all open positions are closed and no new orders can be placed for good.
alert_message
(simplestring)
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=5strategy("risk.max_drawdown Demo 1")
strategy.risk.max_drawdown(50, strategy.percent_of_equity) // set maximum drawdown to 50% of maximum equity
plot(strategy.position_size)
Example
//@version=5strategy("risk.max_drawdown Demo 2", currency = "EuR")
strategy.risk.max_drawdown(2000, strategy.cash) // set maximum drawdown to 2000 EuR from maximum equity
plot(strategy.position_size)
strategy.risk.max_intraday_filled_orders
the purpose of this rule is to determine maximum number of filled orders per 1 day (per 1 bar, if chart resolution is higher than 1 day). the rule affects the whole strategy. Once the maximum number of filled orders is reached, all pending orders are cancelled, all open positions are closed and no new orders can be placed till the end of the current trading session.
a required parameter. the maximum number of filled orders per 1 day.
alert_message
(simplestring)
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=5strategy("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 fora market order to exit current open market position, if there 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).
a required parameter. the maximum loss value. it is specified either in money (base currency), or in percentage of maximum intraday equity. For % of equity the range of allowed values is from 0 to 100.
type
(simplestring)
a required parameter. the type of the value. please specify one of the following values: strategy.percent_of_equity or strategy.cash. Note: if equity drops down to zero or to a negative and the strategy.percent_of_equity is specified, all pending orders are cancelled, all open positions are closed and no new orders can be placed for good.
alert_message
(simplestring)
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
// sets the maximum intraday loss using the strategy's equity value.
//@version=5
strategy("strategy.risk.max_intraday_loss Example 1", overlay = false, default_qty_type = strategy.percent_of_equity, default_qty_value = 100)
// input for maximum intraday loss %.
losspct = input.float(10)
// set maximum intraday loss to our losspct input
strategy.risk.max_intraday_loss(losspct, strategy.percent_of_equity)
// Enter short at bar_index zero.
if bar_index == 0
strategy.entry("short", strategy.short)
// store equity value from the beginning of the day
eqFromDaystart = ta.valuewhen(ta.change(dayofweek) > 0, strategy.equity, 0)
// 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)
// set maximum intraday loss to `absCashLoss` in account currency.
strategy.risk.max_intraday_loss(absCashLoss, strategy.cash)
// Enter short at bar_index zero.
if bar_index == 0
strategy.entry("short", strategy.short)
// store the open price value from the beginning of the day.
beginprice = ta.valuewhen(ta.change(dayofweek) > 0, open, 0)
// Calculate the absolute price change for the current period.
priceChg = (close - beginprice)
hline(absCashLoss)
plot(priceChg)
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
(simpleint/float)
a required parameter. Maximum number of contracts/shares/lots/units in a position.
Example
//@version=5strategy("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
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
ta.atr(length) → series float
Arguments
length
(simpleint)
Length (number of bars back).
Example
//@version=5indicator("ta.atr")
plot(ta.atr(14))
//the same on pine
pine_atr(length) =>
trueRange = na(high[1])? high-low : math.max(math.max(high - low, math.abs(high - close[1])), math.abs(low - close[1]))
//true range can be also calculated with ta.tr(true)
ta.rma(trueRange, length)
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.
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
ta.bb(series, length, mult) - [series float, series float, series float]
Arguments
series
(seriesint/float)
series of values to process.
length
(seriesint)
Number of bars (length).
mult
(simpleint/float)
standard deviation factor.
Example
//@version=5indicator("ta.bb")
> [middle, upper, lower] = ta.bb(close, 5, 4)
plot(middle, color=color.yellow)
plot(upper, color=color.yellow)
plot(lower, color=color.yellow)
// the same on pine
f_bb(src, length, mult) =>
float basis = ta.sma(src, length)
float dev = mult * ta.stdev(src, length)
[basis, basis + dev, basis - dev]
> [pinemiddle, pineupper, pineLower] = f_bb(close, 5, 4)
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.
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
ta.cci(source, length) → series float
Arguments
source
(seriesint/float)
series of values to process.
length
(seriesint)
Number of bars (length).
Returns
Commodity channel index of source for length bars back.
Remarks
`na` values in the `source` series are ignored.
ta.change
+5 overloads
Compares the current `source` value to its value `length` bars ago and returns the difference.
//@version=5indicator('Day and direction Change', overlay = true)
dailybartime = time('1D')
isNewDay = ta.change(dailybartime)
bgcolor(isNewDay ? color.new(color.green, 80) : na)
isGreenbar = close >= open
colorChange = ta.change(isGreenbar)
plotshape(colorChange, 'direction Change')
### Returns
the difference between the values when they are numerical. When a 'bool' source is used, returns `true` when the current source is different from the previous source.
### Remarks
`na` values in the `source` series are included in calculations and will produce an `na` result.
### See also
ta.mom
ta.cross
## ta.cmo
Chande Momentum Oscillator. Calculates the difference between the sum of recent gains and the sum of recent losses and then divides the result by the sum of all price movement over the same period.
### Syntax
ta.cmo(series, length) → series float
### Arguments
- `series`
> (`series` `int`/`float`)
> series of values to process.
- `length`
> (`series` `int`)
> Number of bars (length).
### Example
//@version=5indicator("ta.cmo")
plot(ta.cmo(close, 5), color=color.yellow)
// the same on pine
f_cmo(src, length) =>
float mom = ta.change(src)
float sm1 = math.sum((mom >= 0) ? mom : 0.0, length)
float sm2 = math.sum((mom >= 0) ? 0.0 : -mom, length)
100* (sm1 - sm2) / (sm1 + sm2)plot(f_cmo(close, 5))
the cog (center of gravity) is an indicator based on statistics and the Fibonacci golden ratio.
Syntax
ta.cog(source, length) → series float
Arguments
source
(seriesint/float)
series of values to process.
length
(seriesint)
Number of bars (length).
Example
//@version=5indicator("ta.cog", overlay=true)
plot(ta.cog(close, 10))
// the same on pine
pine_cog(source, length) =>
sum = math.sum(source, length)
num = 0.0fori = 0 to length - 1
price = source[i]
num := num + price * (i + 1)
-num / sum
plot(pine_cog(close, 10))
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.crossover(source1, source2) → series bool
Arguments
source1
(seriesint/float)
First data series.
source2
(seriesint/float)
second data series.
Returns
true if `source1` crossed over `source2` otherwise false.
ta.crossunder
the `source1`-series is defined as having crossed under `source2`-series if, on the current bar, the value of `source1` is less than the value of `source2`, and on the previous bar, the value of `source1` was greater than or equal to the value of `source2`.
Syntax
ta.crossunder(source1, source2) → series bool
Arguments
source1
(seriesint/float)
First data series.
source2
(seriesint/float)
second data series.
Returns
true if `source1` crossed under `source2` otherwise false.
ta.cum
Cumulative (total) sum of `source`. in other words it's a sum of all elements of `source`.
Measure of difference between the series and it's ta.sma
Syntax
ta.dev(source, length) → series float
Arguments
source
(seriesint/float)
series of values to process.
length
(seriesint)
Number of bars (length).
Example
//@version=5indicator("ta.dev")
plot(ta.dev(close, 10))
// the same on pine
pine_dev(source, length) =>
mean = ta.sma(source, length)
sum = 0.0fori = 0 to length - 1
val = source[i]
sum := sum + math.abs(val - mean)
dev = sum/length
plot(pine_dev(close, 10))
the dmi function returns the directional movement index.
Syntax
ta.dmi(diLength, adxsmoothing) - [series float, series float, series float]
Arguments
diLength
(simpleint)
Di period.
adxsmoothing
(simpleint)
aDX smoothing period.
Example
//@version=5indicator(title="directional Movement index", shorttitle="DMi", format=format.price, precision=4)
len = input.int(17, minval=1, title="Di Length")
lensig = input.int(14, title="aDX smoothing", minval=1, maxval=50)
> [diplus, diminus, adx] = ta.dmi(len, lensig)
plot(adx, color=color.red, title="aDX")
plot(diplus, color=color.blue, title="+Di")
plot(diminus, color=color.orange, title="-Di")
### Returns
Tuple of three DMi series: positive directional Movement (+Di), Negative directional Movement (-Di) and average directional Movement index (aDX).
### See also
ta.rsi
ta.tsi
ta.mfi
## ta.ema
the ema function returns the exponentially weighted moving average. in ema weighting factors decrease exponentially. it calculates by using a formula: ema = alpha * source + (1 - alpha) * ema[1], where alpha = 2 / (length + 1).
### Syntax
ta.ema(source, length) → series float
### Arguments
- `source`
> (`series` `int`/`float`)
> series of values to process.
- `length`
> (`simple` `int`)
> Number of bars (length).
### Example
//@version=5indicator("ta.ema")
plot(ta.ema(close, 15))
//the same on pine
pine_ema(src, length) =>
alpha = 2 / (length + 1)
sum = 0.0
sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])plot(pine_ema(close,15))
Returns
Exponential moving average of `source` with alpha = 2 / (length + 1).
Keltner Channels. Keltner channel is a technical analysis indicator showing a central moving average line plus channel lines at a distance above and below.
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
ta.linreg(source, length, offset) → series float
Arguments
source
(seriesint/float)
source series.
length
(simpleint)
Number of bars (length).
offset
(simpleint)
Offset.
Returns
linear regression curve.
Remarks
`na` values in the `source` series are included in calculations and will produce an `na` result.
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
(seriesint/float)
series of values to process.
fastlen
(simpleint)
Fast Length parameter.
slowlen
(simpleint)
slow Length parameter.
siglen
(simpleint)
signal Length parameter.
Example
//@version=5indicator("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:
`na` values in the `source` series are ignored; the function calculates on the `length` quantity of non-`na` values.
ta.mfi
Money Flow index. the Money Flow index (MFi) is a technical oscillator that uses price and volume for identifying overbought or oversold conditions in an asset.
the type of pivot point levels. possible values: "traditional", "Fibonacci", "Woodie", "Classic", "DM", "Camarilla".
anchor
(seriesbool)
the condition that triggers the reset of the pivot point calculations. When true, calculations reset; when false, results calculated at the last reset persist.
developing
(seriesbool)
if false, the values are those calculated the last time the anchor condition was true. they remain constant until the anchor condition becomes true again. if true, the pivots are developing, i.e., they constantly recalculate on the data developing between the point of the last anchor (or bar zero if the anchor condition was never true) and the current bar. optional. the default is false.
a float[] array with numerical values representing 11 pivot point levels: [p, R1, s1, R2, s2, R3, s3, R4, s4, R5, s5]. Levels absent from the specified `type` return na values (e.g., "DM" only calculates p, R1, and s1).
Remarks
the `developing` parameter cannot be `true` when `type` is set to "Woodie", because the Woodie calculation for a period depends on that period's open, which means that the pivot value is either available or unavailable, but never developing. if used together, the indicator will return a runtime error.
ta.pivothigh
+1 overload
this function returns price of the pivot high point. it returns 'NaN', if there was no pivot high point.
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
ta.sar(start, inc, max) → series float
Arguments
start
(simpleint/float)
start.
inc
(simpleint/float)
increment.
max
(simpleint/float)
Maximum.
Example
//@version=5indicator("ta.sar")
plot(ta.sar(0.02, 0.02, 0.2), style=plot.style_cross, linewidth=3)
// the same on pine scriptA(r)
pine_sar(start, inc, max) =>
var float result = na
var float maxMin = na
var float acceleration = na
var bool isbelow = na
bool isFirsttrendbar = false
if bar_index == 1
if close > close[1]
isbelow := true
maxMin := high
result := low[1]
else
isbelow := false
maxMin := low
result := high[1]
isFirsttrendbar := true
acceleration := start
result := result + acceleration * (maxMin - result)
if isbelow
if result > low
isFirsttrendbar := true
isbelow := false
result := 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
plot(pine_sar(0.02, 0.02, 0.2), style=plot.style_cross, linewidth=3)
Returns
parabolic saR.
ta.sma
the sma function returns the moving average, that is the sum of last y values of x, divided by y.
Syntax
ta.sma(source, length) → series float
Arguments
source
(seriesint/float)
series of values to process.
length
(seriesint)
Number of bars (length).
Example
//@version=5indicator("ta.sma")
plot(ta.sma(close, 15))
// same on pine, but much less efficient
pine_sma(x, y) =>
sum = 0.0fori = 0 to y - 1
sum := sum + x[i] / y
sum
plot(pine_sma(close, 15))
Returns
simple moving average of `source` for `length` bars back.
How NaN values are handled. if true, and previous day's close is NaN then tr would be calculated as current day high-low. Otherwise (if false) tr would return NaN in such cases. also note, that ta.atr uses ta.tr(true).
Returns
true range. it is math.max(high - low, math.abs(high - close[1]), math.abs(low - close[1])).
the value to be returned from the bar where the condition is met.
occurrence
(simpleint)
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=5indicator("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.
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.variance(source, length, biased) → series float
Arguments
source
(seriesint/float)
series of values to process.
length
(seriesint)
Number of bars (length).
biased
(seriesbool)
Determines which estimate should be used. optional. the default is true.
Returns
variance of `source` for `length` bars back.
Remarks
if `biased` is true, function will calculate using a biased estimate of the entire population, if false - unbiased estimate of a sample.
`na` values in the `source` series are ignored; the function calculates on the `length` quantity of non-`na` values.
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.vwma(source, length) → series float
Arguments
source
(seriesint/float)
series of values to process.
length
(seriesint)
Number of bars (length).
Example
//@version=5indicator("ta.vwma")
plot(ta.vwma(close, 15))
// same on pine, but less efficient
pine_vwma(x, y) =>
ta.sma(x * volume, y) / ta.sma(volume, y)plot(pine_vwma(close, 15))
Returns
Volume-weighted moving average of `source` for `length` bars back.
the wma function returns weighted moving average of `source` for `length` bars back. in wma weighting factors decrease in arithmetical progression.
Syntax
ta.wma(source, length) → series float
Arguments
source
(seriesint/float)
series of values to process.
length
(seriesint)
Number of bars (length).
Example
//@version=5indicator("ta.wma")
plot(ta.wma(close, 15))
// same on pine, but much less efficient
pine_wma(x, y) =>
norm = 0.0
sum = 0.0fori = 0 to y - 1
weight = (y - i) * y
norm := norm + weight
sum := sum + x[i] * weight
sum / norm
plot(pine_wma(close, 15))
Returns
Weighted moving average of `source` for `length` bars back.
the index of the cell's column. Numbering starts at 0.
row
(seriesint)
the index of the cell's row. Numbering starts at 0.
text
(seriesstring)
the text to be displayed inside the cell. optional. the default is empty string.
width
(seriesint)
the width of the cell as a % of the indicator's visual space. optional. by default, auto-adjusts the width based on the text inside the cell. Value 0 has the same effect.
height
(seriesint)
the height of the cell as a % of the indicator's visual space. optional. by default, auto-adjusts the height based on the text inside of the cell. Value 0 has the same effect.
text_color
(seriescolor)
the color of the text. optional. the default is color.black.
this function does not create the table itself, but defines the table's cells. To use it, you first need to create a table object with table.new.
Each table.cell call overwrites all previously defined properties of a cell. if you call table.cell twice in a row, e.g., the first time with text='Test Text', and the second time with text_color=color.red but without a new text argument, the default value of the 'text' being an empty string, it will overwrite 'Test Text', and your cell will display an empty string. if you want, instead, to modify any of the cell's properties, use the table.cell_set_*() functions.
a single script can only display one table in each of the possible locations. if table.cell is used on several bars to change the same attribute of a cell (e.g. change the background color of the cell to red on the first bar, then to yellow on the second bar), only the last change will be reflected in the table, i.e., the cell's background will be yellow. avoid unnecessary setting of cell properties by enclosing function calls in an ifbarstate.islast block whenever possible, to restrict their execution to the last bar of the series.
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.
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.
this function will merge cells, even if their properties are not yet defined with table.cell.
the resulting merged cell inherits all of its values from the cell located at `start_column`:`start_row`, except width and height. the width and height of the resulting merged cell are based on the width/height of other cells in the neighboring columns/rows and cannot be set manually.
To modify the merged cell with any of the `table.cell_set_*` functions, target the cell at the `start_column`:`start_row` coordinates.
an attempt to merge a cell that has already been merged will result in an error.
the background color of the table. optional. the default is no color.
frame_color
(seriescolor)
the color of the outer frame of the table. optional. the default is no color.
frame_width
(seriesint)
the width of the outer frame of the table. optional. the default is 0.
border_color
(seriescolor)
the color of the borders of the cells (excluding the outer frame). optional. the default is no color.
border_width
(seriesint)
the width of the borders of the cells (excluding the outer frame). optional. the default is 0.
Example
//@version=5indicator("table.new example")
var testtable = table.new(position = position.top_right, columns = 2, rows = 1, bgcolor = color.yellow, border_width = 1)
if barstate.islast
table.cell(table_id = testtable, column = 0, row = 0, text = "Open is " + str.tostring(open))
table.cell(table_id = testtable, column = 1, row = 0, text = "Close is " + str.tostring(close), bgcolor=color.teal)
Returns
the iD of a table object that can be passed to other table.*() functions.
Remarks
this function creates the table object itself, but the table will not be displayed until its cells are populated. To define a cell and change its contents or attributes, use table.cell and other table.cell_*() functions.
One table.new call can only display one table (the last one drawn), but the function itself will be recalculated on each bar it is used on. For performance reasons, it is wise to use table.new in conjunction with either the var keyword (so the table object is only created on the first bar) or in an ifbarstate.islast block (so the table object is only created on the last bar).
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.
//@version=5indicator("ticker.inherit")
//@variable a "NasDaq:aapL" ticker iD with Extender Hours enabled.
tickerExthours = ticker.new("NasDaq", "aapL", session.extended)
//@variable a Heikin ashi ticker iD for "NasDaq:aapL" with Extended Hours enabled.
HatickerExthours = ticker.heikinashi(tickerExthours)
//@variable the "NasDaq:MsFT" symbol with no modifiers.
testsymbol = "NasDaq:MsFT"
//@variable a ticker iD for "NasDaq:MsFT" with inherited Heikin ashi and Extended Hours modifiers.
testsymbolHatickerExthours = ticker.inherit(HatickerExthours, testsymbol)
//@variable the `close` price requested using "NasDaq:MsFT" with inherited modifiers.
secdata = request.security(testsymbolHatickerExthours, "60", close, ignore_invalid_symbol = true)
//@variable the `close` price requested using "NasDaq:MsFT" without modifiers.
comparedata = request.security(testsymbol, "60", close, ignore_invalid_symbol = true)
plot(secdata, color = color.green)
plot(comparedata)
Remarks
if the constructed ticker iD inherits a modifier that doesn't apply to the symbol (e.g., if the `from_tickerid` has Extended Hours enabled, but no such option is available for the `symbol`), the script will ignore the modifier when requesting data using the iD.
ticker.kagi
Creates a ticker identifier for requesting Kagi values.
adjustment type. optional argument. possible values: adjustment.none, adjustment.splits, adjustment.dividends. if adjustment is not given, then default adjustment value is used (can be different depending on particular instrument).
adjustment type. optional argument. possible values: adjustment.none, adjustment.splits, adjustment.dividends. if adjustment is not given, then default adjustment value is used (can be different depending on particular instrument).
Example
//@version=5indicator("ticker.new", overlay=true)
t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
t2 = ticker.heikinashi(t)
c = request.security(t2, timeframe.period, low, barmerge.gaps_on)
plot(c, style=plot.style_linebr)
Returns
string value of ticker id, that can be supplied to request.security function.
atr Length if `style` is equal to 'atr', or box size if `style` is equal to 'traditional'.
request_wicks
(simplebool)
specifies if wick values are returned for Renko bricks. When " + addinternallineNottr("op", "true", "true") + ", " + addinternallineNottr("var", "high", "high") + " and " + addinternallineNottr("var", "low", "low") + " values requested from a symbol using the ticker formed by this function will include wick values when they are present. When " + addinternallineNottr("op", "false", "false") + ", " + addinternallineNottr("var", "high", "high") + " and " + addinternallineNottr("var", "low", "low") + " will always be equal to either " + addinternallineNottr("var", "open", "open") + " or " + addinternallineNottr("var", "close", "close") + ". optional. the default is " + addinternallineNottr("op", "false", "false") + ". a detailed explanation of how Renko wicks are calculated can be found in our Help center.
source
(simplestring)
the source used to calculate bricks. optional. possible values: "Close", "OHLC". the default is "Close".
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
ticker.standard(symbol) → simple string
Arguments
symbol
(simplestring)
a ticker iD to be converted into its standard form. optional. the default is syminfo.tickerid.
Example
//@version=5indicator("ticker.standard", overlay = true)
// this script should be run on a non-standard chart such as Ha, Renko...
// Requests data from the chart type the script is running on.
charttypeValue = request.security(syminfo.tickerid, "1D", close)
// Request data from the standard chart type, regardless of the chart type the script is running 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 ticker aEUR" 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.
timeframe. an empty string is interpreted as the current timeframe of the chart.
Example
//@version=5indicator("time", overlay=true)
// try this on chart aapL,1timeinrange(res, sess) => not na(time(res, sess, "america/New_York")) ? 1 : 0plot(timeinrange("1", "1300-1400"), color=color.red)
// this plots 1.0 at every start of 10 minute bar on a 1 minute chart:
newbar(res) => ta.change(time(res)) == 0 ? 0 : 1plot(newbar("10"))
While setting up a session you can specify not just the hours and minutes but also the days of the week that will be included in that session.
if the days aren't specified, the session is considered to have been set from sunday (1) to saturday (7), i.e. "1100-2000" is the same as "1100-1200:1234567".
You can change that by specifying the days. Forexample, on a symbol that is traded seven days a week with the 24-hour trading session the following script will not color saturdays and sundays:
Example
//@version=5indicator("time", overlay=true)
t1 = time(timeframe.period, "0000-0000:23456")
bgcolor(t1 ? color.new(color.blue, 90) : na)
One `session` argument can include several different sessions, separated by commas. Forexample, the following script will highlight the bars from 10:00 to 11:00and from 14:00 to 15:00 (workdays only):
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.
//@version=5
// Run this script on an intraday chart.
indicator("New day started", overlay = true)
// Highlights the first bar of the new day.
isNewDay = timeframe.change("1D")
bgcolor(isNewDay ? color.new(color.green, 80) : na)
Returns
Returns true on the first bar of a new `timeframe`, false otherwise.
timeframe.from_seconds
+1 overload
Converts a number of seconds into a valid timeframe string.
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".
//@version=5indicator("`timeframe_in_seconds()`")
// Get a user-selected timeframe.
tfinput = input.timeframe("1D")
// Convert it into an "int" number of seconds.
secondsinTf = timeframe.in_seconds(tfinput)
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.
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.
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.
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.
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.
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.
a named constant for use with the `display` parameter of `plot*()` and `input*()` functions. Displays plotted or input values in all possible locations.
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.
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.
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.
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.
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
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 float
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 float
dividends.gross
a named constant for the request.dividends function. is used to request the dividends return on a stock before deductions.
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 zeroes.
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.
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'.
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.
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.
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.
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=5strategy("strategy.cash", overlay = true, default_qty_value = 50, default_qty_type = strategy.cash, initial_capital = 1000000)
if bar_index == 0
// as aEUR~qtyaEUR(tm) is not defined, the previously defined values forthe `default_qty_type` and `default_qty_value` parameters are used to enter trades, namely 50 units of cash in the currency 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")
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=5strategy("strategy.fixed", overlay = true, default_qty_value = 50, default_qty_type = strategy.fixed, initial_capital = 1000000)
if bar_index == 0
// as aEUR~qtyaEUR(tm) is not defined, the previously defined values forthe `default_qty_type` and `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")
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.
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.
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=5strategy("strategy.percent_of_equity", overlay = false, default_qty_value = 100, default_qty_type = strategy.percent_of_equity, initial_capital = 1000000)
// as aEUR~qtyaEUR(tm) is not defined, the previously defined values forthe `default_qty_type` and `default_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 aEUR~qtyaEUR(tm) 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")
a named constant that specifies the algorithm of interpretation of x-value in functions line.new and label.new. if xloc = xloc.bar_index, value of x is a bar index.
a named constant that specifies the algorithm of interpretation of x-value in functions line.new and label.new. if xloc = xloc.bar_time, value of x is a bar unix time.
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 fordebugging 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 scriptA(r) Editor's tooltips.
the 'for' structure allows the repeated execution of a number of statements:
Syntax
> [var_declaration =] for counter = from_num to to_num [by step_num]
statements | continue | break
return_expression
var_declaration - an optional variable declaration that will be assigned the value of the loop's return_expression.
counter - a variable holding the value of the loop's counter, which is incremented/decremented by 1 or by the step_num value on each iteration of the loop.
from_num - the starting value of the counter. "series int/float" values/expressions are allowed.
to_num - the end value of the counter. When the counter becomes greater than to_num (or less than to_num in cases where from_num > to_num) the loop is broken. "series int/float" values/expressions are allowed, but they are evaluated only on the loop's first iteration.
step_num - the increment/decrement value of the counter. it is optional. the default value is +1 or -1, depending on which of from_num or to_num is the greatest. When a value is used, the counter is also incremented/decremented depending on which of from_num or to_num is the greatest, so the +/- sign of step_num is optional.
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 which is 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.
Example
//@version=5indicator("for")
// Here, we count the quantity of bars in a given 'lookback' length which closed above the current bar's close
qtyOfHigherCloses(lookback) =>
int result = 0fori = 1 to lookback
if close[i] > close
result += 1
result
plot(qtyOfHigherCloses(14))
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
> [var_declaration =] for array_element in array_id
statements | continue | break
return_expression
> [var_declaration =] for [index, array_element] in array_id
statements | continue | break
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.
it is allowed to modify the array's elements or its size inside the loop.
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=5indicator("`for` loop with a step")
a = array.from(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
sum = 0.0for 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)
#op_for...in) to set the values of our ispos array to true when their corresponding value in our valuesarray array is positive:
Example
//@version=5indicator("for...in")
// Here we determine on each bar how many of the bar's OHLC values are greater than the sMa of 'close' values
float[] ohlcValues = array.from(open, high, low, close)
qtyGreaterthan(value, array) =>
int result = 0forcurrentelement 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:
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 scriptA(r) language in the very first line of code, for 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)
for [index, value] in valuesarray
if value > 0
array.set(ispos, index, true)
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(ispos))
iterate through matrix rows as arrays.
# 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
import {username}/{libraryName}/{libraryVersion} as {alias}
Arguments
username
(literalstring)
user name of the library's author.
libraryName
(literalstring)
Name of the imported library, which corresponds to the title argument used by the author in his library script.
libraryVersion
(literalint)
Version number of the imported library.
alias
(literalstring)
Namespace used to refer to the library's functions. optional. the default is the libraryName string.
Remarks
using an alias that replaces a built-in namespace such as math.* or strategy.* is allowed, but if the library contains function names that shadow pine scriptA(r)'s built-in functions, the built-ins will become unavailable. the same version of a library can only be imported once. aliases must be distinct for each imported library. When calling library functions, casting their arguments to types other than their declared type is not allowed.
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.
//@version=5
the 4th version of pine scriptA(r) Language allows you to use aEURoeelse ifaEUR syntax.
General code form:
Syntax
var_declarationX = if condition
var_decl_then0
var_decl_then1
...
var_decl_thenN
else if [optional block]
var_decl_else0
var_decl_else1
...
var_decl_elseN
else
var_decl_else0
var_decl_else1
...
var_decl_elseN
return_expression_else
where
var_declarationX aEUR" this variable gets the value of the if statement
condition aEUR" 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 aEUR" 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=5indicator("if")
// this code compiles
x = if close > open
close
else
open
// this code doesnaEUR(tm)t compile
// y = if close > open
// close
// else
// "open"plot(x)
it is possible to omit the `else` block. in this case if the condition is false, an aEURoeemptyaEUR value (na, false, or aEURoeaEUR) will be assigned to the var_declarationX variable:
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.
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:
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.
libraries can export udts. see thelibraries page of our user Manual to learn more.
Example
//@version=5indicator("if")
x = if close > open
close
// if current close > current open, then x = close.
// Otherwise the x = na.
plot(x)
it is possible to use either multiple aEURoeelse ifaEUR blocks or none at all. the blocks aEURoethenaEUR, aEURoeelse ifaEUR, aEURoeelseaEUR are shifted by four spaces:
# var
var is the keyword used for assigning and one-time initializing of the variable.
Normally, a syntax of assignment of variables, which doesnaEUR(tm)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 aEURoekeep the stateaEUR despite the data updating, only changing it when conditions within if-expressions are met.
Syntax
var variable_name = expression
where:
variable_name - any name of the useraEUR(tm)s variable thataEUR(tm)s allowed in pine scriptA(r) (can contain capital and lowercase Latin characters, numbers, and underscores (_), but canaEUR(tm)t start with a number).
expression - any arithmetic expression, just as with defining a regular variable. the expression will be calculated and assigned to a variable once.
Example
//@version=5indicator("if")
x = if open > close
5else if high > low
close
else
open
plot(x)
it is possible to ignore the resulting value of an `if` statement (aEURoevar_declarationX=aEURoe can be omitted). it may be useful if you need the side effect of the expression, forexample in strategy trading:
# varip
varip (var intrabar persist) is the keyword used for the assignment and one-time initialization of a variable or a field of a user-defined type. itaEUR(tm)s similar to the var keyword, but variables and fields declared with varip retain their values between executions of the script on the same bar.
variable_type - an optional fundamental type (int, float, bool, color, string) or a user-defined type, or an array or matrix of one of those types. special types are not compatible with this keyword.
variable_name - a valid identifier. the variable can also be an object created from a udt.
expression - any arithmetic expression, just as when defining a regular variable. the expression will be calculated and assigned to the variable only once, on the first bar.
udt_identifier, field_type, field_name, value - Constructs related to user-defined types as described in the type section.
Example
//@version=5strategy("if")
if (ta.crossover(high, low))
strategy.entry("bbandlE", strategy.long, stop=low, oca_name="bollingerbands", oca_type=strategy.oca.cancel, comment="bbandlE")
else
strategy.cancel(id="bbandlE")
if statements can include each other:
#op_var), v would equal the value of the bar_index. On historical bars, where the script calculates only once per chart bar, the value of v is the same as with var. However, on realtime bars, the script will evaluate the expression on each new chart update, producing a different result.
Example
//@version=5indicator("if")
float x = na
if close > open
if close > close[1]
x := close
else
x := close[1]
else
x := open
plot(x)
#op_+=) operation applied to both the index and ticks fields results in different real-time values because ticks increases on every chart update, while index only does so once per bar. Note how the currbar object does not use the varip keyword. the ticks field of the object can increment on every tick, but the reference itself is defined once and then stays unchanged. if we were to declare currbar using varip, the behavior of index would remain unchanged because while the reference to the type instance would persist between chart updates, the index field of the object would not.
Remarks
When using varip to declare variables in strategies that may execute more than once per historical chart bar, the values of such variables are preserved across successive iterations of the script on the same bar.
the effect of varip eliminates the rollback of variables before each successive execution of a script on the same bar.
# while
the while statement allows the conditional iteration of a local code block.
Syntax
variable_declaration = while boolean_expression
...
continue
...
break
...
return_expression
where:
variable_declaration - an optional variable declaration. the return expression can provide the initialization value for this variable.
boolean_expression - 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=5indicator("num_methods import")
// import the first version of the usernameaEUR(tm)s "num_methods" library and assign it to the "m" namespace",import username/num_methods/1 as m// Call the aEURoesinh()aEUR function from the imported libraryy = m.sinh(3.14)// plot value returned by the "sinh()" function",
plot(y)
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, array.from function.
Example
//@version=5indicator("")
var prices = array.new<float>()
//@function pushes a new value into the array and removes the first one if the resulting array is greater than `maxsize`. Can be used as a method.
method maintainarray(array<float> id, maxsize, value) =>
id.push(value)
if id.size() > maxsize
id.shift()
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 forits 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 type.
// 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.
//@version=5indicator("switch using an expression")
string i_maType = input.string("ema", "Ma type", options = ["ema", "sMa", "RMa", "WMa"])
float ma = switch i_maType
"ema" => ta.ema(close, 10)
"sMa" => ta.sma(close, 10)
"RMa" => ta.rma(close, 10)
// Default used when the three first cases do not match.
=> ta.wma(close, 10)
plot(ma)
switch without an expression:
Explicitly mentioning the type in a variable declaration is optional, except when it is initialized with na. Learn more about pine scriptA(r) types in the user Manual page on the Type system.
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=5indicator("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
drawbox(bar b, right) =>
bar s = bar.new()
color boxcolor = b.c >= b.o ? color.green : color.red
box.new(b.t, b.h, right, b.l, boxcolor, xloc = xloc.bar_time, bgcolor = color.new(boxcolor, 90))
updatebox(box boxid, bar b) =>
color boxcolor = b.c >= b.o ? color.green : color.red
box.set_border_color(boxid, boxcolor)
box.set_bgcolor(boxid, color.new(boxcolor, 90))
box.set_top(boxid, b.h)
box.set_bottom(boxid, b.l)
box.set_right(boxid, time)
secbar = request.security(syminfo.tickerid, timeframeinput, bar.new())
ifnot 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 when HTF changes.
lastbox := drawbox(secbar, time)
else
// On other chart updates, use setters to modify the current box.
updatebox(lastbox, secbar)
Keyword used to explicitly declare the "color" type of a variable or a parameter.
Example
//@version=5indicator("var keyword example")
var a = close
var b = 0.0var c = 0.0var green_bars_count = 0if close > open
var x = close
b := x
green_bars_count := green_bars_count + 1
if green_bars_count >= 10
var y = close
c := y
plot(a)
plot(b)
plot(c)
the variable 'a' keeps the closing price of the first bar foreach bar in the series.
the variable 'b' keeps the closing price of the first "green" bar in the series.
the variable 'c' keeps the closing price of the tenth "green" bar in the series.
#FF000080 // Red color (FF0000) with 50% transparency (80 which is half of FF).if barstate.islastconfirmedhistory label.new(bar_index, high, text = "label", color = labelcolor, textcolor = textcolor)// When declaring variables with color literals, built-in constants(color.green) or functions (color.new(), color.rgb()), the "color" keyword for the type can be omitted.c = color.rgb(0,255,0,0)plot(close, color = c)
Remarks
color literals have the following format: #RRGGbb or #RRGGbbaa. the letter pairs represent 00 to FF hexadecimal values (0 to 255 in decimal) where RR, GG and bb pairs are the values for the color's red, green and blue components. aa is an optional value for the color's transparency (or alpha component) where 00 is invisible and FF opaque. When no aa pair is supplied, FF is used. the hexadecimal letters can be upper or lower case.
Explicitly mentioning the type in a variable declaration is optional, except when it is initialized with na. Learn more about pine scriptA(r) types in the user Manual page on the Type system.
Keyword used to explicitly declare the "float" (floating point) type of a variable or a parameter.
Example
//@version=5indicator("varip")
varip int v = -1v := v + 1plot(v)
With var, `v` would equal the value of the bar_index. On historical bars, where the script calculates only once per chart bar, the value of `v` is the same as with var. However, on realtime bars, the script will evaluate the expression on each new chart update, producing a different result.
Remarks
Explicitly mentioning the type in a variable declaration is optional, except when it is initialized with na. Learn more about pine scriptA(r) types in the user Manual page on the Type system.
Keyword used to explicitly declare the "int" (integer) type of a variable or a parameter.
Example
//@version=5indicator("varip with types")
type bardata
int index = -1
varip int ticks = -1var currbar = bardata.new()
currbar.index += 1currbar.ticks += 1
// Will be equal to bar_index on all bars
plot(currbar.index)
// in real time, will increment per every tick on the chart
plot(currbar.ticks)
the same += operation applied to both the `index` and `ticks` fields results in different real-time values because `ticks` increases on every chart update, while `index` only does so once per bar. Note how the `currbar` object does not use the varip keyword. the `ticks` field of the object can increment on every tick, but the reference itself is defined once and then stays unchanged. if we were to declare `currbar` using varip, the behavior of `index` would remain unchanged because while the reference to the type instance would persist between chart updates, the `index` field of the object would not.
Remarks
Explicitly mentioning the type in a variable declaration is optional, except when it is initialized with na. Learn more about pine scriptA(r) types in the user Manual page on the Type system.
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=5indicator("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 = 1while counter > 0
factorial := factorial * counter
counter := counter - 1plot(factorial)
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=5indicator("bool")
bool b = true // same as `b = true`
b := na
plot(b ? open : close)
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=5indicator("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)
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 function.
Example
//@version=5indicator("color", overlay = true)
color textcolor = color.green
color labelcolor = #FF000080 // Red color (FF0000) with 50% transparency (80 which is half of FF).
if barstate.islastconfirmedhistory
label.new(bar_index, high, text = "label", color = labelcolor, textcolor = textcolor)
// When declaring variables with color literals, built-in constants(color.green) or functions (color.new(), color.rgb()), the "color" keyword forthe type can be omitted.
c = color.rgb(0,255,0,0)
plot(close, color = c)
series is a keyword that can be used in a library's exported functions to specify the type form required for a function's arguments. Explicit use of the series keyword is usually unnecessary because all arguments of exported functions are automatically converted to the "series" form by default.
//@version=5indicator("float")
floatf= 3.14 // same as `f = 3.14`
f := na
plot(f)
# simple
simple is a keyword that can be used in a library's exported functions to specify the type form required for a function's arguments. by default, all arguments of exported functions are automatically converted into the "series" type form. in some cases, this would make arguments unusable with those of built-in functions that do not support the "series" form. For these cases, the simple keyword can be used instead.
//@version=5indicator("int")
int i = 14 // same as `i = 14`
i := na
plot(i)
# string
Keyword used to explicitly declare the "string" type of a variable or a parameter.
Example
//@version=5indicator("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
Explicitly mentioning the type in a variable declaration is optional, except when it is initialized with na. Learn more about pine scriptA(r) types in the user Manual page on the Type system.
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=5indicator("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)
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=5indicator("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))
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=5indicator("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")
# !=
Not equal to. applicable to expressions of any type.
Syntax
expr1 != expr2
Returns
boolean value, or series of boolean values.
# ?:
Ternary conditional operator.
Syntax
expr1 ? expr2 : expr3
Example
//@version=5indicator("matrix example")
// Create `m1` matrix of `int` type.
matrix<int> m1 = matrix.new<int>(2, 3, 0)
// `matrix<int>` is unnecessary because the `matrix.new<int>()` function returns an `int` type matrix object.
m2 = matrix.new<int>(2, 3, 0)
// Display matrix using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(m2))
Returns
expr2 if expr1 is evaluated to true, expr3 otherwise. Zero value (0 and also NaN, +infinity, -infinity) is considered to be false, any other value is true.
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
//@description library of debugging functions.
library("Debugging_library", overlay = true)
export smaCustom(series float source, series int length) =>
ta.sma(source, length)
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
//@description library of debugging functions.
library("Debugging_library", overlay = true)
export emaWrong(float source, int length) =>
// by default, both `source` and `length` will expect values of the `series` type form: `series float` for `source`, `series int` for `length`.
// this function will not compile because `ema()` does not support a "series int" argument for `length`. a "simple int" is required.
ta.ema(source, length)
export emaRight(float source, simple int length) =>
// this function requires an argument of "simple int" type forits `length` parameter.
ta.ema(source, length)
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=5indicator("string")
string s = "Hello World!" // same as `s = "Hello world!"`
// string s = na // same as ""plot(na, title=s)
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 scriptA(r), 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.
a <local_block> is zero or more pine scriptA(r) statements.
the <function_result> is a variable, an expression, or a tuple.
Example
//@version=5indicator("My script")
myvar = 10if close > open
// Modifies the existing global scope `myvar` variable by changing its value from 10 to 20.
myvar := 20
// Creates a new `myvar` variable local to the `if` condition and unreachable from the global scope.
// Does not affect the `myvar` declared in global scope.
myvar = 30plot(myvar)
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
expr1 > expr2
Returns
boolean value, or series of boolean values.
# >=
Greater than or equal to. applicable to numerical expressions.
Current bar index. Numbering is zero-based, index of the first bar is 0.
Type
series int
Example
//@version=5
indicator("bar_index")
plot(bar_index)
plot(bar_index > 5000 ? close : 0)
Remarks
Note that bar_index has replaced n variable in version 4.Note that bar indexing starts from 0 on the first historical bar.Please note that using this variable/function can cause indicator repainting.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 chart, 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.
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.
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.
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.
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)
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)
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.
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.
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.
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)
float maFast = ta.sma(close, 14)
float maSlow = ta.sma(close, 28)
if ta.crossover(maFast, maSlow)
strategy.entry("Long", strategy.long)
if ta.crossunder(maFast, maSlow)
strategy.entry("Short", strategy.short)
changePercent(v1, v2) =>
float result = (v1 - v2) * 100 / math.abs(v2)
// 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.
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.
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.
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=50,
default_qty_type = strategy.percent_of_equity, default_qty_value = 100
)
// Enter a short position on the first bar.
if barstate.isfirst
strategy.entry("Short", strategy.short)
// Plot the capital held by the short position.
plot(strategy.opentrades.capital_held, "Capital held")
// Highlight the chart background if the position is completely closed by margin calls.
bgcolor(bar_index > 0 and strategy.opentrades.capital_held == 0 ? color.new(color.red, 60) : na)
Remarks
This variable returns na if the strategy does not simulate funding trades with a portion of the hypothetical account, i.e., if the strategy function does not include nonzero margin_long or margin_short arguments.
strategy.position_avg_price
Average entry price of current market position. If the market position is flat, 'NaN' is returned.
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).
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".
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".
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.
Prefix of current symbol name (i.e. for 'CME_EOD:TICKER' prefix is 'CME_EOD').
Type
simple string
Example
//@version=5
indicator("syminfo.prefix")
// If current chart symbol is 'BATS:MSFT' then syminfo.prefix is 'BATS'.
if barstate.islastconfirmedhistory
label.new(bar_index, high, text=syminfo.prefix)
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.
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)
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.
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, xloc = 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.orange, 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_estimates)
label.new(bar_index, close, estimatesText, textcolor = color.white, size = size.large)
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, xloc = 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.orange, 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_estimates)
label.new(bar_index, close, estimatesText, textcolor = color.white, size = size.large)
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, xloc = 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.orange, 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_estimates)
label.new(bar_index, close, estimatesText, textcolor = color.white, size = size.large)
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, xloc = 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.orange, 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_estimates)
label.new(bar_index, close, estimatesText, textcolor = color.white, size = size.large)
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, xloc = 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.orange, 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_estimates)
label.new(bar_index, close, estimatesText, textcolor = color.white, size = size.large)
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, xloc = 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.orange, 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_estimates)
label.new(bar_index, close, estimatesText, textcolor = color.white, size = size.large)
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.
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".
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.
//@version=5
indicator("Intraday Intensity Index")
plot(ta.iii, color=color.yellow)
// the same on pine
f_iii() =>
(2 * close - high - low) / ((high - low) * volume)
plot(f_iii())
ta.nvi
Negative Volume Index.
Type
series float
Example
//@version=5
indicator("Negative Volume Index")
plot(ta.nvi, color=color.yellow)
// the same on pine
f_nvi() =>
float ta_nvi = 1.0
float prevNvi = (nz(ta_nvi[1], 0.0) == 0.0) ? 1.0: ta_nvi[1]
if nz(close, 0.0) == 0.0 or nz(close[1], 0.0) == 0.0
ta_nvi := prevNvi
else
ta_nvi := (volume < nz(volume[1], 0.0)) ? prevNvi + ((close - close[1]) / close[1]) * prevNvi : prevNvi
result = ta_nvi
plot(f_nvi())
ta.obv
On Balance Volume.
Type
series float
Example
//@version=5
indicator("On Balance Volume")
plot(ta.obv, color=color.yellow)
// the same on pine
f_obv() =>
ta.cum(math.sign(ta.change(close)) * volume)
plot(f_obv())
ta.pvi
Positive Volume Index.
Type
series float
Example
//@version=5
indicator("Positive Volume Index")
plot(ta.pvi, color=color.yellow)
// the same on pine
f_pvi() =>
float ta_pvi = 1.0
float prevPvi = (nz(ta_pvi[1], 0.0) == 0.0) ? 1.0: ta_pvi[1]
if nz(close, 0.0) == 0.0 or nz(close[1], 0.0) == 0.0
ta_pvi := prevPvi
else
ta_pvi := (volume > nz(volume[1], 0.0)) ? prevPvi + ((close - close[1]) / close[1]) * prevPvi : prevPvi
result = ta_pvi
plot(f_pvi())
ta.pvt
Price-Volume Trend.
Type
series float
Example
//@version=5
indicator("Price-Volume Trend")
plot(ta.pvt, color=color.yellow)
// the same on pine
f_pvt() =>
ta.cum((ta.change(close) / close[1]) * volume)
plot(f_pvt())
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])).
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.