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
The following types are available for user-defined types.
A type can be defined with the type keyword.
A type is similar to a class in object-oriented languages,
but methods are declared afterwards and externally
Type
Description
type
Create a user-defined type with name
.new()
Create a new user-defined type object
.
calls the stored field item of the type either to reassign, or as an expression's return value
Pine Script™ Variables and Constants
Pine Script™ is a loosely typed language. This means that
you do not need to specify the type of data a variable
refers to on asignment unless it is 'na'.
The data type is automatically assigned when
the variable is assigned a value.
It is NOT possible to change the data type after.
Example
a = 1 // a is a intb = 1.2 // b is afloatc = "1.2" // c is a stringd = true // d is a boole = color.new(color.red,50) // e is a color
Example
// type inference// declare a variable without an initial value// the variable type will be 'na' until it is assigned a valuevar int a = na// assign a value to the na inta := 1// variable type is now a value
BUILT INS
Pine Script Indicator functions and variables
Function/Var
Description
ta.accdist
Returns the accumulation/distribution line.
ta.alma()
Returns the Arnaud Legoux Moving Average.
ta.atr()
ATR Returns the Average True Range indicator.
ta.bb()
Returns the Bollinger Bands.
ta.bbw()
Returns the Bollinger Width indicator.
ta.cci()
Returns the Commodity Channel index.
ta.cmo()
Returns the Chande Momentum Oscillator.
ta.cog()
Returns the Center of Gravity indicator.
ta.dmi()
Returns the Directional Movement indicator.
ta.ema()
Returns the Exponential Moving Average.
ta.hma()
Returns the Hull Moving Average.
ta.iii
Returns the Intraday Intensity Index indicator.
ta.kc()
Returns the Keltner Channels.
ta.kcw()
Returns the Keltner Channels width.
ta.linreg()
Returns the Linear Regression Overlay.
ta.macd()
Returns the Moving Average Convergence/Divergence.
ta.mfi()
Returns the Money Flow Index.
ta.mom()
Returns the Momentum indicator.
ta.nvi
Returns the Negative Volume Index.
ta.obv
Returns the On-Balance Volume indicator.
ta.pvi
Returns the Positive Volume Index.
ta.pvt
Returns the Price Volume Trend indicator.
ta.rma()
Returns the Roughness Moving Average.
ta.roc()
Returns the Rate of Change indicator.
ta.rsi(source, length)
Returns the Relative Strength Index.
ta.sar()
Returns the Parabolic Stop and Reverse.
ta.sma()
Returns the Simple Moving Average.
ta.stoch()
Returns the Stochastic oscillator.
ta.supertrend()
Returns the Supertrend indicator.
ta.swma(source)
Returns the Smoothed Weighted Moving Average.
ta.tr
Returns the True Range.
ta.tsi()
Returns the True Strength Index.
ta.vwap
Returns the Volume Weighted Average Price.
ta.vwma()
Returns the Volume Weighted Moving Average.
ta.wad
Returns the Williams Accumulation/Distribution.
ta.wma()
Returns the Weighted Moving Average.
ta.wpr()
Returns the Williams %R indicator.
ta.wvad
Returns the Volume Accumulation/Distribution.
Pine Script Supporting functions
Function
Description
ta.barsince()
Returns the number of bars since a condition has been true.
ta.change()
Returns the percent change of a bar compared to the previous bar.
ta.correlation(source1, source2, length)
Returns the Pearson’s correlation coefficient between two prices.
ta.cross(source1, source2)
Returns true if source1 crossed source2 from downward to upward.
ta.crossover(source1, source2)
Returns true if source1 crossed source2 from downward to upward.
ta.crossunder(source1, source2)
Returns true if source1 crossed source2 from upward to downward.
ta.cum(source)
Returns the cumulative sum of a source.
ta.dev()
Returns the standard deviation of a source.
ta.falling()
Returns true if the current bar’s close price is lower than the previous bar’s close price.
ta.highest()
Returns the highest value from the source.
ta.highestbars()
Returns the highest value from the source within n bars.
ta.lowest()
Returns the lowest value from the source.
ta.lowestbars()
Returns the lowest value from the source within n bars.
ta.median()
Returns the median given the source data.
ta.mode()
Returns the mode given the source data.
ta.percentile_linear_interpolation()
Returns the percentile of the data using linear interpolation.
ta.percentile_nearest_rank()
Returns the percentile of the data using the nea
ta.percentrank(n)
Returns the percentile rank based on the source within n bars.
ta.pivothigh()
Returns the highest high/low that preceded the current bar.
ta.pivotlow()
Returns the lowest high/low that preceded the current bar.
ta.range()
Returns the high to low range of the source.
ta.rising()
Returns true if the current bar’s close price is higher than the previous bar’s close price.
ta.stdev()
Returns the standard deviation of the source.
ta.valuewhen()
Returns the source’s last value when a condition of a given length was true.
ta.variance()
Returns the variance for a given source
Pine Script “math” namespace for math-related functions and variables
Function
Description
math.abs(number)
Returns the absolute value of the number.
math.acos(number)
Returns the arc cosine of the number.
math.asin(number)
Returns the arc sine of the number.
math.atan(number)
Returns the arc tangent of the number.
math.avg()
Returns the average of the numbers.
math.ceil(number)
Returns the ceiling of the number.
math.cos(angle)
Returns the cosine of an angle.
math.exp(number)
Returns the exponential of the number.
math.floor(number)
Returns the floor of the number.
math.log(number)
Returns the natural logarithm of a number.
math.log10(number)
Returns the base-10 logarithm of a number.
math.max()
Returns the maximum of the numbers.
math.min()
Returns the minimum of the numbers.
math.pow()
Returns the value of the first number raised to the power of the second number.
math.random()
Returns a random number between 0 and 1.
math.round(number, precision)
Rounds the number to a given number of decimal places.
math.round_to_mintick(number)
Rounds the number to the smallest increment allowed by the broker
math.sign(number)
Returns a 1 for a postive number and a -1 for a negative number, or 0 for a zero number
math.sin(angle)
Returns the sine of an angle.
math.sqrt(number)
Returns the square root of a number.
math.sum()
Returns the sum of the numbers.
math.tan(angle)
Returns the tangent of an angle.
math.todegrees()
Converts an angle from radians to degrees.
math.toradians()
Converts an angle from degrees to radians.
Pine Script “request” namespace for functions that request external data
Function
Description
request.financial()
Requests financial data such as P/E ratio and market capitalization from an online source.
request.quandl()
Requests a dataset stored online using Quandl.
request.security(<...>, timeframe, <...>)
Requests a certain security to be plotted on the chart.
request.splits()
Requests stock splits data from an online source.
request.dividends()
Requests dividend information from an online source.
request.earnings()
Requests earnings data from an online source.
Pine Script “ticker” namespace for functions that help create tickers
Function
Description
ticker.heikinashi()
Creates a Heikin-Ashi ticker.
ticker.kagi()
Creates a Kagi chart.
ticker.linebreak()
Creates a Line Break chart.
ticker.pointfigure()
Creates a Point & Figure chart.
ticker.renko()
Creates a Renko chart.
ticker.new()
Creates a new ticker.
Pine Script™ Arrays
Arrays allow you to store multiple values in a single variable. Each value in the array is identified by a unique index number. The first element in an array is always 0, the second element is 1, and so on.
Function
Description
array.abs ()
Returns the absolute value of each element in the array.
array.avg ()
Returns the average of the array elements.
array.binary_search ()
Searches for a value in a sorted array and returns the index of the element that matches the value.
array.binary_search_leftmost ()
Searches for a value in a sorted array and returns the index of the leftmost element that matches the value.
array.binary_search_rightmost ()
Searches for a value in a sorted array and returns the index of the rightmost element that matches the value.
array.clear ()
Removes all elements from the array.
array.concat ()
Concatenates two arrays.
array.copy ()
Copies the array.
array.covariance ()
Returns the covariance of the array elements.
array.every ()
Tests whether all elements in the array pass the provided test function.
array.fill ()
Fills the array with a value.
array.first ()
Returns the first element in the array.
array.from ()
Creates an array from a list of values.
array.get ()
Returns the element at the specified index.
array.includes ()
Returns true if the array contains the specified value.
array.indexof ()
Returns the index of the first occurrence of a value in the array.
array.insert ()
Inserts a new element at the specified index.
array.join ()
Joins all elements of an array into a string.
array.last ()
Returns the last element in the array.
array.lastindexof ()
Returns the index of the last occurrence of a value in the array.
array.max ()
Returns the maximum value in the array.
array.median ()
Returns the median of the array elements.
array.min ()
Returns the minimum value in the array.
array.mode ()
Returns the mode of the array elements.
array.new<bool>()
Creates a new array of booleans.
array.new<box>()
Creates a new array of boxes.
array.new<color>()
Creates a new array of colors.
array.new<float>()
Creates a new array of floats.
array.new<int>()
Creates a new array of integers.
array.new<label>()
Creates a new array of labels.
array.new<line>()
Creates a new array of lines.
array.new<linefill>()
Creates a new array of linefills.
array.new<string>()
Creates a new array of strings.
array.new<table>()
Creates a new array of tables.
array.new<type>()
Creates a new array of the specified type.
array.percentile_linear_interpolation ()
Returns the value at the given percentile using linear interpolation.
array.percentile_nearest_rank ()
Returns the value at the given percentile using the nearest rank method.
array.percentrank ()
Returns the percentile rank of a value in the array.
array.pop ()
Removes the last element from the array and returns it.
array.push ()
Adds one or more elements to the end of the array and returns the new length of the array.
array.range ()
Creates a new array with a range of numbers.
array.remove ()
Removes the element at the specified index from the array.
array.reverse ()
Reverses the order of the elements in the array.
array.set ()
Sets the element at the specified index.
array.shift ()
Removes the first element from the array and returns it.
array.size ()
Returns the number of elements in the array.
array.slice ()
Returns a section of the array.
array.some ()
Tests whether at least one element in the array is true if bool, or if any value exists otherwise
array.sort ()
Sorts the elements of an array in place.
array.sort ()
Sorts the elements of the array.
array.sort_indices ()
Returns a new array containing the indices of the original array's elements in sorted order.
array.splice ()
Adds and/or removes elements from the array.
array.standardize ()
Standardizes the array elements by subtracting the mean and dividing by the standard deviation.
array.stdev ()
Returns the standard deviation of the array elements.
array.sum ()
Returns the sum of the array elements.
array.unshift ()
Adds one or more elements to the beginning of the array and returns the new length of the array.
array.variance ()
Returns the variance of the array elements.
Pine Script™ Colors
The following functions are available for colors.
Function
Description
color.a
Returns the alpha component of the color.
color.b
Returns the blue component of the color.
color.g
Returns the green component of the color.
color.r
Returns the red component of the color.
color.rgb
Returns a color from red, green, blue , transp
Pine Script™ Matrices
The following functions are available for matrices as functions and methods
Function
Description
matrix.add_col
Adds a column to a matrix
matrix.add_row
Adds a row to a matrix
matrix.avg
Returns the average of a matrix
matrix.col
Returns a column from a matrix
matrix.columns
Returns the number of columns in a matrix
matrix.concat
Concatenates two matrices
matrix.copy
Copies a matrix
matrix.det
Returns the determinant of a matrix
matrix.diff
Returns the difference of a matrix
matrix.eigenvalues
Returns the eigenvalues of a matrix
matrix.eigenvectors
Returns the eigenvectors of a matrix
matrix.elements_count
Returns the number of elements in a matrix
matrix.fill
Fills a matrix with a value
matrix.get
Returns the value of a matrix element
matrix.inv
Returns the inverse of a matrix
matrix.is_antidiagonal
Returns true if a matrix is antidiagonal
matrix.is_antisymmetric
Returns true if a matrix is antisymmetric
matrix.is_binary
Returns true if a matrix is binary
matrix.is_diagonal
Returns true if a matrix is diagonal
matrix.is_identity
Returns true if a matrix is identity
matrix.is_square
Returns true if a matrix is square
matrix.is_stochastic
Returns true if a matrix is stochastic
matrix.is_symmetric
Returns true if a matrix is symmetric
matrix.is_triangular
Returns true if a matrix is triangular
matrix.is_zero
Returns true if a matrix is zero
matrix.kron
Returns the Kronecker product of two matrices
matrix.max
Returns the maximum value of a matrix
matrix.median
Returns the median of a matrix
matrix.min
Returns the minimum value of a matrix
matrix.mode
Returns the mode of a matrix
matrix.mult
Returns the product of two matrices
matrix.new
Creates a new matrix
matrix.pinv
Returns the pseudoinverse of a matrix
matrix.pow
Returns the power of a matrix
matrix.rank
Returns the rank of a matrix
matrix.remove_col
Removes a column from a matrix
matrix.remove_row
Removes a row from a matrix
matrix.reshape
Reshapes a matrix
matrix.reverse
Reverses the order of the elements in a matrix
matrix.row
Returns a row from a matrix
matrix.rows
Returns the number of rows in a matrix
matrix.set
Sets the value of a matrix element
matrix.sort
Sorts the elements of a matrix
matrix.submatrix
Returns a submatrix from a matrix
matrix.sum
Returns the sum of a matrix
matrix.swap_columns
Swaps two columns in a matrix
matrix.swap_rows
Swaps two rows in a matrix
matrix.trace
Returns the trace of a matrix
matrix.transpose
Returns the transpose of a matrix
Pine Script™ Strings
The following functions are available for strings.
Function
Description
string.charat
Returns the character at the specified index.
string.charcodeat
Returns the Unicode of the character at the specified index.
string.concat
Joins two or more strings, and returns a new joined strings.
string.contains
Returns whether the string contains the specified substring.
string.copy
Copies the string.
string.endswith
Returns whether the string ends with the specified substring.
string.from
Creates a string from a list of values.
string.fromcharcode
Creates a string from a list of Unicode values.
string.indexof
Returns the index of the first occurrence of a substring in the string.
string.isempty
Returns whether the string is empty.
string.join
Joins all elements of a string into a string.
string.lastindexof
Returns the index of the last occurrence of a substring in the string.
string.length
Returns the length of the string.
string.lower
Returns the string converted to lower case.
string.new
Creates a new string.
string.replace
Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
string.split
Splits a string into an array of substrings.
string.startswith
Returns whether the string starts with the specified substring.
string.substr
Extracts the characters from a string, between two specified indices.
string.trim
Removes whitespace from both ends of a string.
string.upper
Returns the string converted to upper case.
Pine Script™ Time
The following functions are available for time.
Function
Description
time.dayofmonth
Returns the day of the month.
time.dayofweek
Returns the day of the week.
time.dayofyear
Returns the day of the year.
time.hour
Returns the hour.
time.isdst
Returns whether daylight saving time is in effect.
time.millisecond
Returns the millisecond.
time.minute
Returns the minute.
time.month
Returns the month.
time.second
Returns the second.
time.timezone
Returns the time zone.
time.tzoffset
Returns the time zone offset.
time.year
Returns the year.
notes about pine script:
Storage methods:
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<" TYPE ">" or "array<" TYPE ">"
- 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<" TYPE ">" or "array<" TYPE ">"
- 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 ">"
- storage types can not be:
- TYPE "[]" "[]"
- "matrix<" TYPE ">" "[]"
- "array<" TYPE ">" "[]"
- "matrix<" TYPE ">" "matrix<" TYPE ">"
- "array<" TYPE ">" "matrix<" TYPE ">"
- "matrix<" TYPE ">" "array<" TYPE ">"
- "array<" TYPE ">" "array<" TYPE ">"
default values
- values can be:
- a number
- a string
- a boolean
- na
- a system variable
- values cannot be:
- a list of values
- a function
- a UDT
A <local_block> is zero or more Pine Script™ statements.
The <function_result> is a variable, an expression, or a tuple.
EXAMPLE
//@version=5
indicator("=>")
// single-line function
f1(x, y) => x + y
// multi-line function
f2(x, y) =>
sum = x + y
sumChange = ta.change(sum, 10)
// Function automatically returns the last expression used in it
plot(f1(30, 8) + f2(1, 3))
>
DESCRIPTION
Greater than. Applicable to numerical expressions.
expr1 > expr2
RETURNS
Boolean value, or series of boolean values.
>=
DESCRIPTION
Greater than or equal to. Applicable to numerical expressions.
expr1 >= expr2
RETURNS
Boolean value, or series of boolean values.
?:
DESCRIPTION
Ternary conditional operator.
expr1 ? expr2 : expr3
EXAMPLE
//@version=5
indicator("?:")
// Draw circles at the bars where open crosses close
s2 = ta.cross(open, close) ? math.avg(open,close) : na
plot(s2, style=plot.style_circles, linewidth=2, color=color.red)
// Combination of ?: operators for 'switch'-like logic
c = timeframe.isintraday ? color.red : timeframe.isdaily ? color.green : timeframe.isweekly ? color.blue : color.gray
plot(hl2, color=c)
RETURNS
expr2 if expr1 is evaluated to true, expr3 otherwise. Zero value (0 and also NaN, +Infinity, -Infinity) is considered to be false, any other value is true.
You can combine two or more ?:.
You may use arithmetic operators with numbers as well as with series variables. In case of usage with series the operators are applied elementwise.
[]
DESCRIPTION
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.
expr1[expr2]
EXAMPLE
//@version=5
indicator("[]")
// [] can be used to "save" variable value between bars
a = 0.0 // declare `a`
a := a[1] // immediately set current value to the same as previous. `na` in the beginning of history
if high == low // if some condition - change `a` value to another
a := low
plot(a)
RETURNS
A series of values.
and
DESCRIPTION
Logical AND. Applicable to boolean expressions.
expr1 and expr2
RETURNS
Boolean value, or series of boolean values.
array
DESCRIPTION
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 function.
EXAMPLE
//@version=5
indicator("array", overlay=true)
array<float> a = na
a := array.new<float>(1, close)
plot(array.get(a, 0))
bool
DESCRIPTION
Keyword used to explicitly declare the "bool" (boolean) type of a variable or a parameter. "Bool" variables can have values true.
EXAMPLE
//@version=5
indicator("bool")
bool b = true // Same as `b = true`
b := na
plot(b ? open : close)
box
DESCRIPTION
Keyword used to explicitly declare the "box" type of a variable or a parameter. Box objects (or IDs) can be created with the box.new function.
EXAMPLE
//@version=5
indicator("box")
// Empty `box1` box ID.
var box box1 = na
// `box` type is unnecessary because `box.new()` returns a "box" type.
var box2 = box.new(na, na, na, na)
box3 = box.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time)
color
DESCRIPTION
Keyword used to explicitly declare the "color" type of a variable or a parameter.
EXAMPLE
//@version=5
indicator("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 for the type can be omitted.
c = color.rgb(0,255,0,0)
plot(close, color = c)
Explicitly mentioning the type in a variable declaration is optional, except when it is initialized with na.
export
DESCRIPTION
Used in libraries to prefix the declaration of functions or user-defined type definitions that will be available from other scripts importing the library.
EXAMPLE
//@version=5
//@description Library of debugging functions.
library("Debugging_library", overlay = true)
//@function Displays a string as a table cell for debugging purposes.
//@param txt String to display.
//@returns Void.
export print(string txt) =>
var table t = table.new(position.middle_right, 1, 1)
table.cell(t, 0, 0, txt, bgcolor = color.yellow)
// Using the function from inside the library to show an example on the published chart.
// This has no impact on scripts using the library.
print("Library Test")
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 in the function's signature.
The @description, @function, @param, @type, @field, and @returns compiler annotations are used to automatically generate the library's description and release notes, and in the Pine Script™ Editor's tooltips.
false
DESCRIPTION
Literal representing a bool value, and result of a comparison operation.
float
DESCRIPTION
Keyword used to explicitly declare the "float" (floating point) type of a variable or a parameter.
EXAMPLE
//@version=5
indicator("float")
float f = 3.14 // Same as `f = 3.14`
f := na
plot(f)
for
DESCRIPTION
The 'for' structure allows the repeated execution of a number of statements:
[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=5
indicator("`for` loop with a step")
a = array.from(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
sum = 0.0
for i = 0 to 9 by 5
// Because the step is set to 5, we are adding only the first (0) and the sixth (5) value from the array `a`.
sum += array.get(a, i)
plot(sum)
for...in
DESCRIPTION
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.
[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=5
indicator("for...in")
// Here we determine on each bar how many of the bar's OHLC values are greater than the SMA of 'close' values
float[] ohlcValues = array.from(open, high, low, close)
qtyGreaterThan(value, array) =>
int result = 0
for currentElement in array
if currentElement > value
result += 1
result
plot(qtyGreaterThan(ta.sma(close, 20), ohlcValues))
Here, we use the two-argument form of for...in to set the values of our isPos array to true when their corresponding value in our valuesArray array is positive:
EXAMPLE
//@version=5
indicator("for...in")
var valuesArray = array.from(4, -8, 11, 78, -16, 34, 7, 99, 0, 55)
var isPos = array.new_bool(10, false)
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.
EXAMPLE
//@version=5
indicator("`for ... in` matrix Example")
// Create a 2x3 matrix with values `4`.
matrix1 = matrix.new<int>(2, 3, 4)
sum = 0.0
// Loop through every row of the matrix.
for rowArray in matrix1
// Sum values of the every row
sum += array.sum(rowArray)
plot(sum)
if
DESCRIPTION
If statement defines what block of statements must be executed when conditions of the expression are satisfied.
To have access to and use the if statement, one should specify the version >= 2 of Pine Script™ language in the very first line of code, for example: //@version=5
The 4th version of Pine Script™ Language allows you to use “else if” syntax.
General code form:
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 — this variable gets the value of the if statement
condition — if the condition is true, the logic from the block 'then' (var_decl_then0, var_decl_then1, etc.) is used.
If the condition is false, the logic from the block 'else' (var_decl_else0, var_decl_else1, etc.) is used.
return_expression_then, return_expression_else — the last expression from the block then or from the block else will return the final value of the statement. If declaration of the variable is in the end, its value will be the result.
The type of returning value of the if statement depends on return_expression_then and return_expression_else type (their types must match: it is not possible to return an integer value from then, while you have a string value in else block).
EXAMPLE
//@version=5
indicator("if")
// This code compiles
x = if close > open
close
else
open
// This code doesn’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 “empty” value (na, false, or “”) will be assigned to the var_declarationX variable:
EXAMPLE
//@version=5
indicator("if")
x = if close > open
close
// If current close > current open, then x = close.
// Otherwise the x = na.
plot(x)
It is possible to use either multiple “else if” blocks or none at all. The blocks “then”, “else if”, “else” are shifted by four spaces:
EXAMPLE
//@version=5
indicator("if")
x = if open > close
5
else if high > low
close
else
open
plot(x)
It is possible to ignore the resulting value of an if statement (“var_declarationX=“ can be omitted). It may be useful if you need the side effect of the expression, for example in strategy trading:
//@version=5
indicator("if")
float x = na
if close > open
if close > close[1]
x := close
else
x := close[1]
else
x := open
plot(x)
import
DESCRIPTION
Used to load an external library before it can be imported.
import {username}/{libraryName}/{libraryVersion} as {alias}
EXAMPLE
//@version=5
indicator("num_methods import")
// Import the first version of the username’s "num_methods" library and assign it to the "m" namespace",
import username/num_methods/1 as m
// Call the “sinh()” function from the imported library
y = m.sinh(3.14)
// Plot value returned by the "sinh()" function",
plot(y)
ARGUMENTS
username (literal string) User name of the library's author.
libraryName (literal string) Name of the imported library, which corresponds to the title argument used by the author in his library script.
libraryVersion (literal int) Version number of the imported library.
alias (literal string) Namespace used to refer to the library's functions. Optional. The default is the libraryName string.
int
DESCRIPTION
Keyword used to explicitly declare the "int" (integer) type of a variable or a parameter.
EXAMPLE
//@version=5
indicator("int")
int i = 14 // Same as `i = 14`
i := na
plot(i)
label
DESCRIPTION
Keyword used to explicitly declare the "label" type of a variable or a parameter. Label objects (or IDs) can be created with the label.new function.
EXAMPLE
//@version=5
indicator("label")
// Empty `label1` label ID.
var label label1 = na
// `label` type is unnecessary because `label.new()` returns "label" type.
var label2 = label.new(na, na, na)
if barstate.islastconfirmedhistory
label3 = label.new(bar_index, high, text = "label3 text")
line
DESCRIPTION
Keyword used to explicitly declare the "line" type of a variable or a parameter. Line objects (or IDs) can be created with the line.new function.
EXAMPLE
//@version=5
indicator("line")
// Empty `line1` line ID.
var line line1 = na
// `line` type is unnecessary because `line.new()` returns "line" type.
var line2 = line.new(na, na, na, na)
line3 = line.new(bar_index - 1, high, bar_index, high, extend = extend.right)
linefill
DESCRIPTION
Keyword used to explicitly declare the "linefill" type of a variable or a parameter. Linefill objects (or IDs) can be created with the linefill.new function.
EXAMPLE
//@version=5
indicator("linefill", overlay=true)
// Empty `linefill1` line ID.
var linefill linefill1 = na
// `linefill` type is unnecessary because `linefill.new()` returns "linefill" type.
var linefill2 = linefill.new(na, na, na)
if barstate.islastconfirmedhistory
line1 = line.new(bar_index - 10, high+1, bar_index, high+1, extend = extend.right)
line2 = line.new(bar_index - 10, low+1, bar_index, low+1, extend = extend.right)
linefill3 = linefill.new(line1, line2, color = color.new(color.green, 80))
matrix
DESCRIPTION
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=5
indicator("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))
method
DESCRIPTION
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
indicator("")
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 for its first parameter.
// maintainArray(prices, 50, close)
// This calls the `array.avg()` built-in using dot notation with the `prices` array.
// It is possible because built-in functions belonging to some namespaces that are a special Pine type
// can be invoked with method notation when the function's first parameter is an ID of that type.
// Those namespaces are: `array`, `matrix`, `line`, `linefill`, `label`, `box`, and `table`.
plot(prices.avg())
not
DESCRIPTION
Logical negation (NOT). Applicable to boolean expressions.
not expr1
RETURNS
Boolean value, or series of boolean values.
or
DESCRIPTION
Logical OR. Applicable to boolean expressions.
expr1 or expr2
RETURNS
Boolean value, or series of boolean values.
series
DESCRIPTION
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=5
//@description Library of debugging functions.
library("Debugging_library", overlay = true)
export smaCustom(series float source, series int length) =>
ta.sma(source, length)
simple
DESCRIPTION
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=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 for its `length` parameter.
ta.ema(source, length)
string
DESCRIPTION
Keyword used to explicitly declare the "string" type of a variable or a parameter.
EXAMPLE
//@version=5
indicator("string")
string s = "Hello World!" // Same as `s = "Hello world!"`
// string s = na // same as ""
plot(na, title=s)
switch
DESCRIPTION
The switch operator transfers control to one of the several statements, depending on the values of a condition and expressions.
//@version=5
indicator("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)
The value of the last expression in the local block of statements that is executed.
table
DESCRIPTION
Keyword used to explicitly declare the "table" type of a variable or a parameter. Table objects (or IDs) can be created with the table.new function.
EXAMPLE
//@version=5
indicator("table")
// Empty `table1` table ID.
var table table1 = na
// `table` type is unnecessary because `table.new()` returns "table" type.
var table2 = table.new(position.top_left, na, na)
if barstate.islastconfirmedhistory
var table3 = table.new(position = position.top_right, columns = 1, rows = 1, bgcolor = color.yellow, border_width = 1)
table.cell(table_id = table3, column = 0, row = 0, text = "table3 text")
true
DESCRIPTION
Literal representing one of the values a bool variable can hold, or an expression can evaluate to when it uses comparison or logical operators.
type
DESCRIPTION
This keyword allows you to declare a user-defined type (UDT) from which objects can be created. UDTs are composite types; they contain an arbitrary number of fields that can be of any type, including the UDT being defined. The syntax to define a UDT is:
Once a UDT is defined, objects can be created from it by using the UDT_identifier.new() construct. When creating a new object, its fields are initialized with their default value if one was specified in the UDT's definition, or na` where "foo" is the name of a previously defined UDT and "x" is one of its fields of "bool" type.
For more information see the User Manual's sections on defining UDTs.
UDTs can be exported from libraries. See the User Manual's page on Libraries.
EXAMPLE
//@version=5
indicator("Multi Time Period Chart", overlay = true)
timeframeInput = input.timeframe("1D")
type bar
float o = open
float h = high
float l = low
float c = close
int t = time
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())
if not na(secBar)
// To avoid a runtime error, only process data when an object exists.
if not barstate.islast
if timeframe.change(timeframeInput)
// On historical bars, draw a new box in the past when the HTF closes.
drawBox(secBar, time[1])
else
var box lastBox = na
if na(lastBox) or timeframe.change(timeframeInput)
// On the last bar, only draw a new current box the first time we get there or when HTF changes.
lastBox := drawBox(secBar, time)
else
// On other chart updates, use setters to modify the current box.
updateBox(lastBox, secBar)
var
DESCRIPTION
var is the keyword used for assigning and one-time initializing of the variable.
Normally, a syntax of assignment of variables, which doesn’t include the keyword var, results in the value of the variable being overwritten with every update of the data. Contrary to that, when assigning variables with the keyword var, they can “keep the state” despite the data updating, only changing it when conditions within if-expressions are met.
var variable_name = expression
where:
variable_name - any name of the user’s variable that’s allowed in Pine Script™ (can contain capital and lowercase Latin characters, numbers, and underscores (_), but can’t start with a number).
expression - any arithmetic expression, just as with defining a regular variable. The expression will be calculated and assigned to a variable once.
EXAMPLE
//@version=5
indicator("Var keyword example")
var a = close
var b = 0.0
var c = 0.0
var green_bars_count = 0
if close > open
var x = close
b := x
green_bars_count := green_bars_count + 1
if green_bars_count >= 10
var y = close
c := y
plot(a)
plot(b)
plot(c)
The variable 'a' keeps the closing price of the first bar for each bar in the series.
The variable 'b' keeps the closing price of the first "green" bar in the series.
The variable 'c' keeps the closing price of the tenth "green" bar in the series.
varip
DESCRIPTION
varip (var intrabar persist) is the keyword used for assigning and one-time initializing of a variable. It is similar to the var keyword, but variables declared with varip retain their values between the updates of a real-time bar.
varip variable_name = expression
where:
variable_name - any name of the user's variable that's allowed in Pine Script™ (can contain capital and lowercase Latin characters, numbers, and underscores (_), but can't start with a number).
expression - any arithmetic expression, just as when defining a regular variable. The expression will be calculated and assigned to the variable only once, on the first bar.
EXAMPLE
//@version=5
indicator("varip")
varip int v = -1
v := v + 1
plot(v)
With var, the plot would return the value of bar_index. With varip, the same behavior occurs on historical bars, but in the real-time bar, the plot returns a value that increases by one for each tick.
while
DESCRIPTION
The while statement allows the conditional iteration of a local code block.
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=5
indicator("while")
// This is a simple example of calculating a factorial using a while loop.
int i_n = input.int(10, "Factorial Size", minval=0)
int counter = i_n
int factorial = 1
while counter > 0
factorial := factorial * counter
counter := counter - 1
plot(factorial)
Constant for dividends adjustment type (dividends adjustment is applied).
TYPE
const string
adjustment.none
DESCRIPTION
Constant for none adjustment type (no adjustment is applied).
TYPE
const string
adjustment.splits
DESCRIPTION
Constant for splits adjustment type (splits adjustment is applied).
TYPE
const string
alert.freq_all
DESCRIPTION
A named constant for use with the freq parameter of the alert() function.
All function calls trigger the alert.
TYPE
const string
alert.freq_once_per_bar
DESCRIPTION
A named constant for use with the freq parameter of the alert() function.
The first function call during the bar triggers the alert.
TYPE
const string
alert.freq_once_per_bar_close
DESCRIPTION
A named constant for use with the freq parameter of the alert() function.
The function call triggers the alert only when it occurs during the last script iteration of the real-time bar, when it closes.
TYPE
const string
bar_index
DESCRIPTION
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)
Note that bar indexing starts from 0 on the first historical bar.
Please note that using this variable/function can cause indicator repainting.
barmerge.gaps_off
DESCRIPTION
Merge strategy for requested data. Data is merged continuously without gaps, all the gaps are filled with the previous nearest existing value.
TYPE
barmerge_gaps
barmerge.gaps_on
DESCRIPTION
Merge strategy for requested data. Data is merged with possible gaps ([na.
TYPE
barmerge_gaps
barmerge.lookahead_off
DESCRIPTION
Merge strategy for the requested data position. Requested barset is merged with current barset in the order of sorting bars by their close time. This merge strategy disables effect of getting data from "future" on calculation on history.
TYPE
barmerge_lookahead
barmerge.lookahead_on
DESCRIPTION
Merge strategy for the requested data position. Requested barset is merged with current barset in the order of sorting bars by their opening time. This merge strategy can lead to undesirable effect of getting data from "future" on calculation on history. This is unacceptable in backtesting strategies, but can be useful in indicators.
TYPE
barmerge_lookahead
barstate.isconfirmed
DESCRIPTION
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
It is NOT recommended to use barstate.isconfirmed is unpredictable.
Please note that using this variable/function can cause indicator repainting.
barstate.isfirst
DESCRIPTION
Returns true if current bar is first bar in barset, false otherwise.
TYPE
series bool
Please note that using this variable/function can cause indicator repainting.
barstate.ishistory
DESCRIPTION
Returns true if current bar is a historical bar, false otherwise.
TYPE
series bool
Please note that using this variable/function can cause indicator repainting.
barstate.islast
DESCRIPTION
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
Please note that using this variable/function can cause indicator repainting.
barstate.islastconfirmedhistory
DESCRIPTION
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
Please note that using this variable/function can cause indicator repainting.
barstate.isnew
DESCRIPTION
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
Please note that using this variable/function can cause indicator repainting.
barstate.isrealtime
DESCRIPTION
Returns true if current bar is a real-time bar, false otherwise.
TYPE
series bool
Please note that using this variable/function can cause indicator repainting.
box.all
DESCRIPTION
Returns an array filled with all the current boxes drawn by the script.
TYPE
box[]
EXAMPLE
//@version=5
indicator("box.all")
//delete all boxes
box.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, border_style=line.style_dashed)
a_allBoxes = box.all
if array.size(a_allBoxes) > 0
for i = 0 to array.size(a_allBoxes) - 1
box.delete(array.get(a_allBoxes, i))
chart.bg_color
DESCRIPTION
Returns the color of the chart's background from the "Chart settings/Appearance/Background" field. When a gradient is selected, the middle point of the gradient is returned.
TYPE
input color
chart.fg_color
DESCRIPTION
Returns a color providing optimal contrast with chart.bg_color.
TYPE
input color
chart.is_heikinashi
DESCRIPTION
TYPE
simple bool
RETURNS
Returns true otherwise.
chart.is_kagi
DESCRIPTION
TYPE
simple bool
RETURNS
Returns true otherwise.
chart.is_linebreak
DESCRIPTION
TYPE
simple bool
RETURNS
Returns true otherwise.
chart.is_pnf
DESCRIPTION
TYPE
simple bool
RETURNS
Returns true otherwise.
chart.is_range
DESCRIPTION
TYPE
simple bool
RETURNS
Returns true otherwise.
chart.is_renko
DESCRIPTION
TYPE
simple bool
RETURNS
Returns true otherwise.
chart.is_standard
DESCRIPTION
TYPE
simple bool
RETURNS
Returns true otherwise.
chart.left_visible_bar_time
DESCRIPTION
The time of the leftmost bar currently visible on the chart.
TYPE
input int
chart.right_visible_bar_time
DESCRIPTION
The time of the rightmost bar currently visible on the chart.
TYPE
input int
close
DESCRIPTION
Close price of the current bar when it has closed, or last traded price of a yet incomplete, realtime bar.
TYPE
series float
color.aqua
DESCRIPTION
Is a named constant for #00BCD4 color.
TYPE
const color
color.black
DESCRIPTION
Is a named constant for #363A45 color.
TYPE
const color
color.blue
DESCRIPTION
Is a named constant for #2962ff color.
TYPE
const color
color.fuchsia
DESCRIPTION
Is a named constant for #E040FB color.
TYPE
const color
color.gray
DESCRIPTION
Is a named constant for #787B86 color.
TYPE
const color
color.green
DESCRIPTION
Is a named constant for #4CAF50 color.
TYPE
const color
color.lime
DESCRIPTION
Is a named constant for #00E676 color.
TYPE
const color
color.maroon
DESCRIPTION
Is a named constant for #880E4F color.
TYPE
const color
color.navy
DESCRIPTION
Is a named constant for #311B92 color.
TYPE
const color
color.olive
DESCRIPTION
Is a named constant for #808000 color.
TYPE
const color
color.orange
DESCRIPTION
Is a named constant for #FF9800 color.
TYPE
const color
color.purple
DESCRIPTION
Is a named constant for #9C27B0 color.
TYPE
const color
color.red
DESCRIPTION
Is a named constant for #FF5252 color.
TYPE
const color
color.silver
DESCRIPTION
Is a named constant for #B2B5BE color.
TYPE
const color
color.teal
DESCRIPTION
Is a named constant for #00897B color.
TYPE
const color
color.white
DESCRIPTION
Is a named constant for #FFFFFF color.
TYPE
const color
color.yellow
DESCRIPTION
Is a named constant for #FFEB3B color.
TYPE
const color
currency.AUD
DESCRIPTION
Australian dollar.
TYPE
const string
currency.BTC
DESCRIPTION
Bitcoin.
TYPE
const string
currency.CAD
DESCRIPTION
Canadian dollar.
TYPE
const string
currency.CHF
DESCRIPTION
Swiss franc.
TYPE
const string
currency.ETH
DESCRIPTION
Ethereum.
TYPE
const string
currency.EUR
DESCRIPTION
Euro.
TYPE
const string
currency.GBP
DESCRIPTION
Pound sterling.
TYPE
const string
currency.HKD
DESCRIPTION
Hong Kong dollar.
TYPE
const string
currency.INR
DESCRIPTION
Indian rupee.
TYPE
const string
currency.JPY
DESCRIPTION
Japanese yen.
TYPE
const string
currency.KRW
DESCRIPTION
South Korean won.
TYPE
const string
currency.MYR
DESCRIPTION
Malaysian ringgit.
TYPE
const string
currency.NOK
DESCRIPTION
Norwegian krone.
TYPE
const string
currency.NONE
DESCRIPTION
Unspecified currency.
TYPE
const string
currency.NZD
DESCRIPTION
New Zealand dollar.
TYPE
const string
currency.RUB
DESCRIPTION
Russian ruble.
TYPE
const string
currency.SEK
DESCRIPTION
Swedish krona.
TYPE
const string
currency.SGD
DESCRIPTION
Singapore dollar.
TYPE
const string
currency.TRY
DESCRIPTION
Turkish lira.
TYPE
const string
currency.USD
DESCRIPTION
United States dollar.
TYPE
const string
currency.USDT
DESCRIPTION
Tether.
TYPE
const string
currency.ZAR
DESCRIPTION
South African rand.
TYPE
const string
dayofmonth
DESCRIPTION
Date of current bar time in exchange timezone.
TYPE
series int
dayofweek
DESCRIPTION
Day of week for current bar time in exchange timezone.
TYPE
series int
You can use dayofweek.sunday variables for comparisons.
dayofweek.friday
DESCRIPTION
Is a named constant for return value of dayofweek variable.
TYPE
const int
dayofweek.monday
DESCRIPTION
Is a named constant for return value of dayofweek variable.
TYPE
const int
dayofweek.saturday
DESCRIPTION
Is a named constant for return value of dayofweek variable.
TYPE
const int
dayofweek.sunday
DESCRIPTION
Is a named constant for return value of dayofweek variable.
TYPE
const int
dayofweek.thursday
DESCRIPTION
Is a named constant for return value of dayofweek variable.
TYPE
const int
dayofweek.tuesday
DESCRIPTION
Is a named constant for return value of dayofweek variable.
TYPE
const int
dayofweek.wednesday
DESCRIPTION
Is a named constant for return value of dayofweek variable.
TYPE
const int
display.all
DESCRIPTION
A named argument for use with the display parameter. Displays everywhere.
TYPE
plot_simple_display
display.data_window
DESCRIPTION
A named argument for use with the display parameter. Displays the plot values in the Data Window, a menu available in the chart's right sidebar.
TYPE
plot_display
display.none
DESCRIPTION
A named argument for use with the display parameter. Causes no plot values to be displayed. The plotted values can nonetheless be used in alert template messages, and will appear in exported chart data.
TYPE
plot_simple_display
display.pane
DESCRIPTION
A named argument for use with the display parameter. Displays the plot in the pane used by the script, as defined with the indicator declaration statement's overlay parameter.
TYPE
plot_display
display.price_scale
DESCRIPTION
A named argument for use with the display parameter. Controls the display of the plot's label and price in the price scale, if the chart's settings allow them.
TYPE
plot_display
display.status_line
DESCRIPTION
A named argument for use with the display parameter. Displays the plot values in the script's status line, next to the script's name on the chart, if the chart's settings allow them.
TYPE
plot_display
dividends.gross
DESCRIPTION
A named constant for the request.dividends function. Is used to request the dividends return on a stock before deductions.
TYPE
const string
dividends.net
DESCRIPTION
A named constant for the request.dividends function. Is used to request the dividends return on a stock after deductions.
TYPE
const string
earnings.actual
DESCRIPTION
A named constant for the request.earnings function. Is used to request the earnings value as it was reported.
TYPE
const string
earnings.estimate
DESCRIPTION
A named constant for the request.earnings function. Is used to request the estimated earnings value.
TYPE
const string
earnings.standardized
DESCRIPTION
A named constant for the request.earnings function. Is used to request the standardized earnings value.
TYPE
const string
extend.both
DESCRIPTION
A named constant for line.new functions.
TYPE
const string
extend.left
DESCRIPTION
A named constant for line.new functions.
TYPE
const string
extend.none
DESCRIPTION
A named constant for line.new functions.
TYPE
const string
extend.right
DESCRIPTION
A named constant for line.new functions.
TYPE
const string
font.family_default
DESCRIPTION
Default text font for box.new functions.
TYPE
const string
font.family_monospace
DESCRIPTION
Monospace text font for box.new functions.
TYPE
const string
format.inherit
DESCRIPTION
Is a named constant for selecting the formatting of the script output values from the parent series in the indicator function.
TYPE
const string
format.mintick
DESCRIPTION
Is a named constant to use with the str.tostring, without the remainder, with ties rounding up, and returns the string version of said value with trailing zeroes.
TYPE
const string
format.percent
DESCRIPTION
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
format.price
DESCRIPTION
Is a named constant for selecting the formatting of the script output values as prices in the indicator function.
TYPE
const string
format.volume
DESCRIPTION
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'.
TYPE
const string
high
DESCRIPTION
Current high price.
TYPE
series float
hl2
DESCRIPTION
Is a shortcut for (high + low)/2
TYPE
series float
hlc3
DESCRIPTION
Is a shortcut for (high + low + close)/3
TYPE
series float
hlcc4
DESCRIPTION
Is a shortcut for (high + low + close + close)/4
TYPE
series float
hline.style_dashed
DESCRIPTION
Is a named constant for dashed linestyle of hline function.
TYPE
hline_style
hline.style_dotted
DESCRIPTION
Is a named constant for dotted linestyle of hline function.
TYPE
hline_style
hline.style_solid
DESCRIPTION
Is a named constant for solid linestyle of hline function.
TYPE
hline_style
hour
DESCRIPTION
Current bar hour in exchange timezone.
TYPE
series int
label.all
DESCRIPTION
Returns an array filled with all the current labels drawn by the script.
TYPE
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))
label.style_arrowdown
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_arrowup
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_circle
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_cross
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_diamond
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_flag
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_center
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_down
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_left
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_lower_left
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_lower_right
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_right
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_up
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_upper_left
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_upper_right
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_none
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_square
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_text_outline
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_triangledown
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_triangleup
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_xcross
DESCRIPTION
Label style for label.new functions.
TYPE
const string
last_bar_index
DESCRIPTION
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.
last_bar_time
DESCRIPTION
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
Note that this variable returns the timestamp based on the time of the bar's open.
line.all
DESCRIPTION
Returns an array filled with all the current lines drawn by the script.
TYPE
line[]
EXAMPLE
//@version=5
indicator("line.all")
//delete all lines
line.new(bar_index - 10, close, bar_index, close)
a_allLines = line.all
if array.size(a_allLines) > 0
for i = 0 to array.size(a_allLines) - 1
line.delete(array.get(a_allLines, i))
line.style_arrow_both
DESCRIPTION
Line style for line.new functions. Solid line with arrows on both points.
TYPE
const string
line.style_arrow_left
DESCRIPTION
Line style for line.new functions. Solid line with arrow on the first point.
TYPE
const string
line.style_arrow_right
DESCRIPTION
Line style for line.new functions. Solid line with arrow on the second point.
TYPE
const string
line.style_dashed
DESCRIPTION
Line style for line.new functions.
TYPE
const string
line.style_dotted
DESCRIPTION
Line style for line.new functions.
TYPE
const string
line.style_solid
DESCRIPTION
Line style for line.new functions.
TYPE
const string
linefill.all
DESCRIPTION
Returns an array filled with all the current linefill objects drawn by the script.
TYPE
linefill[]
location.abovebar
DESCRIPTION
Location value for plotshape functions. Shape is plotted above main series bars.
TYPE
const string
location.absolute
DESCRIPTION
Location value for plotshape functions. Shape is plotted on chart using indicator value as a price coordinate.
TYPE
const string
location.belowbar
DESCRIPTION
Location value for plotshape functions. Shape is plotted below main series bars.
TYPE
const string
location.bottom
DESCRIPTION
Location value for plotshape functions. Shape is plotted near the bottom chart border.
TYPE
const string
location.top
DESCRIPTION
Location value for plotshape functions. Shape is plotted near the top chart border.
TYPE
const string
low
DESCRIPTION
Current low price.
TYPE
series float
math.e
DESCRIPTION
Is a named constant for Euler's number. It is equal to 2.7182818284590452.
TYPE
const float
math.phi
DESCRIPTION
Is a named constant for the golden ratio. It is equal to 1.6180339887498948.
TYPE
const float
math.pi
DESCRIPTION
Is a named constant for Archimedes' constant. It is equal to 3.1415926535897932.
TYPE
const float
math.rphi
DESCRIPTION
Is a named constant for the golden ratio conjugate. It is equal to 0.6180339887498948.
TYPE
const float
minute
DESCRIPTION
Current bar minute in exchange timezone.
TYPE
series int
month
DESCRIPTION
Current bar month in exchange timezone.
TYPE
series int
na
DESCRIPTION
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))
ohlc4
DESCRIPTION
Is a shortcut for (open + high + low + close)/4
TYPE
series float
open
DESCRIPTION
Current open price.
TYPE
series float
order.ascending
DESCRIPTION
Determines the sort order of the array from the smallest to the largest value.
TYPE
sort_order
order.descending
DESCRIPTION
Determines the sort order of the array from the largest to the smallest value.
TYPE
sort_order
plot.style_area
DESCRIPTION
A named constant for the 'Area' style, to be used as an argument for the style parameter in the plot function.
TYPE
plot_style
plot.style_areabr
DESCRIPTION
A named constant for the 'Area With Breaks' style, to be used as an argument for the style parameter in the plot, except the gaps in the data are not filled.
TYPE
plot_style
plot.style_circles
DESCRIPTION
A named constant for the 'Circles' style, to be used as an argument for the style parameter in the plot function.
TYPE
plot_style
plot.style_columns
DESCRIPTION
A named constant for the 'Columns' style, to be used as an argument for the style parameter in the plot function.
TYPE
plot_style
plot.style_cross
DESCRIPTION
A named constant for the 'Cross' style, to be used as an argument for the style parameter in the plot function.
TYPE
plot_style
plot.style_histogram
DESCRIPTION
A named constant for the 'Histogram' style, to be used as an argument for the style parameter in the plot function.
TYPE
plot_style
plot.style_line
DESCRIPTION
A named constant for the 'Line' style, to be used as an argument for the style parameter in the plot function.
TYPE
plot_style
plot.style_linebr
DESCRIPTION
A named constant for the 'Line With Breaks' style, to be used as an argument for the style parameter in the plot, except the gaps in the data are not filled.
TYPE
plot_style
plot.style_stepline
DESCRIPTION
A named constant for the 'Step Line' style, to be used as an argument for the style parameter in the plot function.
TYPE
plot_style
plot.style_stepline_diamond
DESCRIPTION
A named constant for the 'Step Line With Diamonds' style, to be used as an argument for the style parameter in the plot, except the data changes are also marked with the Diamond shapes.
TYPE
plot_style
plot.style_steplinebr
DESCRIPTION
A named constant for the 'Step line with Breaks' style, to be used as an argument for the style parameter in the plot function.
TYPE
plot_style
position.bottom_center
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the bottom edge in the center.
TYPE
const string
position.bottom_left
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the bottom left of the screen.
TYPE
const string
position.bottom_right
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the bottom right of the screen.
TYPE
const string
position.middle_center
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the center of the screen.
TYPE
const string
position.middle_left
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the left side of the screen.
TYPE
const string
position.middle_right
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the right side of the screen.
TYPE
const string
position.top_center
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the top edge in the center.
TYPE
const string
position.top_left
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the upper-left edge.
TYPE
const string
position.top_right
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the upper-right edge.
TYPE
const string
scale.left
DESCRIPTION
Scale value for indicator function. Indicator is added to the left price scale.
TYPE
scale_type
scale.none
DESCRIPTION
Scale value for indicator function. Indicator is added in 'No Scale' mode. Can be used only with 'overlay=true'.
TYPE
scale_type
scale.right
DESCRIPTION
Scale value for indicator function. Indicator is added to the right price scale.
TYPE
scale_type
second
DESCRIPTION
Current bar second in exchange timezone.
TYPE
series int
session.extended
DESCRIPTION
Constant for extended session type (with extended hours data).
TYPE
const string
session.isfirstbar
DESCRIPTION
Returns true on the first bar of the pre-market bars.
TYPE
series bool
session.isfirstbar_regular
DESCRIPTION
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
DESCRIPTION
Returns true on the last bar of the post-market bars.
TYPE
series bool
This variable is not guaranteed to work as expected on non-standard chart types, e.g., Renko.
session.islastbar_regular
DESCRIPTION
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
This variable is not guaranteed to work as expected on non-standard chart types, e.g., Renko.
session.ismarket
DESCRIPTION
Returns true if the current bar is a part of the regular trading hours (i.e. market hours), false otherwise
TYPE
series bool
session.ispostmarket
DESCRIPTION
Returns true if the current bar is a part of the post-market, false otherwise. On non-intraday charts always returns false.
TYPE
series bool
session.ispremarket
DESCRIPTION
Returns true if the current bar is a part of the pre-market, false otherwise. On non-intraday charts always returns false.
TYPE
series bool
session.regular
DESCRIPTION
Constant for regular session type (no extended hours data).
TYPE
const string
shape.arrowdown
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.arrowup
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.circle
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.cross
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.diamond
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.flag
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.labeldown
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.labelup
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.square
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.triangledown
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.triangleup
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.xcross
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
size.auto
DESCRIPTION
Size value for plotshape functions. The size of the shape automatically adapts to the size of the bars.
TYPE
const string
size.huge
DESCRIPTION
Size value for plotshape functions. The size of the shape constantly huge.
TYPE
const string
size.large
DESCRIPTION
Size value for plotshape functions. The size of the shape constantly large.
TYPE
const string
size.normal
DESCRIPTION
Size value for plotshape functions. The size of the shape constantly normal.
TYPE
const string
size.small
DESCRIPTION
Size value for plotshape functions. The size of the shape constantly small.
TYPE
const string
size.tiny
DESCRIPTION
Size value for plotshape functions. The size of the shape constantly tiny.
TYPE
const string
splits.denominator
DESCRIPTION
A named constant for the request.splits of a splits.
TYPE
const string
splits.numerator
DESCRIPTION
A named constant for the request.splits of a splits.
TYPE
const string
strategy.account_currency
DESCRIPTION
Returns the currency used to calculate results, which can be set in the strategy's properties.
TYPE
simple string
strategy.cash
DESCRIPTION
This is one of the arguments that can be supplied to the default_qty_type parameter in the strategy function calls. It specifies that an amount of cash in the strategy.account_currency will be used to enter trades.
TYPE
const string
EXAMPLE
//@version=5
strategy("strategy.cash", overlay = true, default_qty_value = 50, default_qty_type = strategy.cash, initial_capital = 1000000)
if bar_index == 0
// As ‘qty’ is not defined, the previously defined values for the `default_qty_type` 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")
strategy.closedtrades
DESCRIPTION
Number of trades, which were closed for the whole trading interval.
TYPE
series int
strategy.commission.cash_per_contract
DESCRIPTION
Commission type for an order. Money displayed in the account currency per contract.
TYPE
const string
strategy.commission.cash_per_order
DESCRIPTION
Commission type for an order. Money displayed in the account currency per order.
TYPE
const string
strategy.commission.percent
DESCRIPTION
Commission type for an order. A percentage of the cash volume of order.
TYPE
const string
strategy.direction.all
DESCRIPTION
It allows strategy to open both long and short positions.
TYPE
const string
strategy.direction.long
DESCRIPTION
It allows strategy to open only long positions.
TYPE
const string
strategy.direction.short
DESCRIPTION
It allows strategy to open only short positions.
TYPE
const string
strategy.equity
DESCRIPTION
Current equity ([strategy.initial_capital.
TYPE
series float
strategy.eventrades
DESCRIPTION
Number of breakeven trades for the whole trading interval.
TYPE
series int
strategy.fixed
DESCRIPTION
This is one of the arguments that can be supplied to the default_qty_type parameter in the strategy function calls. It specifies that a number of contracts/shares/lots will be used to enter trades.
TYPE
const string
EXAMPLE
//@version=5
strategy("strategy.fixed", overlay = true, default_qty_value = 50, default_qty_type = strategy.fixed, initial_capital = 1000000)
if bar_index == 0
// As ‘qty’ is not defined, the previously defined values for the `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")
strategy.grossloss
DESCRIPTION
Total currency value of all completed losing trades.
TYPE
series float
strategy.grossprofit
DESCRIPTION
Total currency value of all completed winning trades.
TYPE
series float
strategy.initial_capital
DESCRIPTION
The amount of initial capital set in the strategy properties.
TYPE
series float
strategy.long
DESCRIPTION
Long position entry.
TYPE
strategy_direction
strategy.losstrades
DESCRIPTION
Number of unprofitable trades for the whole trading interval.
TYPE
series int
strategy.max_contracts_held_all
DESCRIPTION
Maximum number of contracts/shares/lots/units in one trade for the whole trading interval.
TYPE
series float
strategy.max_contracts_held_long
DESCRIPTION
Maximum number of contracts/shares/lots/units in one long trade for the whole trading interval.
TYPE
series float
strategy.max_contracts_held_short
DESCRIPTION
Maximum number of contracts/shares/lots/units in one short trade for the whole trading interval.
TYPE
series float
strategy.max_drawdown
DESCRIPTION
Maximum equity drawdown value for the whole trading interval.
TYPE
series float
strategy.max_runup
DESCRIPTION
Maximum equity run-up value for the whole trading interval.
TYPE
series float
strategy.netprofit
DESCRIPTION
Total currency value of all completed trades.
TYPE
series float
strategy.oca.cancel
DESCRIPTION
OCA type value for strategy's functions. The parameter determines that an order should belong to an OCO group, where as soon as an order is filled, all other orders of the same group are cancelled. Note: if more than 1 guaranteed-to-be-executed orders of the same OCA group are placed at once, all those orders are filled.
TYPE
const string
strategy.oca.none
DESCRIPTION
OCA type value for strategy's functions. The parameter determines that an order should not belong to any particular OCO group.
TYPE
const string
strategy.oca.reduce
DESCRIPTION
OCA type value for strategy's functions. The parameter determines that an order should belong to an OCO group, where if X number of contracts of an order is filled, number of contracts for each other order of the same OCO group is decreased by X. Note: if more than 1 guaranteed-to-be-executed orders of the same OCA group are placed at once, all those orders are filled.
TYPE
const string
strategy.openprofit
DESCRIPTION
Current unrealized profit or loss for all open positions.
TYPE
series float
strategy.opentrades
DESCRIPTION
Number of market position entries, which were not closed and remain opened. If there is no open market position, 0 is returned.
TYPE
series int
strategy.percent_of_equity
DESCRIPTION
This is one of the arguments that can be supplied to the default_qty_type parameter in the strategy of equity will be used to enter trades.
TYPE
const string
EXAMPLE
//@version=5
strategy("strategy.percent_of_equity", overlay = false, default_qty_value = 100, default_qty_type = strategy.percent_of_equity, initial_capital = 1000000)
// As ‘qty’ is not defined, the previously defined values for the `default_qty_type` and `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 ‘qty’ parameter is set to 10. Entering position with fixed size of 10 contracts and entry market price = (10 * close).
if bar_index == 4
strategy.entry("EN", strategy.long, qty = 10)
if bar_index == 6
strategy.close("EN")
strategy.position_avg_price
DESCRIPTION
Average entry price of current market position. If the market position is flat, 'NaN' is returned.
TYPE
series float
strategy.position_entry_name
DESCRIPTION
Name of the order that initially opened current market position.
TYPE
simple string
strategy.position_size
DESCRIPTION
Direction and size of the current market position. If the value is > 0, the market position is long. If the value is < 0, the market position is short. The absolute value is the number of contracts/shares/lots/units in trade (position size).
TYPE
series float
strategy.short
DESCRIPTION
Short position entry.
TYPE
strategy_direction
strategy.wintrades
DESCRIPTION
Number of profitable trades for the whole trading interval.
TYPE
series int
syminfo.basecurrency
DESCRIPTION
Base currency for the symbol. For the symbol 'BTCUSD' returns 'BTC'.
TYPE
simple string
syminfo.currency
DESCRIPTION
Currency for the current symbol. Returns currency code: 'USD', 'EUR', etc.
TYPE
simple string
syminfo.description
DESCRIPTION
Description for the current symbol.
TYPE
simple string
syminfo.mintick
DESCRIPTION
Min tick value for the current symbol.
TYPE
simple float
syminfo.pointvalue
DESCRIPTION
Point value for the current symbol.
TYPE
simple float
syminfo.prefix
DESCRIPTION
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)
syminfo.root
DESCRIPTION
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)
syminfo.session
DESCRIPTION
Session type of the chart main series. Possible values are session.regular.
TYPE
simple string
syminfo.ticker
DESCRIPTION
Symbol name without exchange prefix, e.g. 'MSFT'.
TYPE
simple string
syminfo.tickerid
DESCRIPTION
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
syminfo.timezone
DESCRIPTION
Timezone of the exchange of the chart main series. Possible values see in timestamp.
TYPE
simple string
syminfo.type
DESCRIPTION
Type of the current symbol. Possible values are stock, futures, index, forex, crypto, fund, dr.
TYPE
simple string
syminfo.volumetype
DESCRIPTION
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
ta.accdist
DESCRIPTION
Accumulation/distribution index.
TYPE
series float
ta.iii
DESCRIPTION
Intraday Intensity Index.
TYPE
series float
EXAMPLE
//@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
DESCRIPTION
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
DESCRIPTION
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
DESCRIPTION
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
DESCRIPTION
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
DESCRIPTION
True range. Same as tr(false). It is max(high - low, abs(high - close[1]), abs(low - close[1]))
TYPE
series float
ta.vwap
DESCRIPTION
Volume Weighted Average Price. It uses hlc3 as its source series.
TYPE
series float
ta.wad
DESCRIPTION
Williams Accumulation/Distribution.
TYPE
series float
EXAMPLE
//@version=5
indicator("Williams Accumulation/Distribution")
plot(ta.wad, color=color.yellow)
// the same on pine
f_wad() =>
trueHigh = math.max(high, close[1])
trueLow = math.min(low, close[1])
mom = ta.change(close)
gain = (mom > 0) ? close - trueLow : (mom < 0) ? close - trueHigh : 0
ta.cum(gain)
plot(f_wad())
ta.wvad
DESCRIPTION
Williams Variable Accumulation/Distribution.
TYPE
series float
EXAMPLE
//@version=5
indicator("Williams Variable Accumulation/Distribution")
plot(ta.wvad, color=color.yellow)
// the same on pine
f_wvad() =>
(close - open) / (high - low) * volume
plot(f_wvad())
table.all
DESCRIPTION
Returns an array filled with all the current tables drawn by the script.
TYPE
table[]
EXAMPLE
//@version=5
indicator("table.all")
//delete all tables
table.new(position = position.top_right, columns = 2, rows = 1, bgcolor = color.yellow, border_width = 1)
a_allTables = table.all
if array.size(a_allTables) > 0
for i = 0 to array.size(a_allTables) - 1
table.delete(array.get(a_allTables, i))
text.align_bottom
DESCRIPTION
Vertical text alignment for box.new functions.
TYPE
const string
text.align_center
DESCRIPTION
Text alignment for box.new functions.
TYPE
const string
text.align_left
DESCRIPTION
Horizontal text alignment for box.new functions.
TYPE
const string
text.align_right
DESCRIPTION
Horizontal text alignment for box.new functions.
TYPE
const string
text.align_top
DESCRIPTION
Vertical text alignment for box.new functions.
TYPE
const string
text.wrap_auto
DESCRIPTION
Automatic wrapping mode for box.new functions.
TYPE
const string
text.wrap_none
DESCRIPTION
Disabled wrapping mode for box.new functions.
TYPE
const string
time
DESCRIPTION
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
time_close
DESCRIPTION
Current bar close time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970. On price-based charts this variable value is na.
TYPE
series int
time_tradingday
DESCRIPTION
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
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).
timeframe.isdaily
DESCRIPTION
Returns true if current resolution is a daily resolution, false otherwise.
TYPE
simple bool
timeframe.isdwm
DESCRIPTION
Returns true if current resolution is a daily or weekly or monthly resolution, false otherwise.
TYPE
simple bool
timeframe.isintraday
DESCRIPTION
Returns true if current resolution is an intraday (minutes or seconds) resolution, false otherwise.
TYPE
simple bool
timeframe.isminutes
DESCRIPTION
Returns true if current resolution is a minutes resolution, false otherwise.
TYPE
simple bool
timeframe.ismonthly
DESCRIPTION
Returns true if current resolution is a monthly resolution, false otherwise.
TYPE
simple bool
timeframe.isseconds
DESCRIPTION
Returns true if current resolution is a seconds resolution, false otherwise.
TYPE
simple bool
timeframe.isweekly
DESCRIPTION
Returns true if current resolution is a weekly resolution, false otherwise.
TYPE
simple bool
timeframe.multiplier
DESCRIPTION
Multiplier of resolution, e.g. '60' - 60, 'D' - 1, '5D' - 5, '12M' - 12.
TYPE
simple int
timeframe.period
DESCRIPTION
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.
TYPE
simple string
timenow
DESCRIPTION
Current time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970.
TYPE
series int
volume
DESCRIPTION
Current bar volume.
TYPE
series float
weekofyear
DESCRIPTION
Week number of current bar time in exchange timezone.
TYPE
series int
xloc.bar_index
DESCRIPTION
A named constant that specifies the algorithm of interpretation of x-value in functions line.new, value of x is a bar index.
TYPE
const string
xloc.bar_time
DESCRIPTION
A named constant that specifies the algorithm of interpretation of x-value in functions line.new, value of x is a bar UNIX time.
TYPE
const string
year
DESCRIPTION
Current bar year in exchange timezone.
TYPE
series int
yloc.abovebar
DESCRIPTION
A named constant that specifies the algorithm of interpretation of y-value in function label.new.
TYPE
const string
yloc.belowbar
DESCRIPTION
A named constant that specifies the algorithm of interpretation of y-value in function label.new.
TYPE
const string
yloc.price
DESCRIPTION
A named constant that specifies the algorithm of interpretation of y-value in function label.new.
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.
alert(message, freq) → void
EXAMPLE
//@version=5
indicator("`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", "▲", location.top, size = size.tiny)
ARGUMENTS
message (series string) Message sent when the alert triggers. Required argument.
freq (input string) The triggering frequency. Possible values are: alert.freq_all.
Contrary to alertcondition calls do NOT count as an additional plot.
Function calls can be located in both global and local scopes.
Function calls do not display anything on the chart.
The 'freq' argument only affects the triggering frequency of the function call where it is used.
alertcondition(...)
DESCRIPTION
Creates alert condition, that is available in Create Alert dialog. Please note, that alertcondition effect is invisible on chart.
alertcondition(condition, title, message) → void
EXAMPLE
//@version=5
indicator("alertcondition", overlay=true)
alertcondition(close >= open, title='Alert on Green Bar', message='Green Bar!')
ARGUMENTS
condition (series bool) Series of boolean values that is used for alert. True values mean alert fire, false - no alert. Required argument.
title (const string) Title of the alert condition. Optional argument.
message (const string) Message to display when alert fires. Optional argument.
array.abs(...)
DESCRIPTION
Returns an array containing the absolute value of each element in the original array.
array.abs(id) → float[]
array.abs(id) → int[]
ARGUMENTS
id (int[]/float[]) An array object.
array.avg(...)
DESCRIPTION
The function returns the mean of an array's elements.
array.avg(id) → series float
array.avg(id) → series int
EXAMPLE
//@version=5
indicator("array.avg example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.avg(a))
RETURNS
Mean of array's elements.
ARGUMENTS
id (int[]/float[]) An array object.
array.binary_search(...)
DESCRIPTION
The function returns the index of the value, or -1 if the value is not found. The array to search must be sorted in ascending order.
val (series int/float) The value to search for in the array.
array.binary_search_leftmost(...)
DESCRIPTION
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.
array.binary_search_leftmost(id, val) → series int
//@version=5
indicator("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
ARGUMENTS
id (int[]/float[]) An array object.
val (series int/float) The value to search for in the array.
array.binary_search_rightmost(...)
DESCRIPTION
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.
array.binary_search_rightmost(id, val) → series int
//@version=5
indicator("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
ARGUMENTS
id (int[]/float[]) An array object.
val (series int/float) The value to search for in the array.
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.
array.concat(id1, id2) → array<type>
EXAMPLE
//@version=5
indicator("array.concat example")
a = array.new_float(0,0)
b = array.new_float(0,0)
for i = 0 to 4
array.push(a, high[i])
array.push(b, low[i])
c = array.concat(a,b)
plot(array.size(a))
plot(array.size(b))
plot(array.size(c))
RETURNS
The first array with merged elements from the second array.
ARGUMENTS
id1 (any array type) The first array object.
id2 (any array type) The second array object.
array.copy(...)
DESCRIPTION
The function creates a copy of an existing array.
array.copy(id) → array<type>
EXAMPLE
//@version=5
indicator("array.copy example")
length = 5
a = array.new_float(length, close)
b = array.copy(a)
a := array.new_float(length, open)
plot(array.sum(a) / length)
plot(array.sum(b) / length)
RETURNS
A copy of an array.
ARGUMENTS
id (any array type) An array object.
array.covariance(...)
DESCRIPTION
The function returns the covariance of two arrays.
array.covariance(id1, id2, biased) → series float
EXAMPLE
//@version=5
indicator("array.covariance example")
a = array.new_float(0)
b = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
array.push(b, open[i])
plot(array.covariance(a, b))
RETURNS
The covariance of two arrays.
ARGUMENTS
id1 (int[]/float[]) An array object.
id2 (int[]/float[]) An array object.
biased (series bool) Determines which estimate should be used. Optional. The default is true.
array.fill(...)
DESCRIPTION
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 ID of an array object which may be used in other array.*() functions.
ARGUMENTS
size (series int) Initial size of an array. Optional. The default is 0.
initial_value (series int) Initial value of all array elements. Optional. The default is 'na'.
array.new_label(...)
DESCRIPTION
The function creates a new array object of label type elements.
array.new_label(size, initial_value) → label[]
EXAMPLE
//@version=5
indicator("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) - 1
for i = 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.
ARGUMENTS
size (series int) Initial size of an array. Optional. The default is 0.
initial_value (series label) Initial value of all array elements. Optional. The default is 'na'.
array.new_line(...)
DESCRIPTION
The function creates a new array object of line type elements.
array.new_line(size, initial_value) → line[]
EXAMPLE
//@version=5
indicator("array.new_line example")
// draw last 15 lines
var a = array.new_line()
array.push(a, line.new(bar_index - 1, close[1], bar_index, close))
if array.size(a) > 15
ln = array.shift(a)
line.delete(ln)
RETURNS
The ID of an array object which may be used in other array.*() functions.
ARGUMENTS
size (series int) Initial size of an array. Optional. The default is 0.
initial_value (series line) Initial value of all array elements. Optional. The default is 'na'.
array.new_linefill(...)
DESCRIPTION
The function creates a new array object of linefill type elements.
index (series int) The index of the element to remove.
array.reverse(...)
DESCRIPTION
The function reverses an array. The first array element becomes the last, and the last array element becomes the first.
array.reverse(id) → void
EXAMPLE
//@version=5
indicator("array.reverse example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.get(a, 0))
array.reverse(a)
plot(array.get(a, 0))
ARGUMENTS
id (any array type) An array object.
array.set(...)
DESCRIPTION
The function sets the value of the element at the specified index.
array.set(id, index, value) → void
EXAMPLE
//@version=5
indicator("array.set example")
a = array.new_float(10)
for i = 0 to 9
array.set(a, i, close[i])
plot(array.sum(a) / 10)
ARGUMENTS
id (any array type) An array object.
index (series int) The index of the element to be modified.
value (series <type of the array's elements>) The new value to be set.
array.shift(...)
DESCRIPTION
The function removes an array's first element and returns its value.
The function returns the number of elements in an array.
array.size(id) → series int
EXAMPLE
//@version=5
indicator("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))
RETURNS
The number of elements in the array.
ARGUMENTS
id (any array type) An array object.
array.slice(...)
DESCRIPTION
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.
//@version=5
indicator("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 array
slice = array.slice(a, 0, 5)
plot(array.sum(a) / 10)
plot(array.sum(slice) / 5)
RETURNS
A shallow copy of an array's slice.
ARGUMENTS
id (any array type) An array object.
index_from (series int) Zero-based index at which to begin extraction.
index_to (series int) Zero-based index before which to end extraction. The function extracts up to but not including the element with this index.
array.sort(...)
DESCRIPTION
The function sorts the elements of an array.
array.sort(id, order) → void
EXAMPLE
//@version=5
indicator("array.sort example")
a = array.new_float(0,0)
for i = 0 to 5
array.push(a, high[i])
array.sort(a, order.descending)
if barstate.islast
label.new(bar_index, close, str.tostring(a))
ARGUMENTS
id (int[]/float[]/string[]) An array object.
order (input sort_order) The sort order: order.ascending (default) or order.descending.
array.sort_indices(...)
DESCRIPTION
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.
//@version=5
indicator("array.standardize example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
b = array.standardize(a)
plot(array.min(b))
plot(array.max(b))
RETURNS
The array of standardized elements.
ARGUMENTS
id (int[]/float[]) An array object.
array.stdev(...)
DESCRIPTION
The function returns the standard deviation of an array's elements.
array.stdev(id, biased) → series float
array.stdev(id, biased) → series int
EXAMPLE
//@version=5
indicator("array.stdev example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.stdev(a))
RETURNS
The standard deviation of the array's elements.
ARGUMENTS
id (int[]/float[]) An array object.
biased (series bool) Determines which estimate should be used. Optional. The default is true.
array.sum(...)
DESCRIPTION
The function returns the sum of an array's elements.
array.sum(id) → series float
array.sum(id) → series int
EXAMPLE
//@version=5
indicator("array.sum example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.sum(a))
RETURNS
The sum of the array's elements.
ARGUMENTS
id (int[]/float[]) An array object.
array.unshift(...)
DESCRIPTION
The function inserts the value at the beginning of the array.
color (series color) Color of bars. You can use constants like 'red' or '#ff001a' as well as complex expressions like 'close >= open ? color.green : color.red'. Required argument.
offset (series int) Shifts the color series to the left or to the right on the given number of bars. Default is 0.
editable (const bool) If true then barcolor style will be editable in Format dialog. Default is true.
show_last (input int) If set, defines the number of bars (from the last bar back to the past) to fill on chart.
title (const string) Title of the barcolor. Optional argument.
display (input plot_simple_display) Controls where the barcolor is displayed. Possible values are: display.none.
color (series color) Color of the filled background. You can use constants like 'red' or '#ff001a' as well as complex expressions like 'close >= open ? color.green : color.red'. Required argument.
offset (series int) Shifts the color series to the left or to the right on the given number of bars. Default is 0.
editable (const bool) If true then bgcolor style will be editable in Format dialog. Default is true.
show_last (input int) If set, defines the number of bars (from the last bar back to the past) to fill on chart.
title (const string) Title of the bgcolor. Optional argument.
display (input plot_simple_display) Controls where the bgcolor is displayed. Possible values are: display.none.
//@version=5
indicator("box.new")
var b = box.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, border_style=line.style_dashed)
box.set_lefttop(b, time, 100)
box.set_rightbottom(b, time + 60 * 60 * 24, 500)
box.set_bgcolor(b, color.green)
RETURNS
The ID of a box object which may be used in box.set**() and box.get**() functions.
ARGUMENTS
left (series int) Bar index (if xloc = xloc.bar_index cannot be drawn further than 500 bars into the future.
top (series int/float) Price of the top border of the box.
right (series int) Bar index (if xloc = xloc.bar_index cannot be drawn further than 500 bars into the future.
bottom (series int/float) Price of the bottom border of the box.
border_color (series color) Color of the four borders. Optional. The default is color.blue.
border_width (series int) Width of the four borders, in pixels. Optional. The default is 1 pixel.
border_style (series string) Style of the four borders. Possible values: line.style_solid.
extend (series string) When extend.none.
xloc (series string) Determines whether the arguments to 'left' and 'right' are a bar index or a time value. If xloc = xloc.bar_index.
bgcolor (series color) Background color of the box. Optional. The default is color.blue.
text (series string) The text to be displayed inside the box. Optional. The default is empty string.
text_size (series string) The size of the text. An optional parameter, the default value is size.auto.
text_font_family (series string) The font family of the text. Optional. The default value is font.family_default.
text_color (series color) The color of the text. Optional. The default is color.black.
text_halign (series string) The horizontal alignment of the box's text. Optional. The default value is text.align_center.
text_valign (series string) The vertical alignment of the box's text. Optional. The default value is text.align_center.
text_wrap (series string) Defines whether the text is presented in a single line, extending past the width of the box if necessary, or wrapped so every line is no wider than the box itself (and clipped by the bottom border of the box if the height of the resulting wrapped text is higher than the height of the box). Optional. The default value is text.wrap_none.
box.set_bgcolor(...)
DESCRIPTION
Sets the background color of the box.
box.set_bgcolor(id, color) → void
ARGUMENTS
id (series box) A box object.
color (series color) New background color.
box.set_border_color(...)
DESCRIPTION
Sets the border color of the box.
box.set_border_color(id, color) → void
ARGUMENTS
id (series box) A box object.
color (series color) New border color.
box.set_border_style(...)
DESCRIPTION
Sets the border style of the box.
box.set_border_style(id, style) → void
ARGUMENTS
id (series box) A box object.
style (series string) New border style.
box.set_border_width(...)
DESCRIPTION
Sets the border width of the box.
box.set_border_width(id, width) → void
ARGUMENTS
id (series box) A box object.
width (series int) Width of the four borders, in pixels.
box.set_bottom(...)
DESCRIPTION
Sets the bottom coordinate of the box.
box.set_bottom(id, bottom) → void
ARGUMENTS
id (series box) A box object.
bottom (series int/float) Price value of the bottom border.
box.set_extend(...)
DESCRIPTION
Sets extending type of the border of this box object. When extend.none, the horizontal borders are extended on both sides.
box.set_extend(id, extend) → void
ARGUMENTS
id (series box) A box object.
extend (series string) New extending type.
box.set_left(...)
DESCRIPTION
Sets the left coordinate of the box.
box.set_left(id, left) → void
ARGUMENTS
id (series box) A box object.
left (series int) Bar index or bar time of the left border. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
box.set_lefttop(...)
DESCRIPTION
Sets the left and top coordinates of the box.
box.set_lefttop(id, left, top) → void
ARGUMENTS
id (series box) A box object.
left (series int) Bar index or bar time of the left border.
top (series int/float) Price value of the top border.
box.set_right(...)
DESCRIPTION
Sets the right coordinate of the box.
box.set_right(id, right) → void
ARGUMENTS
id (series box) A box object.
right (series int) Bar index or bar time of the right border. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
box.set_rightbottom(...)
DESCRIPTION
Sets the right and bottom coordinates of the box.
box.set_rightbottom(id, right, bottom) → void
ARGUMENTS
id (series box) A box object.
right (series int) Bar index or bar time of the right border.
bottom (series int/float) Price value of the bottom border.
box.set_text(...)
DESCRIPTION
The function sets the text in the box.
box.set_text(id, text) → void
ARGUMENTS
id (series box) A box object.
text (series string) The text to be displayed inside the box.
box.set_text_color(...)
DESCRIPTION
The function sets the color of the text inside the box.
box.set_text_color(id, text_color) → void
ARGUMENTS
id (series box) A box object.
text_color (series color) The color of the text.
box.set_text_font_family(...)
DESCRIPTION
The function sets the font family of the text inside the box.
//@version=5
indicator("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)
ARGUMENTS
id (series box) A box object.
text_font_family (series string) The font family of the text. Possible values: font.family_default.
box.set_text_halign(...)
DESCRIPTION
The function sets the horizontal alignment of the box's text.
box.set_text_halign(id, text_halign) → void
ARGUMENTS
id (series box) A box object.
text_halign (series string) The horizontal alignment of a box's text. Possible values: text.align_left.
box.set_text_size(...)
DESCRIPTION
The function sets the size of the box's text.
box.set_text_size(id, text_size) → void
ARGUMENTS
id (series box) A box object.
text_size (series string) The size of the text. Possible values: size.auto.
box.set_text_valign(...)
DESCRIPTION
The function sets the vertical alignment of a box's text.
box.set_text_valign(id, text_valign) → void
ARGUMENTS
id (series box) A box object.
text_valign (series string) The vertical alignment of the box's text. Possible values: text.align_top.
box.set_text_wrap(...)
DESCRIPTION
The function sets the mode of wrapping of the text inside the box.
box.set_text_wrap(id, text_wrap) → void
ARGUMENTS
id (series box) A box object.
text_wrap (series string) The mode of the wrapping. Possible values: text.wrap_auto.
box.set_top(...)
DESCRIPTION
Sets the top coordinate of the box.
box.set_top(id, top) → void
ARGUMENTS
id (series box) A box object.
top (series int/float) Price value of the top border.
color(...)
DESCRIPTION
Casts na to color
color(x) → const color
color(x) → input color
color(x) → simple color
color(x) → series color
RETURNS
The value of the argument after casting to color.
color.b(...)
DESCRIPTION
Retrieves the value of the color's blue component.
The value (0 to 255) of the color's blue component.
ARGUMENTS
color (series color) Color.
color.from_gradient(...)
DESCRIPTION
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.
color.from_gradient(value, bottom_value, top_value, bottom_color, top_color) → series color
dayofmonth(time) → series int
dayofmonth(time, timezone) → series int
RETURNS
Day of month (in exchange timezone) for provided UNIX time.
ARGUMENTS
time (series int) UNIX time in milliseconds.
timezone (series string) Allows adjusting the returned value to a time zone specified in either UTC/GMT notation (e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). Optional. The default is syminfo.timezone.
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.
dayofweek(...)
DESCRIPTION
dayofweek(time) → series int
dayofweek(time, timezone) → series int
RETURNS
Day of week (in exchange timezone) for provided UNIX time.
ARGUMENTS
time (series int) UNIX time in milliseconds.
timezone (series string) Allows adjusting the returned value to a time zone specified in either UTC/GMT notation (e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). Optional. The default is syminfo.timezone.
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970.
fill(...)
DESCRIPTION
Fills background between two plots or hlines with a given color.
hline1 (hline) The first hline object. Required argument.
hline2 (hline) The second hline object. Required argument.
plot1 (plot) The first plot object. Required argument.
plot2 (plot) The second plot object. Required argument.
color (series color) Color of the background fill. You can use constants like 'color=color.red' or 'color=#ff001a' as well as complex expressions like 'color = close >= open ? color.green : color.red'. Optional argument.
title (const string) Title of the created fill object. Optional argument.
editable (const bool) If true then fill style will be editable in Format dialog. Default is true.
show_last (input int) If set, defines the number of bars (from the last bar back to the past) to fill on chart.
fillgaps (const bool) Controls continuing fills on gaps, i.e., when one of the plot() calls returns an na value. When true, the last fill will continue on gaps. The default is false.
display (input plot_simple_display) Controls where the fill is displayed. Possible values are: display.none.
top_value (series int/float) Value where the gradient uses the top_color.
bottom_value (series int/float) Value where the gradient uses the bottom_color.
top_color (series color) Color of the gradient at the topmost value.
bottom_color (series color) Color of the gradient at the bottommost value.
fixnan(...)
DESCRIPTION
For a given series replaces NaN values with previous nearest non-NaN value.
fixnan(source) → series float
fixnan(source) → series int
fixnan(source) → series bool
fixnan(source) → series color
RETURNS
Series without na gaps.
ARGUMENTS
source (series int/float/bool/color) Source used for the calculation.
//@version=5
indicator("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))
RETURNS
An hline object, that can be used in fill
ARGUMENTS
price (input int/float) Price value at which the object will be rendered. Required argument.
title (const string) Title of the object.
color (input color) Color of the rendered line. Must be a constant value (not an expression). Optional argument.
linestyle (input hline_style) Style of the rendered line. Possible values are: hline.style_solid. Optional argument.
linewidth (input int) Width of the rendered line. Default value is 1.
editable (const bool) If true then hline style will be editable in Format dialog. Default is true.
display (input plot_simple_display) Controls where the hline is displayed. Possible values are: display.none.
hour(...)
DESCRIPTION
hour(time) → series int
hour(time, timezone) → series int
RETURNS
Hour (in exchange timezone) for provided UNIX time.
ARGUMENTS
time (series int) UNIX time in milliseconds.
timezone (series string) Allows adjusting the returned value to a time zone specified in either UTC/GMT notation (e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). Optional. The default is syminfo.timezone.
indicator(...)
DESCRIPTION
This declaration statement designates the script as an indicator and sets a number of indicator-related properties.
title (const string) The title of the script. It is displayed on the chart when no shorttitle argument is used, and becomes the publication's default title when publishing the script.
shorttitle (const string) The script's display name on charts. If specified, it will replace the title argument in most chart-related windows. Optional. The default is the argument used for title.
overlay (const bool) If true.
format (const string) Specifies the formatting of the script's displayed values. Possible values: format.inherit.
precision (const int) Specifies the number of digits after the floating point of the script's displayed values. Must be a non-negative integer no greater than 16. If format is set to format.inherit. Optional. The default is inherited from the precision of the chart's symbol.
scale (scale_type) The price scale used. Possible values: scale.right value can only be applied in combination with overlay = true. Optional. By default, the script uses the same scale as the chart.
max_bars_back (const int) The length of the historical buffer the script keeps for every variable and function, which determines how many past values can be referenced using the [] history-referencing operator. The required buffer size is automatically detected by the Pine Script™ runtime. Using this parameter is only necessary when a runtime error occurs because automatic detection fails. More information on the underlying mechanics of the historical buffer can be found in our Help Center. Optional. The default is 0.
timeframe (const string) 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.
timeframe_gaps (const bool) Specifies how the indicator's values are displayed on chart bars when the timeframe is higher than the chart's. If true.
explicit_plot_zorder (const bool) Specifies the order in which the script's plots, fills, and hlines are rendered. If true.
max_lines_count (const int) The number of last line drawings displayed. Possible values: 1-500. The count is approximate; more drawings than the specified count may be displayed. Optional. The default is 50.
max_labels_count (const int) The number of last label drawings displayed. Possible values: 1-500. The count is approximate; more drawings than the specified count may be displayed. Optional. The default is 50.
max_boxes_count (const int) The number of last box drawings displayed. Possible values: 1-500. The count is approximate; more drawings than the specified count may be displayed. Optional. The default is 50.
input(...)
DESCRIPTION
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.
defval (const int/float/bool/string/color or source-type built-ins) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where script users can change it. Source-type built-ins are built-in series float variables that specify the source of the calculation: close, hlc3, etc.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
input.bool(...)
DESCRIPTION
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.
defval (const bool) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.color(...)
DESCRIPTION
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.
input.color(defval, title, tooltip, inline, group, confirm) → input color
defval (const color) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.float(...)
DESCRIPTION
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.
defval (const int/float) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where script users can change it. When a list of values is used with the options parameter, the value must be one of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
minval (const int/float) Minimal possible value of the input variable. Optional.
maxval (const int/float) Maximum possible value of the input variable. Optional.
step (const int/float) Step value used for incrementing/decrementing the input. Optional. The default is 1.
options (tuple of const int/float values: [val1, val2, ...]) A list of options to choose from a dropdown menu, separated by commas and enclosed in square brackets: [val1, val2, ...]. When using this parameter, the minval, maxval and step parameters cannot be used.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.int(...)
DESCRIPTION
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.
defval (const int) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where script users can change it. When a list of values is used with the options parameter, the value must be one of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
minval (const int) Minimal possible value of the input variable. Optional.
maxval (const int) Maximum possible value of the input variable. Optional.
step (const int) Step value used for incrementing/decrementing the input. Optional. The default is 1.
options (tuple of const int values: [val1, val2, ...]) A list of options to choose from a dropdown menu, separated by commas and enclosed in square brackets: [val1, val2, ...]. When using this parameter, the minval, maxval and step parameters cannot be used.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.price(...)
DESCRIPTION
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.
defval (const int/float) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, the interactive input mode is enabled and the selection is done by clicking on the chart when the indicator is added to the chart, or by selecting the indicator and moving the selection after that. Optional. The default is false.
input.session(...)
DESCRIPTION
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.
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it. When a list of values is used with the options parameter, the value must be one of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
options (tuple of const string values: [val1, val2, ...]) A list of options to choose from.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.source(...)
DESCRIPTION
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 call, the user can also select an output from another indicator on their chart as the source.
input.source(defval, title, tooltip, inline, group) → series float
defval (open/high/low/close/hl2/hlc3/ohlc4/hlcc4) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
input.string(...)
DESCRIPTION
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.
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it. When a list of values is used with the options parameter, the value must be one of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
options (tuple of const string values: [val1, val2, ...]) A list of options to choose from.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.symbol(...)
DESCRIPTION
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.
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.text_area(...)
DESCRIPTION
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.
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.time(...)
DESCRIPTION
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.
input.time(defval, title, tooltip, inline, group, confirm) → input int
defval (const int) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it. The value can be a timestamp function, but only if it uses a date argument in const string format.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, the interactive input mode is enabled and the selection is done by clicking on the chart when the indicator is added to the chart, or by selecting the indicator and moving the selection after that. Optional. The default is false.
input.timeframe(...)
DESCRIPTION
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.
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it. When a list of values is used with the options parameter, the value must be one of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
options (tuple of const string values: [val1, val2, ...]) A list of options to choose from.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
int(...)
DESCRIPTION
Casts na or truncates float value to int
int(x) → simple int
int(x) → input int
int(x) → const int
int(x) → series int
//@version=5
indicator("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)
ARGUMENTS
id (series label) A label object.
text_font_family (series string) The font family of the text. Possible values: font.family_default.
label.set_textalign(...)
DESCRIPTION
Sets the alignment for the label text.
label.set_textalign(id, textalign) → void
ARGUMENTS
id (series label) Label object.
textalign (series string) Label text alignment. Possible values: text.align_left.
label.set_textcolor(...)
DESCRIPTION
Sets color of the label text.
label.set_textcolor(id, textcolor) → void
ARGUMENTS
id (series label) Label object.
textcolor (series color) New text color.
label.set_tooltip(...)
DESCRIPTION
Sets the tooltip text.
label.set_tooltip(id, tooltip) → void
ARGUMENTS
id (series label) Label object.
tooltip (series string) Tooltip text.
label.set_x(...)
DESCRIPTION
Sets bar index or bar time (depending on the xloc) of the label position.
label.set_x(id, x) → void
ARGUMENTS
id (series label) Label object.
x (series int) New bar index or bar time of the label position. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
label.set_xloc(...)
DESCRIPTION
Sets x-location and new bar index/time value.
label.set_xloc(id, x, xloc) → void
ARGUMENTS
id (series label) Label object.
x (series int) New bar index or bar time of the label position.
xloc (series string) New x-location value.
label.set_xy(...)
DESCRIPTION
Sets bar index/time and price of the label position.
label.set_xy(id, x, y) → void
ARGUMENTS
id (series label) Label object.
x (series int) New bar index or bar time of the label position. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
y (series int/float) New price of the label position.
label.set_y(...)
DESCRIPTION
Sets price of the label position
label.set_y(id, y) → void
ARGUMENTS
id (series label) Label object.
y (series int/float) New price of the label position.
label.set_yloc(...)
DESCRIPTION
Sets new y-location calculation algorithm.
label.set_yloc(id, yloc) → void
ARGUMENTS
id (series label) Label object.
yloc (series string) New y-location value.
library(...)
DESCRIPTION
Declaration statement identifying a script as a library.
library(title, overlay) → void
EXAMPLE
//@version=5
// @description Math library
library("num_methods", overlay = true)
// Calculate "sinh()" from the float parameter `x`
export sinh(float x) =>
(math.exp(x) - math.exp(-x)) / 2.0
plot(sinh(0))
ARGUMENTS
title (const string) The title of the library and its identifier. It cannot contain spaces, special characters or begin with a digit. It is used as the publication's default title, and to uniquely identify the library in the import statement, when another script uses it. It is also used as the script's name on the chart.
overlay (const bool) If true, the library will be added over the chart. If false, it will be added in a separate pane. Optional. The default is false.
line(...)
DESCRIPTION
Casts na to line
line(x) → series line
RETURNS
The value of the argument after casting to line.
line.copy(...)
DESCRIPTION
Clones the line object.
line.copy(id) → series line
EXAMPLE
//@version=5
indicator('Last 100 bars price range', overlay = true)
LOOKBACK = 100
highest = 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.
ARGUMENTS
id (series line) Line object.
line.delete(...)
DESCRIPTION
Deletes the specified line object. If it has already been deleted, does nothing.
line.delete(id) → void
ARGUMENTS
id (series line) Line object to delete.
line.get_price(...)
DESCRIPTION
Returns the price level of a line at a given bar index.
line.get_price(id, x) → series float
EXAMPLE
//@version=5
indicator("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'.
ARGUMENTS
id (series line) Line object.
x (series int) Bar index for which price is required.
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.
line.get_x1(...)
DESCRIPTION
Returns UNIX time or bar index (depending on the last xloc value set) of the first point of the line.
line.get_x1(id) → series int
EXAMPLE
//@version=5
indicator("line.get_x1")
my_line = line.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time)
a = line.get_x1(my_line)
plot(time - line.get_x1(my_line)) //draws zero plot
RETURNS
UNIX timestamp (in milliseconds) or bar index.
ARGUMENTS
id (series line) Line object.
line.get_x2(...)
DESCRIPTION
Returns UNIX time or bar index (depending on the last xloc value set) of the second point of the line.
line.get_x2(id) → series int
RETURNS
UNIX timestamp (in milliseconds) or bar index.
ARGUMENTS
id (series line) Line object.
line.get_y1(...)
DESCRIPTION
Returns price of the first point of the line.
line.get_y1(id) → series float
RETURNS
Price value.
ARGUMENTS
id (series line) Line object.
line.get_y2(...)
DESCRIPTION
Returns price of the second point of the line.
line.get_y2(id) → series float
RETURNS
Price value.
ARGUMENTS
id (series line) Line object.
line.new(...)
DESCRIPTION
Creates new line object.
line.new(x1, y1, x2, y2, xloc, extend, color, style, width) → series line
EXAMPLE
//@version=5
indicator("line.new")
var line1 = line.new(0, low, bar_index, high, extend=extend.right)
var line2 = line.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, style=line.style_dashed)
line.set_x2(line1, 0)
line.set_xloc(line1, time, time + 60 * 60 * 24, xloc.bar_time)
line.set_color(line2, color.green)
line.set_width(line2, 5)
RETURNS
Line ID object which may be passed to line.setXXX and line.getXXX functions.
ARGUMENTS
x1 (series int) Bar index (if xloc = xloc.bar_index cannot be drawn further than 500 bars into the future.
y1 (series int/float) Price of the first point of the line.
x2 (series int) Bar index (if xloc = xloc.bar_index cannot be drawn further than 500 bars into the future.
y2 (series int/float) Price of the second point of the line.
xloc (series string) See description of x1 argument. Possible values: xloc.bar_index.
extend (series string) If extend=[extend.none.
color (series color) Line color.
style (series string) Line style. Possible values: line.style_solid.
width (series int) Line width in pixels.
line.set_color(...)
DESCRIPTION
Sets the line color
line.set_color(id, color) → void
ARGUMENTS
id (series line) Line object.
color (series color) New line color
line.set_extend(...)
DESCRIPTION
Sets extending type of this line object. If extend=[extend.none, draws a straight line that goes through these points.
line.set_extend(id, extend) → void
ARGUMENTS
id (series line) Line object.
extend (series string) New extending type.
line.set_style(...)
DESCRIPTION
Sets the line style
line.set_style(id, style) → void
ARGUMENTS
id (series line) Line object.
style (series string) New line style.
line.set_width(...)
DESCRIPTION
Sets the line width.
line.set_width(id, width) → void
ARGUMENTS
id (series line) Line object.
width (series int) New line width in pixels.
line.set_x1(...)
DESCRIPTION
Sets bar index or bar time (depending on the xloc) of the first point.
line.set_x1(id, x) → void
ARGUMENTS
id (series line) Line object.
x (series int) Bar index or bar time. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
line.set_x2(...)
DESCRIPTION
Sets bar index or bar time (depending on the xloc) of the second point.
line.set_x2(id, x) → void
ARGUMENTS
id (series line) Line object.
x (series int) Bar index or bar time. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
line.set_xloc(...)
DESCRIPTION
Sets x-location and new bar index/time values.
line.set_xloc(id, x1, x2, xloc) → void
ARGUMENTS
id (series line) Line object.
x1 (series int) Bar index or bar time of the first point.
x2 (series int) Bar index or bar time of the second point.
xloc (series string) New x-location value.
line.set_xy1(...)
DESCRIPTION
Sets bar index/time and price of the first point.
line.set_xy1(id, x, y) → void
ARGUMENTS
id (series line) Line object.
x (series int) Bar index or bar time. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
y (series int/float) Price.
line.set_xy2(...)
DESCRIPTION
Sets bar index/time and price of the second point
line.set_xy2(id, x, y) → void
ARGUMENTS
id (series line) Line object.
x (series int) Bar index or bar time.
y (series int/float) Price.
line.set_y1(...)
DESCRIPTION
Sets price of the first point
line.set_y1(id, y) → void
ARGUMENTS
id (series line) Line object.
y (series int/float) Price.
line.set_y2(...)
DESCRIPTION
Sets price of the second point.
line.set_y2(id, y) → void
ARGUMENTS
id (series line) Line object.
y (series int/float) Price.
linefill(...)
DESCRIPTION
Casts na to linefill.
linefill(x) → series linefill
RETURNS
The value of the argument after casting to linefill.
linefill.delete(...)
DESCRIPTION
Deletes the specified linefill object. If it has already been deleted, does nothing.
linefill.delete(id) → void
ARGUMENTS
id (series linefill) A linefill object.
linefill.get_line1(...)
DESCRIPTION
Returns the ID of the first line used in the id linefill.
linefill.get_line1(id) → series line
ARGUMENTS
id (series linefill) A linefill object.
linefill.get_line2(...)
DESCRIPTION
Returns the ID of the second line used in the id linefill.
linefill.get_line2(id) → series line
ARGUMENTS
id (series linefill) A linefill object.
linefill.new(...)
DESCRIPTION
Creates a new linefill object and displays it on the chart, filling the space between line1 and line2 with the color specified in color.
linefill.new(line1, line2, color) → series linefill
RETURNS
The ID of a linefill object that can be passed to other linefill.*() functions.
ARGUMENTS
line1 (series line) First line object.
line2 (series line) Second line object.
color (series color) The color used to fill the space between the lines.
If both lines are extended in the same direction relative to the lines themselves (e.g. both have extend.right, the space between line extensions will also be filled.
linefill.set_color(...)
DESCRIPTION
The function sets the color of the linefill object passed to it.
linefill.set_color(id, color) → void
ARGUMENTS
id (series linefill) A linefill object.
color (series color) The color of the linefill object.
math.abs(...)
DESCRIPTION
Absolute value of number is number if number >= 0, or -number otherwise.
math.abs(number) → simple int
math.abs(number) → input int
math.abs(number) → const int
math.abs(number) → series int
math.abs(number) → simple float
math.abs(number) → input float
math.abs(number) → const float
math.abs(number) → series float
RETURNS
The absolute value of number.
math.acos(...)
DESCRIPTION
The acos function returns the arccosine (in radians) of number such that cos(acos(y)) = y for y in range [-1, 1].
base raised to the power of exponent. If base is a series, it is calculated elementwise.
ARGUMENTS
base (series int/float) Specify the base to use.
exponent (series int/float) Specifies the exponent.
math.random(...)
DESCRIPTION
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.
math.random(min, max, seed) → series float
RETURNS
A random value.
ARGUMENTS
min (series int/float) The lower bound of the range of random values. The value is not included in the range. The default is 0.
max (series int/float) The upper bound of the range of random values. The value is not included in the range. The default is 1.
seed (series int) Optional argument. When the same seed is used, allows successive calls to the function to produce a repeatable set of values.
math.round(...)
DESCRIPTION
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.
math.round(number) → simple int
math.round(number) → input int
math.round(number) → const int
math.round(number) → series int
math.round(number, precision) → simple float
math.round(number, precision) → input float
math.round(number, precision) → const float
math.round(number, precision) → series float
RETURNS
The value of number rounded to the nearest integer, or according to precision.
ARGUMENTS
number (series int/float) The value to be rounded.
precision (series int) Optional argument. Decimal places to which number will be rounded. When no argument is supplied, rounding is to the nearest integer.
math.round_to_mintick(...)
DESCRIPTION
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.
math.round_to_mintick(number) → simple float
math.round_to_mintick(number) → series float
RETURNS
The number rounded to tick precision.
ARGUMENTS
number (series int/float) The value to be rounded.
math.sign(...)
DESCRIPTION
Sign (signum) of number is zero if number is zero, 1.0 if number is greater than zero, -1.0 if number is less than zero.
//@version=5
indicator("`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=5
indicator("`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))
ARGUMENTS
id (any matrix type) A matrix object.
column (series int) The index of the column after which the new column will be inserted. Optional. The default value is matrix.columns.
array_id (any array type) An array to be inserted. Optional.
matrix.add_row(...)
DESCRIPTION
The function adds a row at the row index of the id matrix. The row can consist of na values, or an array can be used to provide values.
//@version=5
indicator("`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=5
indicator("`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))
ARGUMENTS
id (any matrix type) A matrix object.
row (series int) The index of the row after which the new row will be inserted. Optional. The default value is matrix.rows.
array_id (any array type) An array to be inserted. Optional.
matrix.avg(...)
DESCRIPTION
The function calculates the average of all elements in the matrix.
matrix.avg(id) → series float
matrix.avg(id) → series int
EXAMPLE
//@version=5
indicator("`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')
RETURNS
The average value from the id matrix.
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.col(...)
DESCRIPTION
The function creates a one-dimensional array from the elements of a matrix column.
matrix.col(id, column) → type[]
EXAMPLE
//@version=5
indicator("`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.
ARGUMENTS
id (any matrix type) A matrix object.
column (series int) Index of the required column.
matrix.columns(...)
DESCRIPTION
The function returns the number of columns in the matrix.
matrix.columns(id) → series int
EXAMPLE
//@version=5
indicator("`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) + "n" + str.tostring(m))
RETURNS
The number of columns in the matrix id.
ARGUMENTS
id (any matrix type) A matrix object.
matrix.concat(...)
DESCRIPTION
The function appends the m2 matrix to the m1 matrix.
Returns the id1 matrix concatenated with the id2 matrix.
ARGUMENTS
id1 (any matrix type) Matrix object to concatenate into.
id2 (any matrix type) Matrix object whose elements will be appended to id1.
matrix.copy(...)
DESCRIPTION
The function creates a new matrix which is a copy of the original.
matrix.copy(id) → matrix<type>
EXAMPLE
//@version=5
indicator("`matrix.copy()` Example")
// For efficiency, 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))
RETURNS
A new matrix object of the copied id matrix.
ARGUMENTS
id (any matrix type) A matrix object to copy.
matrix.det(...)
DESCRIPTION
The function returns the determinant of a square matrix.
matrix.det(id) → series float
matrix.det(id) → series int
EXAMPLE
//@version=5
indicator("`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')
RETURNS
The determinant value of the id matrix.
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.diff(...)
DESCRIPTION
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=5
indicator("`matrix.diff()` Example 1")
// For efficiency, 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=5
indicator("`matrix.diff()` Example 2")
// For efficiency, 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.
ARGUMENTS
id1 (matrix/matrix) Matrix to subtract from.
id2 (series int/float/matrix/matrix) Matrix object or a scalar value to be subtracted.
matrix.eigenvalues(...)
DESCRIPTION
The function returns an array containing the eigenvalues of a square matrix.
//@version=5
indicator("`matrix.eigenvectors()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix
var m1 = matrix.new<int>(2, 2, 1)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 2)
matrix.set(m1, 0, 1, 4)
matrix.set(m1, 1, 0, 6)
matrix.set(m1, 1, 1, 8)
// Get the eigenvectors of the matrix.
m2 = matrix.eigenvectors(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, "Matrix Eigenvectors:")
table.cell(t, 1, 1, str.tostring(m2))
RETURNS
A new matrix containing the eigenvectors of the id matrix.
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.elements_count(...)
DESCRIPTION
The function returns the total number of all matrix elements.
matrix.elements_count(id) → series int
ARGUMENTS
id (any matrix type) A matrix object.
matrix.fill(...)
DESCRIPTION
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.
//@version=5
indicator("`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 2 and 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))
ARGUMENTS
id (any matrix type) A matrix object.
value (series <type of the matrix's elements>) The value to fill with.
from_column (series int) Column index from which the fill will begin (inclusive). Optional. The default value is 0.
to_column (series int) Column index where the fill will end (non inclusive). Optional. The default value is matrix.columns.
from_row (series int) Row index from which the fill will begin (inclusive). Optional. The default value is 0.
to_row (series int) Row index where the fill will end (not inclusive). Optional. The default value is matrix.rows.
matrix.get(...)
DESCRIPTION
The function returns the element with the specified index of the matrix.
matrix.get(id, row, column) → <matrix_type>
EXAMPLE
//@version=5
indicator("`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.
ARGUMENTS
id (any matrix type) A matrix object.
row (series int) Index of the required row.
column (series int) Index of the required column.
matrix.inv(...)
DESCRIPTION
The function returns the inverse of a square matrix.
//@version=5
indicator("`matrix.kron()` Example")
// Display using a table.
if barstate.islastconfirmedhistory
// Create two matrices with default values `1` and `2`.
var m1 = matrix.new<float>(2, 2, 1)
var m2 = matrix.new<float>(2, 2, 2)
// Calculate the Kronecker product of the matrices.
var m3 = matrix.kron(m1, m2)
// Display matrix elements.
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, "⊗")
table.cell(t, 2, 0, "Matrix 2:")
table.cell(t, 2, 1, str.tostring(m2))
table.cell(t, 3, 1, "=")
table.cell(t, 4, 0, "Kronecker product:")
table.cell(t, 4, 1, str.tostring(m3))
RETURNS
A new matrix containing the Kronecker product of id1 and id2.
ARGUMENTS
id1 (matrix/matrix) First matrix object.
id2 (matrix/matrix) Second matrix object.
matrix.max(...)
DESCRIPTION
The function returns the largest value from the matrix elements.
matrix.max(id) → series float
matrix.max(id) → series int
EXAMPLE
//@version=5
indicator("`matrix.max()` Example")
// Create a 2x2 matrix.
var m = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m, 0, 0, 1)
matrix.set(m, 0, 1, 2)
matrix.set(m, 1, 0, 3)
matrix.set(m, 1, 1, 4)
// Get the maximum value in the matrix.
var x = matrix.max(m)
plot(x, 'Matrix maximum value')
RETURNS
The maximum value from the id matrix.
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.median(...)
DESCRIPTION
The function calculates the median of matrix elements.
matrix.median(id) → series float
matrix.median(id) → series int
EXAMPLE
//@version=5
indicator("`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')
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.min(...)
DESCRIPTION
The function returns the smallest value from the matrix elements.
matrix.min(id) → series float
matrix.min(id) → series int
EXAMPLE
//@version=5
indicator("`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')
RETURNS
The smallest value from the id matrix.
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.mode(...)
DESCRIPTION
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.
matrix.mode(id) → series float
matrix.mode(id) → series int
EXAMPLE
//@version=5
indicator("`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. Returns ‘na’ if none exists.
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.mult(...)
DESCRIPTION
The function returns a new matrix resulting from the product.
//@version=5
indicator("`matrix.mult()` Example 1")
// For efficiency, 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=5
indicator("`matrix.mult()` Example 2")
// For efficiency, 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=5
indicator("`matrix.mult()` Example 3")
// For efficiency, 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.
ARGUMENTS
id1 (matrix/matrix) First matrix object.
id2 (series int/float/matrix/matrix/int[]/float[]) Second matrix object, value or array.
matrix.new(...)
DESCRIPTION
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 ("").
Create a matrix of elements with the same initial value
EXAMPLE
//@version=5
indicator("`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=5
indicator("`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)
for i = 0 to rows <= 0 ? na : rows - 1
for j = 0 to columns <= 0 ? na : columns - 1
matrix.set(m, i, j, array.get(data, i * columns + j))
m
// 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=5
indicator("`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, "n")
var rows = array.size(rowsArray)
var cols = array.size(str.split(array.get(rowsArray, 0), " "))
var matrix = matrix.new<float>(rows, cols, na)
row = 0
for rowString in rowsArray
col = 0
values = str.split(rowString, " ")
for val in values
matrix.set(matrix, row, col, str.tonumber(val))
col += 1
row += 1
matrix
stringInput = input.text_area("1 2 3n4 5 6n7 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=5
indicator("`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)
for i = 0 to rows - 1
for j = 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))
RETURNS
The ID of the new matrix object.
ARGUMENTS
rows (series int) Initial row count of the matrix. Optional. The default value is 0.
columns (series int) Initial column count of the matrix. Optional. The default value is 0.
initial_value (<matrix_type>) Initial value of all matrix elements. Optional. The default is 'na'.
matrix.pinv(...)
DESCRIPTION
The function returns the pseudoinverse of a matrix.
//@version=5
indicator("`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, "Matrix³:")
table.cell(t, 1, 1, str.tostring(m2))
RETURNS
The product of the id matrix by itself power times.
ARGUMENTS
id (matrix/matrix) A matrix object.
power (series int) The number of times the matrix will be multiplied by itself.
matrix.rank(...)
DESCRIPTION
The function calculates the rank of the matrix.
matrix.rank(id) → series int
EXAMPLE
//@version=5
indicator("`matrix.rank()` Example")
// For efficiency, 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))
RETURNS
The rank of the id matrix.
ARGUMENTS
id (any matrix type) A matrix object.
matrix.remove_col(...)
DESCRIPTION
The function removes the column at column index of the id matrix and returns an array containing the removed column's values.
matrix.remove_col(id, column) → type[]
EXAMPLE
//@version=5
indicator("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.
ARGUMENTS
id (any matrix type) A matrix object.
column (series int) The index of the column to be removed. Optional. The default value is matrix.columns.
matrix.remove_row(...)
DESCRIPTION
The function removes the row at row index of the id matrix and returns an array containing the removed row's values.
matrix.remove_row(id, row) → type[]
EXAMPLE
//@version=5
indicator("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.
ARGUMENTS
id (any matrix type) A matrix object.
row (series int) The index of the row to be deleted. Optional. The default value is matrix.rows.
matrix.reshape(...)
DESCRIPTION
The function rebuilds the id matrix to rows x cols dimensions.
matrix.reshape(id, rows, columns) → void
EXAMPLE
//@version=5
indicator("`matrix.reshape()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix.
var m1 = matrix.new<float>(2, 3)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 0, 2, 3)
matrix.set(m1, 1, 0, 4)
matrix.set(m1, 1, 1, 5)
matrix.set(m1, 1, 2, 6)
// Copy the matrix to a new one.
var m2 = matrix.copy(m1)
// Reshape the copy to a 3x2.
matrix.reshape(m2, 3, 2)
// 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, "Reshaped matrix:")
table.cell(t, 1, 1, str.tostring(m2))
ARGUMENTS
id (any matrix type) A matrix object.
rows (series int) The number of rows of the reshaped matrix.
columns (series int) The number of columns of the reshaped matrix.
matrix.reverse(...)
DESCRIPTION
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.
matrix.reverse(id) → void
EXAMPLE
//@version=5
indicator("`matrix.reverse()` Example")
// For efficiency, 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))
ARGUMENTS
id (any matrix type) A matrix object.
matrix.row(...)
DESCRIPTION
The function creates a one-dimensional array from the elements of a matrix row.
matrix.row(id, row) → type[]
EXAMPLE
//@version=5
indicator("`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.
ARGUMENTS
id (any matrix type) A matrix object.
row (series int) Index of the required row.
matrix.rows(...)
DESCRIPTION
The function returns the number of rows in the matrix.
matrix.rows(id) → series int
EXAMPLE
//@version=5
indicator("`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) + "n" + str.tostring(m))
RETURNS
The number of rows in the matrix id.
ARGUMENTS
id (any matrix type) A matrix object.
matrix.set(...)
DESCRIPTION
The function assigns value to the element at the row and column of the id matrix.
matrix.set(id, row, column, value) → void
EXAMPLE
//@version=5
indicator("`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 1 and 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))
ARGUMENTS
id (any matrix type) A matrix object.
row (series int) The row index of the element to be modified.
column (series int) The column index of the element to be modified.
value (series <type of the matrix's elements>) The new value to be set.
matrix.sort(...)
DESCRIPTION
The function rearranges the rows in the id matrix following the sorted order of the values in the column.
matrix.sort(id, column, order) → void
EXAMPLE
//@version=5
indicator("`matrix.sort()` Example")
// For efficiency, 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))
ARGUMENTS
id (matrix/matrix/matrix) A matrix object to be sorted.
column (series int) Index of the column whose sorted values determine the new order of rows. Optional. The default value is 0.
order (input sort_order) The sort order. Possible values: order.ascending.
matrix.submatrix(...)
DESCRIPTION
The function extracts a submatrix of the id matrix within the specified indices.
//@version=5
indicator("`matrix.sum()` Example 1")
// For efficiency, 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=5
indicator("`matrix.sum()` Example 2")
// For efficiency, 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.
ARGUMENTS
id1 (matrix/matrix) First matrix object.
id2 (series int/float/matrix/matrix) Second matrix object, or scalar value.
matrix.swap_columns(...)
DESCRIPTION
The function swaps the columns at the index column1 and column2 in the id matrix.
matrix.swap_columns(id, column1, column2) → void
EXAMPLE
//@version=5
indicator("`matrix.swap_columns()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix with ‘na’ 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))
ARGUMENTS
id (any matrix type) A matrix object.
column1 (series int) Index of the first column to be swapped.
column2 (series int) Index of the second column to be swapped.
matrix.swap_rows(...)
DESCRIPTION
The function swaps the rows at the index row1 and row2 in the id matrix.
matrix.swap_rows(id, row1, row2) → void
EXAMPLE
//@version=5
indicator("`matrix.swap_rows()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 3x2 matrix with ‘na’ 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))
ARGUMENTS
id (any matrix type) A matrix object.
row1 (series int) Index of the first row to be swapped.
row2 (series int) Index of the second row to be swapped.
matrix.trace(...)
DESCRIPTION
The function calculates the trace.
matrix.trace(id) → series float
matrix.trace(id) → series int
EXAMPLE
//@version=5
indicator("`matrix.trace()` Example")
// For efficiency, 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 trace of the matrix.
tr = matrix.trace(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, "Trace of the matrix:")
table.cell(t, 1, 1, str.tostring(tr))
RETURNS
The trace of the id matrix.
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.transpose(...)
DESCRIPTION
The function creates a new, transposed version of the id. This interchanges the row and column index of each element.
matrix.transpose(id) → matrix<type>
EXAMPLE
//@version=5
indicator("`matrix.transpose()` Example")
// For efficiency, 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, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
// Create a transpose of the matrix.
var m2 = matrix.transpose(m1)
// 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, "Transposed matrix:")
table.cell(t, 1, 1, str.tostring(m2))
RETURNS
A new matrix containing the transposed version of the id matrix.
ARGUMENTS
id (any matrix type) A matrix object.
max_bars_back(...)
DESCRIPTION
Function sets the maximum number of bars that is available for historical reference of a given built-in or user variable. When operator '[]' is applied to a variable - it is a reference to a historical value of that variable.
If an argument of an operator '[]' is a compile time constant value (e.g. 'v[10]', 'close[500]') then there is no need to use 'max_bars_back' function for that variable. Pine Script™ compiler will use that constant value as history buffer size.
If an argument of an operator '[]' is a value, calculated at runtime (e.g. 'v[i]' where 'i' - is a series variable) then Pine Script™ attempts to autodetect the history buffer size at runtime. Sometimes it fails and the script crashes at runtime because it eventually refers to historical values that are out of the buffer. In that case you should use 'max_bars_back' to fix that problem manually.
max_bars_back(var, num) → void
EXAMPLE
//@version=5
indicator("max_bars_back")
close_() => close
depth() => 400
d = depth()
v = close_()
max_bars_back(v, 500)
out = if bar_index > 0
v[d]
else
v
plot(out)
RETURNS
void
ARGUMENTS
var (series int/float/bool/color/label/line) Series variable identifier for which history buffer should be resized. Possible values are: 'open', 'high', 'low', 'close', 'volume', 'time', or any user defined variable id.
num (const int) History buffer size which is the number of bars that could be referenced for variable 'var'.
If the indicator function instead.
minute(...)
DESCRIPTION
minute(time) → series int
minute(time, timezone) → series int
RETURNS
Minute (in exchange timezone) for provided UNIX time.
ARGUMENTS
time (series int) UNIX time in milliseconds.
timezone (series string) Allows adjusting the returned value to a time zone specified in either UTC/GMT notation (e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). Optional. The default is syminfo.timezone.
month(...)
DESCRIPTION
month(time) → series int
month(time, timezone) → series int
RETURNS
Month (in exchange timezone) for provided UNIX time.
ARGUMENTS
time (series int) UNIX time in milliseconds.
timezone (series string) Allows adjusting the returned value to a time zone specified in either UTC/GMT notation (e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). Optional. The default is syminfo.timezone.
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)
The following types are available for user-defined types.
A type can be defined with the type keyword.
A type is similar to a class in object-oriented languages,
but methods are declared afterwards and externally
Type
Description
type
Create a user-defined type with name
.new()
Create a new user-defined type object
.
calls the stored field item of the type either to reassign, or as an expression's return value
Pine Script™ Variables and Constants
Pine Script™ is a loosely typed language. This means that
you do not need to specify the type of data a variable
refers to on asignment unless it is 'na'.
The data type is automatically assigned when
the variable is assigned a value.
It is NOT possible to change the data type after.
Example
a = 1 // a is a intb = 1.2 // b is afloatc = "1.2" // c is a stringd = true // d is a boole = color.new(color.red,50) // e is a color
Example
// type inference// declare a variable without an initial value// the variable type will be 'na' until it is assigned a valuevar int a = na// assign a value to the na inta := 1// variable type is now a value
BUILT INS
Pine Script Indicator functions and variables
Function/Var
Description
ta.accdist
Returns the accumulation/distribution line.
ta.alma()
Returns the Arnaud Legoux Moving Average.
ta.atr()
ATR Returns the Average True Range indicator.
ta.bb()
Returns the Bollinger Bands.
ta.bbw()
Returns the Bollinger Width indicator.
ta.cci()
Returns the Commodity Channel index.
ta.cmo()
Returns the Chande Momentum Oscillator.
ta.cog()
Returns the Center of Gravity indicator.
ta.dmi()
Returns the Directional Movement indicator.
ta.ema()
Returns the Exponential Moving Average.
ta.hma()
Returns the Hull Moving Average.
ta.iii
Returns the Intraday Intensity Index indicator.
ta.kc()
Returns the Keltner Channels.
ta.kcw()
Returns the Keltner Channels width.
ta.linreg()
Returns the Linear Regression Overlay.
ta.macd()
Returns the Moving Average Convergence/Divergence.
ta.mfi()
Returns the Money Flow Index.
ta.mom()
Returns the Momentum indicator.
ta.nvi
Returns the Negative Volume Index.
ta.obv
Returns the On-Balance Volume indicator.
ta.pvi
Returns the Positive Volume Index.
ta.pvt
Returns the Price Volume Trend indicator.
ta.rma()
Returns the Roughness Moving Average.
ta.roc()
Returns the Rate of Change indicator.
ta.rsi(source, length)
Returns the Relative Strength Index.
ta.sar()
Returns the Parabolic Stop and Reverse.
ta.sma()
Returns the Simple Moving Average.
ta.stoch()
Returns the Stochastic oscillator.
ta.supertrend()
Returns the Supertrend indicator.
ta.swma(source)
Returns the Smoothed Weighted Moving Average.
ta.tr
Returns the True Range.
ta.tsi()
Returns the True Strength Index.
ta.vwap
Returns the Volume Weighted Average Price.
ta.vwma()
Returns the Volume Weighted Moving Average.
ta.wad
Returns the Williams Accumulation/Distribution.
ta.wma()
Returns the Weighted Moving Average.
ta.wpr()
Returns the Williams %R indicator.
ta.wvad
Returns the Volume Accumulation/Distribution.
Pine Script Supporting functions
Function
Description
ta.barsince()
Returns the number of bars since a condition has been true.
ta.change()
Returns the percent change of a bar compared to the previous bar.
ta.correlation(source1, source2, length)
Returns the Pearson’s correlation coefficient between two prices.
ta.cross(source1, source2)
Returns true if source1 crossed source2 from downward to upward.
ta.crossover(source1, source2)
Returns true if source1 crossed source2 from downward to upward.
ta.crossunder(source1, source2)
Returns true if source1 crossed source2 from upward to downward.
ta.cum(source)
Returns the cumulative sum of a source.
ta.dev()
Returns the standard deviation of a source.
ta.falling()
Returns true if the current bar’s close price is lower than the previous bar’s close price.
ta.highest()
Returns the highest value from the source.
ta.highestbars()
Returns the highest value from the source within n bars.
ta.lowest()
Returns the lowest value from the source.
ta.lowestbars()
Returns the lowest value from the source within n bars.
ta.median()
Returns the median given the source data.
ta.mode()
Returns the mode given the source data.
ta.percentile_linear_interpolation()
Returns the percentile of the data using linear interpolation.
ta.percentile_nearest_rank()
Returns the percentile of the data using the nea
ta.percentrank(n)
Returns the percentile rank based on the source within n bars.
ta.pivothigh()
Returns the highest high/low that preceded the current bar.
ta.pivotlow()
Returns the lowest high/low that preceded the current bar.
ta.range()
Returns the high to low range of the source.
ta.rising()
Returns true if the current bar’s close price is higher than the previous bar’s close price.
ta.stdev()
Returns the standard deviation of the source.
ta.valuewhen()
Returns the source’s last value when a condition of a given length was true.
ta.variance()
Returns the variance for a given source
Pine Script “math” namespace for math-related functions and variables
Function
Description
math.abs(number)
Returns the absolute value of the number.
math.acos(number)
Returns the arc cosine of the number.
math.asin(number)
Returns the arc sine of the number.
math.atan(number)
Returns the arc tangent of the number.
math.avg()
Returns the average of the numbers.
math.ceil(number)
Returns the ceiling of the number.
math.cos(angle)
Returns the cosine of an angle.
math.exp(number)
Returns the exponential of the number.
math.floor(number)
Returns the floor of the number.
math.log(number)
Returns the natural logarithm of a number.
math.log10(number)
Returns the base-10 logarithm of a number.
math.max()
Returns the maximum of the numbers.
math.min()
Returns the minimum of the numbers.
math.pow()
Returns the value of the first number raised to the power of the second number.
math.random()
Returns a random number between 0 and 1.
math.round(number, precision)
Rounds the number to a given number of decimal places.
math.round_to_mintick(number)
Rounds the number to the smallest increment allowed by the broker
math.sign(number)
Returns a 1 for a postive number and a -1 for a negative number, or 0 for a zero number
math.sin(angle)
Returns the sine of an angle.
math.sqrt(number)
Returns the square root of a number.
math.sum()
Returns the sum of the numbers.
math.tan(angle)
Returns the tangent of an angle.
math.todegrees()
Converts an angle from radians to degrees.
math.toradians()
Converts an angle from degrees to radians.
Pine Script “request” namespace for functions that request external data
Function
Description
request.financial()
Requests financial data such as P/E ratio and market capitalization from an online source.
request.quandl()
Requests a dataset stored online using Quandl.
request.security(<...>, timeframe, <...>)
Requests a certain security to be plotted on the chart.
request.splits()
Requests stock splits data from an online source.
request.dividends()
Requests dividend information from an online source.
request.earnings()
Requests earnings data from an online source.
Pine Script “ticker” namespace for functions that help create tickers
Function
Description
ticker.heikinashi()
Creates a Heikin-Ashi ticker.
ticker.kagi()
Creates a Kagi chart.
ticker.linebreak()
Creates a Line Break chart.
ticker.pointfigure()
Creates a Point & Figure chart.
ticker.renko()
Creates a Renko chart.
ticker.new()
Creates a new ticker.
Pine Script™ Arrays
Arrays allow you to store multiple values in a single variable. Each value in the array is identified by a unique index number. The first element in an array is always 0, the second element is 1, and so on.
Function
Description
array.abs ()
Returns the absolute value of each element in the array.
array.avg ()
Returns the average of the array elements.
array.binary_search ()
Searches for a value in a sorted array and returns the index of the element that matches the value.
array.binary_search_leftmost ()
Searches for a value in a sorted array and returns the index of the leftmost element that matches the value.
array.binary_search_rightmost ()
Searches for a value in a sorted array and returns the index of the rightmost element that matches the value.
array.clear ()
Removes all elements from the array.
array.concat ()
Concatenates two arrays.
array.copy ()
Copies the array.
array.covariance ()
Returns the covariance of the array elements.
array.every ()
Tests whether all elements in the array pass the provided test function.
array.fill ()
Fills the array with a value.
array.first ()
Returns the first element in the array.
array.from ()
Creates an array from a list of values.
array.get ()
Returns the element at the specified index.
array.includes ()
Returns true if the array contains the specified value.
array.indexof ()
Returns the index of the first occurrence of a value in the array.
array.insert ()
Inserts a new element at the specified index.
array.join ()
Joins all elements of an array into a string.
array.last ()
Returns the last element in the array.
array.lastindexof ()
Returns the index of the last occurrence of a value in the array.
array.max ()
Returns the maximum value in the array.
array.median ()
Returns the median of the array elements.
array.min ()
Returns the minimum value in the array.
array.mode ()
Returns the mode of the array elements.
array.new<bool>()
Creates a new array of booleans.
array.new<box>()
Creates a new array of boxes.
array.new<color>()
Creates a new array of colors.
array.new<float>()
Creates a new array of floats.
array.new<int>()
Creates a new array of integers.
array.new<label>()
Creates a new array of labels.
array.new<line>()
Creates a new array of lines.
array.new<linefill>()
Creates a new array of linefills.
array.new<string>()
Creates a new array of strings.
array.new<table>()
Creates a new array of tables.
array.new<type>()
Creates a new array of the specified type.
array.percentile_linear_interpolation ()
Returns the value at the given percentile using linear interpolation.
array.percentile_nearest_rank ()
Returns the value at the given percentile using the nearest rank method.
array.percentrank ()
Returns the percentile rank of a value in the array.
array.pop ()
Removes the last element from the array and returns it.
array.push ()
Adds one or more elements to the end of the array and returns the new length of the array.
array.range ()
Creates a new array with a range of numbers.
array.remove ()
Removes the element at the specified index from the array.
array.reverse ()
Reverses the order of the elements in the array.
array.set ()
Sets the element at the specified index.
array.shift ()
Removes the first element from the array and returns it.
array.size ()
Returns the number of elements in the array.
array.slice ()
Returns a section of the array.
array.some ()
Tests whether at least one element in the array is true if bool, or if any value exists otherwise
array.sort ()
Sorts the elements of an array in place.
array.sort ()
Sorts the elements of the array.
array.sort_indices ()
Returns a new array containing the indices of the original array's elements in sorted order.
array.splice ()
Adds and/or removes elements from the array.
array.standardize ()
Standardizes the array elements by subtracting the mean and dividing by the standard deviation.
array.stdev ()
Returns the standard deviation of the array elements.
array.sum ()
Returns the sum of the array elements.
array.unshift ()
Adds one or more elements to the beginning of the array and returns the new length of the array.
array.variance ()
Returns the variance of the array elements.
Pine Script™ Colors
The following functions are available for colors.
Function
Description
color.a
Returns the alpha component of the color.
color.b
Returns the blue component of the color.
color.g
Returns the green component of the color.
color.r
Returns the red component of the color.
color.rgb
Returns a color from red, green, blue , transp
Pine Script™ Matrices
The following functions are available for matrices as functions and methods
Function
Description
matrix.add_col
Adds a column to a matrix
matrix.add_row
Adds a row to a matrix
matrix.avg
Returns the average of a matrix
matrix.col
Returns a column from a matrix
matrix.columns
Returns the number of columns in a matrix
matrix.concat
Concatenates two matrices
matrix.copy
Copies a matrix
matrix.det
Returns the determinant of a matrix
matrix.diff
Returns the difference of a matrix
matrix.eigenvalues
Returns the eigenvalues of a matrix
matrix.eigenvectors
Returns the eigenvectors of a matrix
matrix.elements_count
Returns the number of elements in a matrix
matrix.fill
Fills a matrix with a value
matrix.get
Returns the value of a matrix element
matrix.inv
Returns the inverse of a matrix
matrix.is_antidiagonal
Returns true if a matrix is antidiagonal
matrix.is_antisymmetric
Returns true if a matrix is antisymmetric
matrix.is_binary
Returns true if a matrix is binary
matrix.is_diagonal
Returns true if a matrix is diagonal
matrix.is_identity
Returns true if a matrix is identity
matrix.is_square
Returns true if a matrix is square
matrix.is_stochastic
Returns true if a matrix is stochastic
matrix.is_symmetric
Returns true if a matrix is symmetric
matrix.is_triangular
Returns true if a matrix is triangular
matrix.is_zero
Returns true if a matrix is zero
matrix.kron
Returns the Kronecker product of two matrices
matrix.max
Returns the maximum value of a matrix
matrix.median
Returns the median of a matrix
matrix.min
Returns the minimum value of a matrix
matrix.mode
Returns the mode of a matrix
matrix.mult
Returns the product of two matrices
matrix.new
Creates a new matrix
matrix.pinv
Returns the pseudoinverse of a matrix
matrix.pow
Returns the power of a matrix
matrix.rank
Returns the rank of a matrix
matrix.remove_col
Removes a column from a matrix
matrix.remove_row
Removes a row from a matrix
matrix.reshape
Reshapes a matrix
matrix.reverse
Reverses the order of the elements in a matrix
matrix.row
Returns a row from a matrix
matrix.rows
Returns the number of rows in a matrix
matrix.set
Sets the value of a matrix element
matrix.sort
Sorts the elements of a matrix
matrix.submatrix
Returns a submatrix from a matrix
matrix.sum
Returns the sum of a matrix
matrix.swap_columns
Swaps two columns in a matrix
matrix.swap_rows
Swaps two rows in a matrix
matrix.trace
Returns the trace of a matrix
matrix.transpose
Returns the transpose of a matrix
Pine Script™ Strings
The following functions are available for strings.
Function
Description
string.charat
Returns the character at the specified index.
string.charcodeat
Returns the Unicode of the character at the specified index.
string.concat
Joins two or more strings, and returns a new joined strings.
string.contains
Returns whether the string contains the specified substring.
string.copy
Copies the string.
string.endswith
Returns whether the string ends with the specified substring.
string.from
Creates a string from a list of values.
string.fromcharcode
Creates a string from a list of Unicode values.
string.indexof
Returns the index of the first occurrence of a substring in the string.
string.isempty
Returns whether the string is empty.
string.join
Joins all elements of a string into a string.
string.lastindexof
Returns the index of the last occurrence of a substring in the string.
string.length
Returns the length of the string.
string.lower
Returns the string converted to lower case.
string.new
Creates a new string.
string.replace
Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
string.split
Splits a string into an array of substrings.
string.startswith
Returns whether the string starts with the specified substring.
string.substr
Extracts the characters from a string, between two specified indices.
string.trim
Removes whitespace from both ends of a string.
string.upper
Returns the string converted to upper case.
Pine Script™ Time
The following functions are available for time.
Function
Description
time.dayofmonth
Returns the day of the month.
time.dayofweek
Returns the day of the week.
time.dayofyear
Returns the day of the year.
time.hour
Returns the hour.
time.isdst
Returns whether daylight saving time is in effect.
time.millisecond
Returns the millisecond.
time.minute
Returns the minute.
time.month
Returns the month.
time.second
Returns the second.
time.timezone
Returns the time zone.
time.tzoffset
Returns the time zone offset.
time.year
Returns the year.
notes about pine script:
Storage methods:
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<" TYPE ">" or "array<" TYPE ">"
- 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<" TYPE ">" or "array<" TYPE ">"
- 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 ">"
- storage types can not be:
- TYPE "[]" "[]"
- "matrix<" TYPE ">" "[]"
- "array<" TYPE ">" "[]"
- "matrix<" TYPE ">" "matrix<" TYPE ">"
- "array<" TYPE ">" "matrix<" TYPE ">"
- "matrix<" TYPE ">" "array<" TYPE ">"
- "array<" TYPE ">" "array<" TYPE ">"
default values
- values can be:
- a number
- a string
- a boolean
- na
- a system variable
- values cannot be:
- a list of values
- a function
- a UDT
Language Operators
!=
DESCRIPTION
Not equal to. Applicable to expressions of any type.
expr1 != expr2
RETURNS
Boolean value, or series of boolean values.
%
DESCRIPTION
Modulo (integer remainder). Applicable to numerical expressions.
A <local_block> is zero or more Pine Script™ statements.
The <function_result> is a variable, an expression, or a tuple.
EXAMPLE
//@version=5
indicator("=>")
// single-line function
f1(x, y) => x + y
// multi-line function
f2(x, y) =>
sum = x + y
sumChange = ta.change(sum, 10)
// Function automatically returns the last expression used in it
plot(f1(30, 8) + f2(1, 3))
>
DESCRIPTION
Greater than. Applicable to numerical expressions.
expr1 > expr2
RETURNS
Boolean value, or series of boolean values.
>=
DESCRIPTION
Greater than or equal to. Applicable to numerical expressions.
expr1 >= expr2
RETURNS
Boolean value, or series of boolean values.
?:
DESCRIPTION
Ternary conditional operator.
expr1 ? expr2 : expr3
EXAMPLE
//@version=5
indicator("?:")
// Draw circles at the bars where open crosses close
s2 = ta.cross(open, close) ? math.avg(open,close) : na
plot(s2, style=plot.style_circles, linewidth=2, color=color.red)
// Combination of ?: operators for 'switch'-like logic
c = timeframe.isintraday ? color.red : timeframe.isdaily ? color.green : timeframe.isweekly ? color.blue : color.gray
plot(hl2, color=c)
RETURNS
expr2 if expr1 is evaluated to true, expr3 otherwise. Zero value (0 and also NaN, +Infinity, -Infinity) is considered to be false, any other value is true.
You can combine two or more ?:.
You may use arithmetic operators with numbers as well as with series variables. In case of usage with series the operators are applied elementwise.
[]
DESCRIPTION
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.
expr1[expr2]
EXAMPLE
//@version=5
indicator("[]")
// [] can be used to "save" variable value between bars
a = 0.0 // declare `a`
a := a[1] // immediately set current value to the same as previous. `na` in the beginning of history
if high == low // if some condition - change `a` value to another
a := low
plot(a)
RETURNS
A series of values.
and
DESCRIPTION
Logical AND. Applicable to boolean expressions.
expr1 and expr2
RETURNS
Boolean value, or series of boolean values.
array
DESCRIPTION
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 function.
EXAMPLE
//@version=5
indicator("array", overlay=true)
array<float> a = na
a := array.new<float>(1, close)
plot(array.get(a, 0))
bool
DESCRIPTION
Keyword used to explicitly declare the "bool" (boolean) type of a variable or a parameter. "Bool" variables can have values true.
EXAMPLE
//@version=5
indicator("bool")
bool b = true // Same as `b = true`
b := na
plot(b ? open : close)
box
DESCRIPTION
Keyword used to explicitly declare the "box" type of a variable or a parameter. Box objects (or IDs) can be created with the box.new function.
EXAMPLE
//@version=5
indicator("box")
// Empty `box1` box ID.
var box box1 = na
// `box` type is unnecessary because `box.new()` returns a "box" type.
var box2 = box.new(na, na, na, na)
box3 = box.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time)
color
DESCRIPTION
Keyword used to explicitly declare the "color" type of a variable or a parameter.
EXAMPLE
//@version=5
indicator("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 for the type can be omitted.
c = color.rgb(0,255,0,0)
plot(close, color = c)
Explicitly mentioning the type in a variable declaration is optional, except when it is initialized with na.
export
DESCRIPTION
Used in libraries to prefix the declaration of functions or user-defined type definitions that will be available from other scripts importing the library.
EXAMPLE
//@version=5
//@description Library of debugging functions.
library("Debugging_library", overlay = true)
//@function Displays a string as a table cell for debugging purposes.
//@param txt String to display.
//@returns Void.
export print(string txt) =>
var table t = table.new(position.middle_right, 1, 1)
table.cell(t, 0, 0, txt, bgcolor = color.yellow)
// Using the function from inside the library to show an example on the published chart.
// This has no impact on scripts using the library.
print("Library Test")
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 in the function's signature.
The @description, @function, @param, @type, @field, and @returns compiler annotations are used to automatically generate the library's description and release notes, and in the Pine Script™ Editor's tooltips.
false
DESCRIPTION
Literal representing a bool value, and result of a comparison operation.
float
DESCRIPTION
Keyword used to explicitly declare the "float" (floating point) type of a variable or a parameter.
EXAMPLE
//@version=5
indicator("float")
float f = 3.14 // Same as `f = 3.14`
f := na
plot(f)
for
DESCRIPTION
The 'for' structure allows the repeated execution of a number of statements:
[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=5
indicator("`for` loop with a step")
a = array.from(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
sum = 0.0
for i = 0 to 9 by 5
// Because the step is set to 5, we are adding only the first (0) and the sixth (5) value from the array `a`.
sum += array.get(a, i)
plot(sum)
for...in
DESCRIPTION
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.
[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=5
indicator("for...in")
// Here we determine on each bar how many of the bar's OHLC values are greater than the SMA of 'close' values
float[] ohlcValues = array.from(open, high, low, close)
qtyGreaterThan(value, array) =>
int result = 0
for currentElement in array
if currentElement > value
result += 1
result
plot(qtyGreaterThan(ta.sma(close, 20), ohlcValues))
Here, we use the two-argument form of for...in to set the values of our `isPos` array to `true` when their corresponding value in our `valuesArray` array is positive:
EXAMPLE
//@version=5
indicator("for...in")
var valuesArray = array.from(4, -8, 11, 78, -16, 34, 7, 99, 0, 55)
var isPos = array.new_bool(10, false)
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.
EXAMPLE
//@version=5
indicator("`for ... in` matrix Example")
// Create a 2x3 matrix with values `4`.
matrix1 = matrix.new<int>(2, 3, 4)
sum = 0.0
// Loop through every row of the matrix.
for rowArray in matrix1
// Sum values of the every row
sum += array.sum(rowArray)
plot(sum)
if
DESCRIPTION
If statement defines what block of statements must be executed when conditions of the expression are satisfied.
To have access to and use the if statement, one should specify the version >= 2 of Pine Script™ language in the very first line of code, for example: //@version=5
The 4th version of Pine Script™ Language allows you to use “else if” syntax.
var_declarationX — this variable gets the value of the if statement
condition — if the condition is true, the logic from the block 'then' (var_decl_then0, var_decl_then1, etc.) is used.
If the condition is false, the logic from the block 'else' (var_decl_else0, var_decl_else1, etc.) is used.
return_expression_then, return_expression_else — the last expression from the block then or from the block else will return the final value of the statement. If declaration of the variable is in the end, its value will be the result.
The type of returning value of the if statement depends on return_expression_then and return_expression_else type (their types must match: it is not possible to return an integer value from then, while you have a string value in else block).
EXAMPLE
//@version=5
indicator("if")
// This code compiles
x = if close > open
close
else
open
// This code doesn’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 “empty” value (na, false, or “”) will be assigned to the var_declarationX variable:
EXAMPLE
//@version=5
indicator("if")
x = if close > open
close
// If current close > current open, then x = close.
// Otherwise the x = na.
plot(x)
It is possible to use either multiple “else if” blocks or none at all. The blocks “then”, “else if”, “else” are shifted by four spaces:
EXAMPLE
//@version=5
indicator("if")
x = if open > close
5
else if high > low
close
else
open
plot(x)
It is possible to ignore the resulting value of an `if` statement (“var_declarationX=“ can be omitted). It may be useful if you need the side effect of the expression, for example in strategy trading:
//@version=5
indicator("if")
float x = na
if close > open
if close > close[1]
x := close
else
x := close[1]
else
x := open
plot(x)
import
DESCRIPTION
Used to load an external library before it can be imported.
import {username}/{libraryName}/{libraryVersion} as {alias}
EXAMPLE
//@version=5
indicator("num_methods import")
// Import the first version of the username’s "num_methods" library and assign it to the "m" namespace",
import username/num_methods/1 as m
// Call the “sinh()” function from the imported library
y = m.sinh(3.14)
// Plot value returned by the "sinh()" function",
plot(y)
ARGUMENTS
username (literal string) User name of the library's author.
libraryName (literal string) Name of the imported library, which corresponds to the `title` argument used by the author in his library script.
libraryVersion (literal int) Version number of the imported library.
alias (literal string) Namespace used to refer to the library's functions. Optional. The default is the libraryName string.
int
DESCRIPTION
Keyword used to explicitly declare the "int" (integer) type of a variable or a parameter.
EXAMPLE
//@version=5
indicator("int")
int i = 14 // Same as `i = 14`
i := na
plot(i)
label
DESCRIPTION
Keyword used to explicitly declare the "label" type of a variable or a parameter. Label objects (or IDs) can be created with the label.new function.
EXAMPLE
//@version=5
indicator("label")
// Empty `label1` label ID.
var label label1 = na
// `label` type is unnecessary because `label.new()` returns "label" type.
var label2 = label.new(na, na, na)
if barstate.islastconfirmedhistory
label3 = label.new(bar_index, high, text = "label3 text")
line
DESCRIPTION
Keyword used to explicitly declare the "line" type of a variable or a parameter. Line objects (or IDs) can be created with the line.new function.
EXAMPLE
//@version=5
indicator("line")
// Empty `line1` line ID.
var line line1 = na
// `line` type is unnecessary because `line.new()` returns "line" type.
var line2 = line.new(na, na, na, na)
line3 = line.new(bar_index - 1, high, bar_index, high, extend = extend.right)
linefill
DESCRIPTION
Keyword used to explicitly declare the "linefill" type of a variable or a parameter. Linefill objects (or IDs) can be created with the linefill.new function.
EXAMPLE
//@version=5
indicator("linefill", overlay=true)
// Empty `linefill1` line ID.
var linefill linefill1 = na
// `linefill` type is unnecessary because `linefill.new()` returns "linefill" type.
var linefill2 = linefill.new(na, na, na)
if barstate.islastconfirmedhistory
line1 = line.new(bar_index - 10, high+1, bar_index, high+1, extend = extend.right)
line2 = line.new(bar_index - 10, low+1, bar_index, low+1, extend = extend.right)
linefill3 = linefill.new(line1, line2, color = color.new(color.green, 80))
matrix
DESCRIPTION
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=5
indicator("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))
method
DESCRIPTION
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.
[export] method ( [= ], …) =>
EXAMPLE
//@version=5
indicator("")
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 for its first parameter.
// maintainArray(prices, 50, close)
// This calls the `array.avg()` built-in using dot notation with the `prices` array.
// It is possible because built-in functions belonging to some namespaces that are a special Pine type
// can be invoked with method notation when the function's first parameter is an ID of that type.
// Those namespaces are: `array`, `matrix`, `line`, `linefill`, `label`, `box`, and `table`.
plot(prices.avg())
not
DESCRIPTION
Logical negation (NOT). Applicable to boolean expressions.
not expr1
RETURNS
Boolean value, or series of boolean values.
or
DESCRIPTION
Logical OR. Applicable to boolean expressions.
expr1 or expr2
RETURNS
Boolean value, or series of boolean values.
series
DESCRIPTION
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.
export ([[series] ] [ = <default_value>])
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)
simple
DESCRIPTION
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.
export ([[simple] ] [ = <default_value>])
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 for its `length` parameter.
ta.ema(source, length)
string
DESCRIPTION
Keyword used to explicitly declare the "string" type of a variable or a parameter.
EXAMPLE
//@version=5
indicator("string")
string s = "Hello World!" // Same as `s = "Hello world!"`
// string s = na // same as ""
plot(na, title=s)
switch
DESCRIPTION
The switch operator transfers control to one of the several statements, depending on the values of a condition and expressions.
//@version=5
indicator("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)
The value of the last expression in the local block of statements that is executed.
table
DESCRIPTION
Keyword used to explicitly declare the "table" type of a variable or a parameter. Table objects (or IDs) can be created with the table.new function.
EXAMPLE
//@version=5
indicator("table")
// Empty `table1` table ID.
var table table1 = na
// `table` type is unnecessary because `table.new()` returns "table" type.
var table2 = table.new(position.top_left, na, na)
if barstate.islastconfirmedhistory
var table3 = table.new(position = position.top_right, columns = 1, rows = 1, bgcolor = color.yellow, border_width = 1)
table.cell(table_id = table3, column = 0, row = 0, text = "table3 text")
true
DESCRIPTION
Literal representing one of the values a bool variable can hold, or an expression can evaluate to when it uses comparison or logical operators.
type
DESCRIPTION
This keyword allows you to declare a user-defined type (UDT) from which objects can be created. UDTs are composite types; they contain an arbitrary number of fields that can be of any type, including the UDT being defined. The syntax to define a UDT is:
Once a UDT is defined, objects can be created from it by using the `UDT_identifier.new()` construct. When creating a new object, its fields are initialized with their default value if one was specified in the UDT's definition, or na` where "foo" is the name of a previously defined UDT and "x" is one of its fields of "bool" type.
For more information see the User Manual's sections on defining UDTs.
UDTs can be exported from libraries. See the User Manual's page on Libraries.
EXAMPLE
//@version=5
indicator("Multi Time Period Chart", overlay = true)
timeframeInput = input.timeframe("1D")
type bar
float o = open
float h = high
float l = low
float c = close
int t = time
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())
if not na(secBar)
// To avoid a runtime error, only process data when an object exists.
if not barstate.islast
if timeframe.change(timeframeInput)
// On historical bars, draw a new box in the past when the HTF closes.
drawBox(secBar, time[1])
else
var box lastBox = na
if na(lastBox) or timeframe.change(timeframeInput)
// On the last bar, only draw a new current box the first time we get there or when HTF changes.
lastBox := drawBox(secBar, time)
else
// On other chart updates, use setters to modify the current box.
updateBox(lastBox, secBar)
var
DESCRIPTION
var is the keyword used for assigning and one-time initializing of the variable.
Normally, a syntax of assignment of variables, which doesn’t include the keyword var, results in the value of the variable being overwritten with every update of the data. Contrary to that, when assigning variables with the keyword var, they can “keep the state” despite the data updating, only changing it when conditions within if-expressions are met.
var variable_name = expression
where:
variable_name - any name of the user’s variable that’s allowed in Pine Script™ (can contain capital and lowercase Latin characters, numbers, and underscores (_), but can’t start with a number).
expression - any arithmetic expression, just as with defining a regular variable. The expression will be calculated and assigned to a variable once.
EXAMPLE
//@version=5
indicator("Var keyword example")
var a = close
var b = 0.0
var c = 0.0
var green_bars_count = 0
if close > open
var x = close
b := x
green_bars_count := green_bars_count + 1
if green_bars_count >= 10
var y = close
c := y
plot(a)
plot(b)
plot(c)
The variable 'a' keeps the closing price of the first bar for each bar in the series.
The variable 'b' keeps the closing price of the first "green" bar in the series.
The variable 'c' keeps the closing price of the tenth "green" bar in the series.
varip
DESCRIPTION
varip (var intrabar persist) is the keyword used for assigning and one-time initializing of a variable. It is similar to the var keyword, but variables declared with varip retain their values between the updates of a real-time bar.
varip variable_name = expression
where:
variable_name - any name of the user's variable that's allowed in Pine Script™ (can contain capital and lowercase Latin characters, numbers, and underscores (_), but can't start with a number).
expression - any arithmetic expression, just as when defining a regular variable. The expression will be calculated and assigned to the variable only once, on the first bar.
EXAMPLE
//@version=5
indicator("varip")
varip int v = -1
v := v + 1
plot(v)
With var, the plot would return the value of bar_index. With varip, the same behavior occurs on historical bars, but in the real-time bar, the plot returns a value that increases by one for each tick.
while
DESCRIPTION
The `while` statement allows the conditional iteration of a local code block.
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=5
indicator("while")
// This is a simple example of calculating a factorial using a while loop.
int i_n = input.int(10, "Factorial Size", minval=0)
int counter = i_n
int factorial = 1
while counter > 0
factorial := factorial * counter
counter := counter - 1
plot(factorial)
Built-In Variables
adjustment.dividends
DESCRIPTION
Constant for dividends adjustment type (dividends adjustment is applied).
TYPE
const string
adjustment.none
DESCRIPTION
Constant for none adjustment type (no adjustment is applied).
TYPE
const string
adjustment.splits
DESCRIPTION
Constant for splits adjustment type (splits adjustment is applied).
TYPE
const string
alert.freq_all
DESCRIPTION
A named constant for use with the `freq` parameter of the alert() function.
All function calls trigger the alert.
TYPE
const string
alert.freq_once_per_bar
DESCRIPTION
A named constant for use with the `freq` parameter of the alert() function.
The first function call during the bar triggers the alert.
TYPE
const string
alert.freq_once_per_bar_close
DESCRIPTION
A named constant for use with the `freq` parameter of the alert() function.
The function call triggers the alert only when it occurs during the last script iteration of the real-time bar, when it closes.
TYPE
const string
bar_index
DESCRIPTION
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)
Note that bar indexing starts from 0 on the first historical bar.
Please note that using this variable/function can cause indicator repainting.
barmerge.gaps_off
DESCRIPTION
Merge strategy for requested data. Data is merged continuously without gaps, all the gaps are filled with the previous nearest existing value.
TYPE
barmerge_gaps
barmerge.gaps_on
DESCRIPTION
Merge strategy for requested data. Data is merged with possible gaps ([na.
TYPE
barmerge_gaps
barmerge.lookahead_off
DESCRIPTION
Merge strategy for the requested data position. Requested barset is merged with current barset in the order of sorting bars by their close time. This merge strategy disables effect of getting data from "future" on calculation on history.
TYPE
barmerge_lookahead
barmerge.lookahead_on
DESCRIPTION
Merge strategy for the requested data position. Requested barset is merged with current barset in the order of sorting bars by their opening time. This merge strategy can lead to undesirable effect of getting data from "future" on calculation on history. This is unacceptable in backtesting strategies, but can be useful in indicators.
TYPE
barmerge_lookahead
barstate.isconfirmed
DESCRIPTION
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
It is NOT recommended to use barstate.isconfirmed is unpredictable.
Please note that using this variable/function can cause indicator repainting.
barstate.isfirst
DESCRIPTION
Returns true if current bar is first bar in barset, false otherwise.
TYPE
series bool
Please note that using this variable/function can cause indicator repainting.
barstate.ishistory
DESCRIPTION
Returns true if current bar is a historical bar, false otherwise.
TYPE
series bool
Please note that using this variable/function can cause indicator repainting.
barstate.islast
DESCRIPTION
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
Please note that using this variable/function can cause indicator repainting.
barstate.islastconfirmedhistory
DESCRIPTION
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
Please note that using this variable/function can cause indicator repainting.
barstate.isnew
DESCRIPTION
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
Please note that using this variable/function can cause indicator repainting.
barstate.isrealtime
DESCRIPTION
Returns true if current bar is a real-time bar, false otherwise.
TYPE
series bool
Please note that using this variable/function can cause indicator repainting.
box.all
DESCRIPTION
Returns an array filled with all the current boxes drawn by the script.
TYPE
box[]
EXAMPLE
//@version=5
indicator("box.all")
//delete all boxes
box.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, border_style=line.style_dashed)
a_allBoxes = box.all
if array.size(a_allBoxes) > 0
for i = 0 to array.size(a_allBoxes) - 1
box.delete(array.get(a_allBoxes, i))
chart.bg_color
DESCRIPTION
Returns the color of the chart's background from the "Chart settings/Appearance/Background" field. When a gradient is selected, the middle point of the gradient is returned.
TYPE
input color
chart.fg_color
DESCRIPTION
Returns a color providing optimal contrast with chart.bg_color.
TYPE
input color
chart.is_heikinashi
DESCRIPTION
TYPE
simple bool
RETURNS
Returns true otherwise.
chart.is_kagi
DESCRIPTION
TYPE
simple bool
RETURNS
Returns true otherwise.
chart.is_linebreak
DESCRIPTION
TYPE
simple bool
RETURNS
Returns true otherwise.
chart.is_pnf
DESCRIPTION
TYPE
simple bool
RETURNS
Returns true otherwise.
chart.is_range
DESCRIPTION
TYPE
simple bool
RETURNS
Returns true otherwise.
chart.is_renko
DESCRIPTION
TYPE
simple bool
RETURNS
Returns true otherwise.
chart.is_standard
DESCRIPTION
TYPE
simple bool
RETURNS
Returns true otherwise.
chart.left_visible_bar_time
DESCRIPTION
The time of the leftmost bar currently visible on the chart.
TYPE
input int
chart.right_visible_bar_time
DESCRIPTION
The time of the rightmost bar currently visible on the chart.
TYPE
input int
close
DESCRIPTION
Close price of the current bar when it has closed, or last traded price of a yet incomplete, realtime bar.
TYPE
series float
color.aqua
DESCRIPTION
Is a named constant for #00BCD4 color.
TYPE
const color
color.black
DESCRIPTION
Is a named constant for #363A45 color.
TYPE
const color
color.blue
DESCRIPTION
Is a named constant for #2962ff color.
TYPE
const color
color.fuchsia
DESCRIPTION
Is a named constant for #E040FB color.
TYPE
const color
color.gray
DESCRIPTION
Is a named constant for #787B86 color.
TYPE
const color
color.green
DESCRIPTION
Is a named constant for #4CAF50 color.
TYPE
const color
color.lime
DESCRIPTION
Is a named constant for #00E676 color.
TYPE
const color
color.maroon
DESCRIPTION
Is a named constant for #880E4F color.
TYPE
const color
color.navy
DESCRIPTION
Is a named constant for #311B92 color.
TYPE
const color
color.olive
DESCRIPTION
Is a named constant for #808000 color.
TYPE
const color
color.orange
DESCRIPTION
Is a named constant for #FF9800 color.
TYPE
const color
color.purple
DESCRIPTION
Is a named constant for #9C27B0 color.
TYPE
const color
color.red
DESCRIPTION
Is a named constant for #FF5252 color.
TYPE
const color
color.silver
DESCRIPTION
Is a named constant for #B2B5BE color.
TYPE
const color
color.teal
DESCRIPTION
Is a named constant for #00897B color.
TYPE
const color
color.white
DESCRIPTION
Is a named constant for #FFFFFF color.
TYPE
const color
color.yellow
DESCRIPTION
Is a named constant for #FFEB3B color.
TYPE
const color
currency.AUD
DESCRIPTION
Australian dollar.
TYPE
const string
currency.BTC
DESCRIPTION
Bitcoin.
TYPE
const string
currency.CAD
DESCRIPTION
Canadian dollar.
TYPE
const string
currency.CHF
DESCRIPTION
Swiss franc.
TYPE
const string
currency.ETH
DESCRIPTION
Ethereum.
TYPE
const string
currency.EUR
DESCRIPTION
Euro.
TYPE
const string
currency.GBP
DESCRIPTION
Pound sterling.
TYPE
const string
currency.HKD
DESCRIPTION
Hong Kong dollar.
TYPE
const string
currency.INR
DESCRIPTION
Indian rupee.
TYPE
const string
currency.JPY
DESCRIPTION
Japanese yen.
TYPE
const string
currency.KRW
DESCRIPTION
South Korean won.
TYPE
const string
currency.MYR
DESCRIPTION
Malaysian ringgit.
TYPE
const string
currency.NOK
DESCRIPTION
Norwegian krone.
TYPE
const string
currency.NONE
DESCRIPTION
Unspecified currency.
TYPE
const string
currency.NZD
DESCRIPTION
New Zealand dollar.
TYPE
const string
currency.RUB
DESCRIPTION
Russian ruble.
TYPE
const string
currency.SEK
DESCRIPTION
Swedish krona.
TYPE
const string
currency.SGD
DESCRIPTION
Singapore dollar.
TYPE
const string
currency.TRY
DESCRIPTION
Turkish lira.
TYPE
const string
currency.USD
DESCRIPTION
United States dollar.
TYPE
const string
currency.USDT
DESCRIPTION
Tether.
TYPE
const string
currency.ZAR
DESCRIPTION
South African rand.
TYPE
const string
dayofmonth
DESCRIPTION
Date of current bar time in exchange timezone.
TYPE
series int
dayofweek
DESCRIPTION
Day of week for current bar time in exchange timezone.
TYPE
series int
You can use dayofweek.sunday variables for comparisons.
dayofweek.friday
DESCRIPTION
Is a named constant for return value of dayofweek variable.
TYPE
const int
dayofweek.monday
DESCRIPTION
Is a named constant for return value of dayofweek variable.
TYPE
const int
dayofweek.saturday
DESCRIPTION
Is a named constant for return value of dayofweek variable.
TYPE
const int
dayofweek.sunday
DESCRIPTION
Is a named constant for return value of dayofweek variable.
TYPE
const int
dayofweek.thursday
DESCRIPTION
Is a named constant for return value of dayofweek variable.
TYPE
const int
dayofweek.tuesday
DESCRIPTION
Is a named constant for return value of dayofweek variable.
TYPE
const int
dayofweek.wednesday
DESCRIPTION
Is a named constant for return value of dayofweek variable.
TYPE
const int
display.all
DESCRIPTION
A named argument for use with the `display` parameter. Displays everywhere.
TYPE
plot_simple_display
display.data_window
DESCRIPTION
A named argument for use with the `display` parameter. Displays the plot values in the Data Window, a menu available in the chart's right sidebar.
TYPE
plot_display
display.none
DESCRIPTION
A named argument for use with the `display` parameter. Causes no plot values to be displayed. The plotted values can nonetheless be used in alert template messages, and will appear in exported chart data.
TYPE
plot_simple_display
display.pane
DESCRIPTION
A named argument for use with the `display` parameter. Displays the plot in the pane used by the script, as defined with the indicator declaration statement's `overlay` parameter.
TYPE
plot_display
display.price_scale
DESCRIPTION
A named argument for use with the `display` parameter. Controls the display of the plot's label and price in the price scale, if the chart's settings allow them.
TYPE
plot_display
display.status_line
DESCRIPTION
A named argument for use with the `display` parameter. Displays the plot values in the script's status line, next to the script's name on the chart, if the chart's settings allow them.
TYPE
plot_display
dividends.gross
DESCRIPTION
A named constant for the request.dividends function. Is used to request the dividends return on a stock before deductions.
TYPE
const string
dividends.net
DESCRIPTION
A named constant for the request.dividends function. Is used to request the dividends return on a stock after deductions.
TYPE
const string
earnings.actual
DESCRIPTION
A named constant for the request.earnings function. Is used to request the earnings value as it was reported.
TYPE
const string
earnings.estimate
DESCRIPTION
A named constant for the request.earnings function. Is used to request the estimated earnings value.
TYPE
const string
earnings.standardized
DESCRIPTION
A named constant for the request.earnings function. Is used to request the standardized earnings value.
TYPE
const string
extend.both
DESCRIPTION
A named constant for line.new functions.
TYPE
const string
extend.left
DESCRIPTION
A named constant for line.new functions.
TYPE
const string
extend.none
DESCRIPTION
A named constant for line.new functions.
TYPE
const string
extend.right
DESCRIPTION
A named constant for line.new functions.
TYPE
const string
font.family_default
DESCRIPTION
Default text font for box.new functions.
TYPE
const string
font.family_monospace
DESCRIPTION
Monospace text font for box.new functions.
TYPE
const string
format.inherit
DESCRIPTION
Is a named constant for selecting the formatting of the script output values from the parent series in the indicator function.
TYPE
const string
format.mintick
DESCRIPTION
Is a named constant to use with the str.tostring, without the remainder, with ties rounding up, and returns the string version of said value with trailing zeroes.
TYPE
const string
format.percent
DESCRIPTION
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
format.price
DESCRIPTION
Is a named constant for selecting the formatting of the script output values as prices in the indicator function.
TYPE
const string
format.volume
DESCRIPTION
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'.
TYPE
const string
high
DESCRIPTION
Current high price.
TYPE
series float
hl2
DESCRIPTION
Is a shortcut for (high + low)/2
TYPE
series float
hlc3
DESCRIPTION
Is a shortcut for (high + low + close)/3
TYPE
series float
hlcc4
DESCRIPTION
Is a shortcut for (high + low + close + close)/4
TYPE
series float
hline.style_dashed
DESCRIPTION
Is a named constant for dashed linestyle of hline function.
TYPE
hline_style
hline.style_dotted
DESCRIPTION
Is a named constant for dotted linestyle of hline function.
TYPE
hline_style
hline.style_solid
DESCRIPTION
Is a named constant for solid linestyle of hline function.
TYPE
hline_style
hour
DESCRIPTION
Current bar hour in exchange timezone.
TYPE
series int
label.all
DESCRIPTION
Returns an array filled with all the current labels drawn by the script.
TYPE
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))
label.style_arrowdown
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_arrowup
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_circle
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_cross
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_diamond
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_flag
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_center
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_down
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_left
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_lower_left
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_lower_right
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_right
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_up
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_upper_left
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_label_upper_right
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_none
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_square
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_text_outline
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_triangledown
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_triangleup
DESCRIPTION
Label style for label.new functions.
TYPE
const string
label.style_xcross
DESCRIPTION
Label style for label.new functions.
TYPE
const string
last_bar_index
DESCRIPTION
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.
last_bar_time
DESCRIPTION
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
Note that this variable returns the timestamp based on the time of the bar's open.
line.all
DESCRIPTION
Returns an array filled with all the current lines drawn by the script.
TYPE
line[]
EXAMPLE
//@version=5
indicator("line.all")
//delete all lines
line.new(bar_index - 10, close, bar_index, close)
a_allLines = line.all
if array.size(a_allLines) > 0
for i = 0 to array.size(a_allLines) - 1
line.delete(array.get(a_allLines, i))
line.style_arrow_both
DESCRIPTION
Line style for line.new functions. Solid line with arrows on both points.
TYPE
const string
line.style_arrow_left
DESCRIPTION
Line style for line.new functions. Solid line with arrow on the first point.
TYPE
const string
line.style_arrow_right
DESCRIPTION
Line style for line.new functions. Solid line with arrow on the second point.
TYPE
const string
line.style_dashed
DESCRIPTION
Line style for line.new functions.
TYPE
const string
line.style_dotted
DESCRIPTION
Line style for line.new functions.
TYPE
const string
line.style_solid
DESCRIPTION
Line style for line.new functions.
TYPE
const string
linefill.all
DESCRIPTION
Returns an array filled with all the current linefill objects drawn by the script.
TYPE
linefill[]
location.abovebar
DESCRIPTION
Location value for plotshape functions. Shape is plotted above main series bars.
TYPE
const string
location.absolute
DESCRIPTION
Location value for plotshape functions. Shape is plotted on chart using indicator value as a price coordinate.
TYPE
const string
location.belowbar
DESCRIPTION
Location value for plotshape functions. Shape is plotted below main series bars.
TYPE
const string
location.bottom
DESCRIPTION
Location value for plotshape functions. Shape is plotted near the bottom chart border.
TYPE
const string
location.top
DESCRIPTION
Location value for plotshape functions. Shape is plotted near the top chart border.
TYPE
const string
low
DESCRIPTION
Current low price.
TYPE
series float
math.e
DESCRIPTION
Is a named constant for Euler's number. It is equal to 2.7182818284590452.
TYPE
const float
math.phi
DESCRIPTION
Is a named constant for the golden ratio. It is equal to 1.6180339887498948.
TYPE
const float
math.pi
DESCRIPTION
Is a named constant for Archimedes' constant. It is equal to 3.1415926535897932.
TYPE
const float
math.rphi
DESCRIPTION
Is a named constant for the golden ratio conjugate. It is equal to 0.6180339887498948.
TYPE
const float
minute
DESCRIPTION
Current bar minute in exchange timezone.
TYPE
series int
month
DESCRIPTION
Current bar month in exchange timezone.
TYPE
series int
na
DESCRIPTION
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))
ohlc4
DESCRIPTION
Is a shortcut for (open + high + low + close)/4
TYPE
series float
open
DESCRIPTION
Current open price.
TYPE
series float
order.ascending
DESCRIPTION
Determines the sort order of the array from the smallest to the largest value.
TYPE
sort_order
order.descending
DESCRIPTION
Determines the sort order of the array from the largest to the smallest value.
TYPE
sort_order
plot.style_area
DESCRIPTION
A named constant for the 'Area' style, to be used as an argument for the `style` parameter in the plot function.
TYPE
plot_style
plot.style_areabr
DESCRIPTION
A named constant for the 'Area With Breaks' style, to be used as an argument for the `style` parameter in the plot, except the gaps in the data are not filled.
TYPE
plot_style
plot.style_circles
DESCRIPTION
A named constant for the 'Circles' style, to be used as an argument for the `style` parameter in the plot function.
TYPE
plot_style
plot.style_columns
DESCRIPTION
A named constant for the 'Columns' style, to be used as an argument for the `style` parameter in the plot function.
TYPE
plot_style
plot.style_cross
DESCRIPTION
A named constant for the 'Cross' style, to be used as an argument for the `style` parameter in the plot function.
TYPE
plot_style
plot.style_histogram
DESCRIPTION
A named constant for the 'Histogram' style, to be used as an argument for the `style` parameter in the plot function.
TYPE
plot_style
plot.style_line
DESCRIPTION
A named constant for the 'Line' style, to be used as an argument for the `style` parameter in the plot function.
TYPE
plot_style
plot.style_linebr
DESCRIPTION
A named constant for the 'Line With Breaks' style, to be used as an argument for the `style` parameter in the plot, except the gaps in the data are not filled.
TYPE
plot_style
plot.style_stepline
DESCRIPTION
A named constant for the 'Step Line' style, to be used as an argument for the `style` parameter in the plot function.
TYPE
plot_style
plot.style_stepline_diamond
DESCRIPTION
A named constant for the 'Step Line With Diamonds' style, to be used as an argument for the `style` parameter in the plot, except the data changes are also marked with the Diamond shapes.
TYPE
plot_style
plot.style_steplinebr
DESCRIPTION
A named constant for the 'Step line with Breaks' style, to be used as an argument for the `style` parameter in the plot function.
TYPE
plot_style
position.bottom_center
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the bottom edge in the center.
TYPE
const string
position.bottom_left
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the bottom left of the screen.
TYPE
const string
position.bottom_right
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the bottom right of the screen.
TYPE
const string
position.middle_center
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the center of the screen.
TYPE
const string
position.middle_left
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the left side of the screen.
TYPE
const string
position.middle_right
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the right side of the screen.
TYPE
const string
position.top_center
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the top edge in the center.
TYPE
const string
position.top_left
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the upper-left edge.
TYPE
const string
position.top_right
DESCRIPTION
Table position is used in table.new functions.
Binds the table to the upper-right edge.
TYPE
const string
scale.left
DESCRIPTION
Scale value for indicator function. Indicator is added to the left price scale.
TYPE
scale_type
scale.none
DESCRIPTION
Scale value for indicator function. Indicator is added in 'No Scale' mode. Can be used only with 'overlay=true'.
TYPE
scale_type
scale.right
DESCRIPTION
Scale value for indicator function. Indicator is added to the right price scale.
TYPE
scale_type
second
DESCRIPTION
Current bar second in exchange timezone.
TYPE
series int
session.extended
DESCRIPTION
Constant for extended session type (with extended hours data).
TYPE
const string
session.isfirstbar
DESCRIPTION
Returns true on the first bar of the pre-market bars.
TYPE
series bool
session.isfirstbar_regular
DESCRIPTION
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
DESCRIPTION
Returns true on the last bar of the post-market bars.
TYPE
series bool
This variable is not guaranteed to work as expected on non-standard chart types, e.g., Renko.
session.islastbar_regular
DESCRIPTION
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
This variable is not guaranteed to work as expected on non-standard chart types, e.g., Renko.
session.ismarket
DESCRIPTION
Returns true if the current bar is a part of the regular trading hours (i.e. market hours), false otherwise
TYPE
series bool
session.ispostmarket
DESCRIPTION
Returns true if the current bar is a part of the post-market, false otherwise. On non-intraday charts always returns false.
TYPE
series bool
session.ispremarket
DESCRIPTION
Returns true if the current bar is a part of the pre-market, false otherwise. On non-intraday charts always returns false.
TYPE
series bool
session.regular
DESCRIPTION
Constant for regular session type (no extended hours data).
TYPE
const string
shape.arrowdown
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.arrowup
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.circle
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.cross
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.diamond
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.flag
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.labeldown
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.labelup
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.square
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.triangledown
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.triangleup
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
shape.xcross
DESCRIPTION
Shape style for plotshape function.
TYPE
const string
size.auto
DESCRIPTION
Size value for plotshape functions. The size of the shape automatically adapts to the size of the bars.
TYPE
const string
size.huge
DESCRIPTION
Size value for plotshape functions. The size of the shape constantly huge.
TYPE
const string
size.large
DESCRIPTION
Size value for plotshape functions. The size of the shape constantly large.
TYPE
const string
size.normal
DESCRIPTION
Size value for plotshape functions. The size of the shape constantly normal.
TYPE
const string
size.small
DESCRIPTION
Size value for plotshape functions. The size of the shape constantly small.
TYPE
const string
size.tiny
DESCRIPTION
Size value for plotshape functions. The size of the shape constantly tiny.
TYPE
const string
splits.denominator
DESCRIPTION
A named constant for the request.splits of a splits.
TYPE
const string
splits.numerator
DESCRIPTION
A named constant for the request.splits of a splits.
TYPE
const string
strategy.account_currency
DESCRIPTION
Returns the currency used to calculate results, which can be set in the strategy's properties.
TYPE
simple string
strategy.cash
DESCRIPTION
This is one of the arguments that can be supplied to the `default_qty_type` parameter in the strategy function calls. It specifies that an amount of cash in the `strategy.account_currency` will be used to enter trades.
TYPE
const string
EXAMPLE
//@version=5
strategy("strategy.cash", overlay = true, default_qty_value = 50, default_qty_type = strategy.cash, initial_capital = 1000000)
if bar_index == 0
// As ‘qty’ is not defined, the previously defined values for the `default_qty_type` 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")
strategy.closedtrades
DESCRIPTION
Number of trades, which were closed for the whole trading interval.
TYPE
series int
strategy.commission.cash_per_contract
DESCRIPTION
Commission type for an order. Money displayed in the account currency per contract.
TYPE
const string
strategy.commission.cash_per_order
DESCRIPTION
Commission type for an order. Money displayed in the account currency per order.
TYPE
const string
strategy.commission.percent
DESCRIPTION
Commission type for an order. A percentage of the cash volume of order.
TYPE
const string
strategy.direction.all
DESCRIPTION
It allows strategy to open both long and short positions.
TYPE
const string
strategy.direction.long
DESCRIPTION
It allows strategy to open only long positions.
TYPE
const string
strategy.direction.short
DESCRIPTION
It allows strategy to open only short positions.
TYPE
const string
strategy.equity
DESCRIPTION
Current equity ([strategy.initial_capital.
TYPE
series float
strategy.eventrades
DESCRIPTION
Number of breakeven trades for the whole trading interval.
TYPE
series int
strategy.fixed
DESCRIPTION
This is one of the arguments that can be supplied to the `default_qty_type` parameter in the strategy function calls. It specifies that a number of contracts/shares/lots will be used to enter trades.
TYPE
const string
EXAMPLE
//@version=5
strategy("strategy.fixed", overlay = true, default_qty_value = 50, default_qty_type = strategy.fixed, initial_capital = 1000000)
if bar_index == 0
// As ‘qty’ is not defined, the previously defined values for the `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")
strategy.grossloss
DESCRIPTION
Total currency value of all completed losing trades.
TYPE
series float
strategy.grossprofit
DESCRIPTION
Total currency value of all completed winning trades.
TYPE
series float
strategy.initial_capital
DESCRIPTION
The amount of initial capital set in the strategy properties.
TYPE
series float
strategy.long
DESCRIPTION
Long position entry.
TYPE
strategy_direction
strategy.losstrades
DESCRIPTION
Number of unprofitable trades for the whole trading interval.
TYPE
series int
strategy.max_contracts_held_all
DESCRIPTION
Maximum number of contracts/shares/lots/units in one trade for the whole trading interval.
TYPE
series float
strategy.max_contracts_held_long
DESCRIPTION
Maximum number of contracts/shares/lots/units in one long trade for the whole trading interval.
TYPE
series float
strategy.max_contracts_held_short
DESCRIPTION
Maximum number of contracts/shares/lots/units in one short trade for the whole trading interval.
TYPE
series float
strategy.max_drawdown
DESCRIPTION
Maximum equity drawdown value for the whole trading interval.
TYPE
series float
strategy.max_runup
DESCRIPTION
Maximum equity run-up value for the whole trading interval.
TYPE
series float
strategy.netprofit
DESCRIPTION
Total currency value of all completed trades.
TYPE
series float
strategy.oca.cancel
DESCRIPTION
OCA type value for strategy's functions. The parameter determines that an order should belong to an OCO group, where as soon as an order is filled, all other orders of the same group are cancelled. Note: if more than 1 guaranteed-to-be-executed orders of the same OCA group are placed at once, all those orders are filled.
TYPE
const string
strategy.oca.none
DESCRIPTION
OCA type value for strategy's functions. The parameter determines that an order should not belong to any particular OCO group.
TYPE
const string
strategy.oca.reduce
DESCRIPTION
OCA type value for strategy's functions. The parameter determines that an order should belong to an OCO group, where if X number of contracts of an order is filled, number of contracts for each other order of the same OCO group is decreased by X. Note: if more than 1 guaranteed-to-be-executed orders of the same OCA group are placed at once, all those orders are filled.
TYPE
const string
strategy.openprofit
DESCRIPTION
Current unrealized profit or loss for all open positions.
TYPE
series float
strategy.opentrades
DESCRIPTION
Number of market position entries, which were not closed and remain opened. If there is no open market position, 0 is returned.
TYPE
series int
strategy.percent_of_equity
DESCRIPTION
This is one of the arguments that can be supplied to the `default_qty_type` parameter in the strategy of equity will be used to enter trades.
TYPE
const string
EXAMPLE
//@version=5
strategy("strategy.percent_of_equity", overlay = false, default_qty_value = 100, default_qty_type = strategy.percent_of_equity, initial_capital = 1000000)
// As ‘qty’ is not defined, the previously defined values for the `default_qty_type` and `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 ‘qty’ parameter is set to 10. Entering position with fixed size of 10 contracts and entry market price = (10 * close).
if bar_index == 4
strategy.entry("EN", strategy.long, qty = 10)
if bar_index == 6
strategy.close("EN")
strategy.position_avg_price
DESCRIPTION
Average entry price of current market position. If the market position is flat, 'NaN' is returned.
TYPE
series float
strategy.position_entry_name
DESCRIPTION
Name of the order that initially opened current market position.
TYPE
simple string
strategy.position_size
DESCRIPTION
Direction and size of the current market position. If the value is > 0, the market position is long. If the value is < 0, the market position is short. The absolute value is the number of contracts/shares/lots/units in trade (position size).
TYPE
series float
strategy.short
DESCRIPTION
Short position entry.
TYPE
strategy_direction
strategy.wintrades
DESCRIPTION
Number of profitable trades for the whole trading interval.
TYPE
series int
syminfo.basecurrency
DESCRIPTION
Base currency for the symbol. For the symbol 'BTCUSD' returns 'BTC'.
TYPE
simple string
syminfo.currency
DESCRIPTION
Currency for the current symbol. Returns currency code: 'USD', 'EUR', etc.
TYPE
simple string
syminfo.description
DESCRIPTION
Description for the current symbol.
TYPE
simple string
syminfo.mintick
DESCRIPTION
Min tick value for the current symbol.
TYPE
simple float
syminfo.pointvalue
DESCRIPTION
Point value for the current symbol.
TYPE
simple float
syminfo.prefix
DESCRIPTION
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)
syminfo.root
DESCRIPTION
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)
syminfo.session
DESCRIPTION
Session type of the chart main series. Possible values are session.regular.
TYPE
simple string
syminfo.ticker
DESCRIPTION
Symbol name without exchange prefix, e.g. 'MSFT'.
TYPE
simple string
syminfo.tickerid
DESCRIPTION
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
syminfo.timezone
DESCRIPTION
Timezone of the exchange of the chart main series. Possible values see in timestamp.
TYPE
simple string
syminfo.type
DESCRIPTION
Type of the current symbol. Possible values are stock, futures, index, forex, crypto, fund, dr.
TYPE
simple string
syminfo.volumetype
DESCRIPTION
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
ta.accdist
DESCRIPTION
Accumulation/distribution index.
TYPE
series float
ta.iii
DESCRIPTION
Intraday Intensity Index.
TYPE
series float
EXAMPLE
//@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
DESCRIPTION
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
DESCRIPTION
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
DESCRIPTION
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
DESCRIPTION
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
DESCRIPTION
True range. Same as tr(false). It is max(high - low, abs(high - close[1]), abs(low - close[1]))
TYPE
series float
ta.vwap
DESCRIPTION
Volume Weighted Average Price. It uses hlc3 as its source series.
TYPE
series float
ta.wad
DESCRIPTION
Williams Accumulation/Distribution.
TYPE
series float
EXAMPLE
//@version=5
indicator("Williams Accumulation/Distribution")
plot(ta.wad, color=color.yellow)
// the same on pine
f_wad() =>
trueHigh = math.max(high, close[1])
trueLow = math.min(low, close[1])
mom = ta.change(close)
gain = (mom > 0) ? close - trueLow : (mom < 0) ? close - trueHigh : 0
ta.cum(gain)
plot(f_wad())
ta.wvad
DESCRIPTION
Williams Variable Accumulation/Distribution.
TYPE
series float
EXAMPLE
//@version=5
indicator("Williams Variable Accumulation/Distribution")
plot(ta.wvad, color=color.yellow)
// the same on pine
f_wvad() =>
(close - open) / (high - low) * volume
plot(f_wvad())
table.all
DESCRIPTION
Returns an array filled with all the current tables drawn by the script.
TYPE
table[]
EXAMPLE
//@version=5
indicator("table.all")
//delete all tables
table.new(position = position.top_right, columns = 2, rows = 1, bgcolor = color.yellow, border_width = 1)
a_allTables = table.all
if array.size(a_allTables) > 0
for i = 0 to array.size(a_allTables) - 1
table.delete(array.get(a_allTables, i))
text.align_bottom
DESCRIPTION
Vertical text alignment for box.new functions.
TYPE
const string
text.align_center
DESCRIPTION
Text alignment for box.new functions.
TYPE
const string
text.align_left
DESCRIPTION
Horizontal text alignment for box.new functions.
TYPE
const string
text.align_right
DESCRIPTION
Horizontal text alignment for box.new functions.
TYPE
const string
text.align_top
DESCRIPTION
Vertical text alignment for box.new functions.
TYPE
const string
text.wrap_auto
DESCRIPTION
Automatic wrapping mode for box.new functions.
TYPE
const string
text.wrap_none
DESCRIPTION
Disabled wrapping mode for box.new functions.
TYPE
const string
time
DESCRIPTION
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
time_close
DESCRIPTION
Current bar close time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970. On price-based charts this variable value is na.
TYPE
series int
time_tradingday
DESCRIPTION
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
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).
timeframe.isdaily
DESCRIPTION
Returns true if current resolution is a daily resolution, false otherwise.
TYPE
simple bool
timeframe.isdwm
DESCRIPTION
Returns true if current resolution is a daily or weekly or monthly resolution, false otherwise.
TYPE
simple bool
timeframe.isintraday
DESCRIPTION
Returns true if current resolution is an intraday (minutes or seconds) resolution, false otherwise.
TYPE
simple bool
timeframe.isminutes
DESCRIPTION
Returns true if current resolution is a minutes resolution, false otherwise.
TYPE
simple bool
timeframe.ismonthly
DESCRIPTION
Returns true if current resolution is a monthly resolution, false otherwise.
TYPE
simple bool
timeframe.isseconds
DESCRIPTION
Returns true if current resolution is a seconds resolution, false otherwise.
TYPE
simple bool
timeframe.isweekly
DESCRIPTION
Returns true if current resolution is a weekly resolution, false otherwise.
TYPE
simple bool
timeframe.multiplier
DESCRIPTION
Multiplier of resolution, e.g. '60' - 60, 'D' - 1, '5D' - 5, '12M' - 12.
TYPE
simple int
timeframe.period
DESCRIPTION
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.
TYPE
simple string
timenow
DESCRIPTION
Current time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970.
TYPE
series int
volume
DESCRIPTION
Current bar volume.
TYPE
series float
weekofyear
DESCRIPTION
Week number of current bar time in exchange timezone.
TYPE
series int
xloc.bar_index
DESCRIPTION
A named constant that specifies the algorithm of interpretation of x-value in functions line.new, value of x is a bar index.
TYPE
const string
xloc.bar_time
DESCRIPTION
A named constant that specifies the algorithm of interpretation of x-value in functions line.new, value of x is a bar UNIX time.
TYPE
const string
year
DESCRIPTION
Current bar year in exchange timezone.
TYPE
series int
yloc.abovebar
DESCRIPTION
A named constant that specifies the algorithm of interpretation of y-value in function label.new.
TYPE
const string
yloc.belowbar
DESCRIPTION
A named constant that specifies the algorithm of interpretation of y-value in function label.new.
TYPE
const string
yloc.price
DESCRIPTION
A named constant that specifies the algorithm of interpretation of y-value in function label.new.
TYPE
const string
Built-In Functions
alert(...)
DESCRIPTION
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.
alert(message, freq) → void
EXAMPLE
//@version=5
indicator("`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", "▲", location.top, size = size.tiny)
ARGUMENTS
message (series string) Message sent when the alert triggers. Required argument.
freq (input string) The triggering frequency. Possible values are: alert.freq_all.
Contrary to alertcondition calls do NOT count as an additional plot.
Function calls can be located in both global and local scopes.
Function calls do not display anything on the chart.
The 'freq' argument only affects the triggering frequency of the function call where it is used.
alertcondition(...)
DESCRIPTION
Creates alert condition, that is available in Create Alert dialog. Please note, that alertcondition effect is invisible on chart.
alertcondition(condition, title, message) → void
EXAMPLE
//@version=5
indicator("alertcondition", overlay=true)
alertcondition(close >= open, title='Alert on Green Bar', message='Green Bar!')
ARGUMENTS
condition (series bool) Series of boolean values that is used for alert. True values mean alert fire, false - no alert. Required argument.
title (const string) Title of the alert condition. Optional argument.
message (const string) Message to display when alert fires. Optional argument.
array.abs(...)
DESCRIPTION
Returns an array containing the absolute value of each element in the original array.
array.abs(id) → float\[\]
array.abs(id) → int\[\]
ARGUMENTS
id (int[]/float[]) An array object.
array.avg(...)
DESCRIPTION
The function returns the mean of an array's elements.
array.avg(id) → series float
array.avg(id) → series int
EXAMPLE
//@version=5
indicator("array.avg example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.avg(a))
RETURNS
Mean of array's elements.
ARGUMENTS
id (int[]/float[]) An array object.
array.binary_search(...)
DESCRIPTION
The function returns the index of the value, or -1 if the value is not found. The array to search must be sorted in ascending order.
val (series int/float) The value to search for in the array.
array.binary_search_leftmost(...)
DESCRIPTION
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.
array.binary\_search\_leftmost(id, val) → series int
//@version=5
indicator("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
ARGUMENTS
id (int[]/float[]) An array object.
val (series int/float) The value to search for in the array.
array.binary_search_rightmost(...)
DESCRIPTION
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.
array.binary\_search\_rightmost(id, val) → series int
//@version=5
indicator("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
ARGUMENTS
id (int[]/float[]) An array object.
val (series int/float) The value to search for in the array.
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.
array.concat(id1, id2) → array<type>
EXAMPLE
//@version=5
indicator("array.concat example")
a = array.new_float(0,0)
b = array.new_float(0,0)
for i = 0 to 4
array.push(a, high[i])
array.push(b, low[i])
c = array.concat(a,b)
plot(array.size(a))
plot(array.size(b))
plot(array.size(c))
RETURNS
The first array with merged elements from the second array.
ARGUMENTS
id1 (any array type) The first array object.
id2 (any array type) The second array object.
array.copy(...)
DESCRIPTION
The function creates a copy of an existing array.
array.copy(id) → array<type>
EXAMPLE
//@version=5
indicator("array.copy example")
length = 5
a = array.new_float(length, close)
b = array.copy(a)
a := array.new_float(length, open)
plot(array.sum(a) / length)
plot(array.sum(b) / length)
RETURNS
A copy of an array.
ARGUMENTS
id (any array type) An array object.
array.covariance(...)
DESCRIPTION
The function returns the covariance of two arrays.
array.covariance(id1, id2, biased) → series float
EXAMPLE
//@version=5
indicator("array.covariance example")
a = array.new_float(0)
b = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
array.push(b, open[i])
plot(array.covariance(a, b))
RETURNS
The covariance of two arrays.
ARGUMENTS
id1 (int[]/float[]) An array object.
id2 (int[]/float[]) An array object.
biased (series bool) Determines which estimate should be used. Optional. The default is true.
array.fill(...)
DESCRIPTION
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.
//@version=5
indicator("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) - 1
for i = 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.
ARGUMENTS
size (series int) Initial size of an array. Optional. The default is 0.
initial_value (series label) Initial value of all array elements. Optional. The default is 'na'.
array.new_line(...)
DESCRIPTION
The function creates a new array object of line type elements.
array.new\_line(size, initial\_value) → line\[\]
EXAMPLE
//@version=5
indicator("array.new_line example")
// draw last 15 lines
var a = array.new_line()
array.push(a, line.new(bar_index - 1, close[1], bar_index, close))
if array.size(a) > 15
ln = array.shift(a)
line.delete(ln)
RETURNS
The ID of an array object which may be used in other array.*() functions.
ARGUMENTS
size (series int) Initial size of an array. Optional. The default is 0.
initial_value (series line) Initial value of all array elements. Optional. The default is 'na'.
array.new_linefill(...)
DESCRIPTION
The function creates a new array object of linefill type elements.
index (series int) The index of the element to remove.
array.reverse(...)
DESCRIPTION
The function reverses an array. The first array element becomes the last, and the last array element becomes the first.
array.reverse(id) → void
EXAMPLE
//@version=5
indicator("array.reverse example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.get(a, 0))
array.reverse(a)
plot(array.get(a, 0))
ARGUMENTS
id (any array type) An array object.
array.set(...)
DESCRIPTION
The function sets the value of the element at the specified index.
array.set(id, index, value) → void
EXAMPLE
//@version=5
indicator("array.set example")
a = array.new_float(10)
for i = 0 to 9
array.set(a, i, close[i])
plot(array.sum(a) / 10)
ARGUMENTS
id (any array type) An array object.
index (series int) The index of the element to be modified.
value (series <type of the array's elements>) The new value to be set.
array.shift(...)
DESCRIPTION
The function removes an array's first element and returns its value.
The function returns the number of elements in an array.
array.size(id) → series int
EXAMPLE
//@version=5
indicator("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))
RETURNS
The number of elements in the array.
ARGUMENTS
id (any array type) An array object.
array.slice(...)
DESCRIPTION
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.
//@version=5
indicator("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 array
slice = array.slice(a, 0, 5)
plot(array.sum(a) / 10)
plot(array.sum(slice) / 5)
RETURNS
A shallow copy of an array's slice.
ARGUMENTS
id (any array type) An array object.
index_from (series int) Zero-based index at which to begin extraction.
index_to (series int) Zero-based index before which to end extraction. The function extracts up to but not including the element with this index.
array.sort(...)
DESCRIPTION
The function sorts the elements of an array.
array.sort(id, order) → void
EXAMPLE
//@version=5
indicator("array.sort example")
a = array.new_float(0,0)
for i = 0 to 5
array.push(a, high[i])
array.sort(a, order.descending)
if barstate.islast
label.new(bar_index, close, str.tostring(a))
ARGUMENTS
id (int[]/float[]/string[]) An array object.
order (input sort_order) The sort order: order.ascending (default) or order.descending.
array.sort_indices(...)
DESCRIPTION
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.
//@version=5
indicator("array.standardize example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
b = array.standardize(a)
plot(array.min(b))
plot(array.max(b))
RETURNS
The array of standardized elements.
ARGUMENTS
id (int[]/float[]) An array object.
array.stdev(...)
DESCRIPTION
The function returns the standard deviation of an array's elements.
array.stdev(id, biased) → series float
array.stdev(id, biased) → series int
EXAMPLE
//@version=5
indicator("array.stdev example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.stdev(a))
RETURNS
The standard deviation of the array's elements.
ARGUMENTS
id (int[]/float[]) An array object.
biased (series bool) Determines which estimate should be used. Optional. The default is true.
array.sum(...)
DESCRIPTION
The function returns the sum of an array's elements.
array.sum(id) → series float
array.sum(id) → series int
EXAMPLE
//@version=5
indicator("array.sum example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.sum(a))
RETURNS
The sum of the array's elements.
ARGUMENTS
id (int[]/float[]) An array object.
array.unshift(...)
DESCRIPTION
The function inserts the value at the beginning of the array.
color (series color) Color of bars. You can use constants like 'red' or '#ff001a' as well as complex expressions like 'close >= open ? color.green : color.red'. Required argument.
offset (series int) Shifts the color series to the left or to the right on the given number of bars. Default is 0.
editable (const bool) If true then barcolor style will be editable in Format dialog. Default is true.
show_last (input int) If set, defines the number of bars (from the last bar back to the past) to fill on chart.
title (const string) Title of the barcolor. Optional argument.
display (input plot_simple_display) Controls where the barcolor is displayed. Possible values are: display.none.
color (series color) Color of the filled background. You can use constants like 'red' or '#ff001a' as well as complex expressions like 'close >= open ? color.green : color.red'. Required argument.
offset (series int) Shifts the color series to the left or to the right on the given number of bars. Default is 0.
editable (const bool) If true then bgcolor style will be editable in Format dialog. Default is true.
show_last (input int) If set, defines the number of bars (from the last bar back to the past) to fill on chart.
title (const string) Title of the bgcolor. Optional argument.
display (input plot_simple_display) Controls where the bgcolor is displayed. Possible values are: display.none.
//@version=5
indicator("box.new")
var b = box.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, border_style=line.style_dashed)
box.set_lefttop(b, time, 100)
box.set_rightbottom(b, time + 60 * 60 * 24, 500)
box.set_bgcolor(b, color.green)
RETURNS
The ID of a box object which may be used in box.set_*() and box.get_*() functions.
ARGUMENTS
left (series int) Bar index (if xloc = xloc.bar_index cannot be drawn further than 500 bars into the future.
top (series int/float) Price of the top border of the box.
right (series int) Bar index (if xloc = xloc.bar_index cannot be drawn further than 500 bars into the future.
bottom (series int/float) Price of the bottom border of the box.
border_color (series color) Color of the four borders. Optional. The default is color.blue.
border_width (series int) Width of the four borders, in pixels. Optional. The default is 1 pixel.
border_style (series string) Style of the four borders. Possible values: line.style_solid.
extend (series string) When extend.none.
xloc (series string) Determines whether the arguments to 'left' and 'right' are a bar index or a time value. If xloc = xloc.bar_index.
bgcolor (series color) Background color of the box. Optional. The default is color.blue.
text (series string) The text to be displayed inside the box. Optional. The default is empty string.
text_size (series string) The size of the text. An optional parameter, the default value is size.auto.
text_font_family (series string) The font family of the text. Optional. The default value is font.family_default.
text_color (series color) The color of the text. Optional. The default is color.black.
text_halign (series string) The horizontal alignment of the box's text. Optional. The default value is text.align_center.
text_valign (series string) The vertical alignment of the box's text. Optional. The default value is text.align_center.
text_wrap (series string) Defines whether the text is presented in a single line, extending past the width of the box if necessary, or wrapped so every line is no wider than the box itself (and clipped by the bottom border of the box if the height of the resulting wrapped text is higher than the height of the box). Optional. The default value is text.wrap_none.
box.set_bgcolor(...)
DESCRIPTION
Sets the background color of the box.
box.set\_bgcolor(id, color) → void
ARGUMENTS
id (series box) A box object.
color (series color) New background color.
box.set_border_color(...)
DESCRIPTION
Sets the border color of the box.
box.set\_border\_color(id, color) → void
ARGUMENTS
id (series box) A box object.
color (series color) New border color.
box.set_border_style(...)
DESCRIPTION
Sets the border style of the box.
box.set\_border\_style(id, style) → void
ARGUMENTS
id (series box) A box object.
style (series string) New border style.
box.set_border_width(...)
DESCRIPTION
Sets the border width of the box.
box.set\_border\_width(id, width) → void
ARGUMENTS
id (series box) A box object.
width (series int) Width of the four borders, in pixels.
box.set_bottom(...)
DESCRIPTION
Sets the bottom coordinate of the box.
box.set\_bottom(id, bottom) → void
ARGUMENTS
id (series box) A box object.
bottom (series int/float) Price value of the bottom border.
box.set_extend(...)
DESCRIPTION
Sets extending type of the border of this box object. When extend.none, the horizontal borders are extended on both sides.
box.set\_extend(id, extend) → void
ARGUMENTS
id (series box) A box object.
extend (series string) New extending type.
box.set_left(...)
DESCRIPTION
Sets the left coordinate of the box.
box.set\_left(id, left) → void
ARGUMENTS
id (series box) A box object.
left (series int) Bar index or bar time of the left border. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
box.set_lefttop(...)
DESCRIPTION
Sets the left and top coordinates of the box.
box.set\_lefttop(id, left, top) → void
ARGUMENTS
id (series box) A box object.
left (series int) Bar index or bar time of the left border.
top (series int/float) Price value of the top border.
box.set_right(...)
DESCRIPTION
Sets the right coordinate of the box.
box.set\_right(id, right) → void
ARGUMENTS
id (series box) A box object.
right (series int) Bar index or bar time of the right border. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
box.set_rightbottom(...)
DESCRIPTION
Sets the right and bottom coordinates of the box.
box.set\_rightbottom(id, right, bottom) → void
ARGUMENTS
id (series box) A box object.
right (series int) Bar index or bar time of the right border.
bottom (series int/float) Price value of the bottom border.
box.set_text(...)
DESCRIPTION
The function sets the text in the box.
box.set\_text(id, text) → void
ARGUMENTS
id (series box) A box object.
text (series string) The text to be displayed inside the box.
box.set_text_color(...)
DESCRIPTION
The function sets the color of the text inside the box.
box.set\_text\_color(id, text\_color) → void
ARGUMENTS
id (series box) A box object.
text_color (series color) The color of the text.
box.set_text_font_family(...)
DESCRIPTION
The function sets the font family of the text inside the box.
//@version=5
indicator("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)
ARGUMENTS
id (series box) A box object.
text_font_family (series string) The font family of the text. Possible values: font.family_default.
box.set_text_halign(...)
DESCRIPTION
The function sets the horizontal alignment of the box's text.
box.set\_text\_halign(id, text\_halign) → void
ARGUMENTS
id (series box) A box object.
text_halign (series string) The horizontal alignment of a box's text. Possible values: text.align_left.
box.set_text_size(...)
DESCRIPTION
The function sets the size of the box's text.
box.set\_text\_size(id, text\_size) → void
ARGUMENTS
id (series box) A box object.
text_size (series string) The size of the text. Possible values: size.auto.
box.set_text_valign(...)
DESCRIPTION
The function sets the vertical alignment of a box's text.
box.set\_text\_valign(id, text\_valign) → void
ARGUMENTS
id (series box) A box object.
text_valign (series string) The vertical alignment of the box's text. Possible values: text.align_top.
box.set_text_wrap(...)
DESCRIPTION
The function sets the mode of wrapping of the text inside the box.
box.set\_text\_wrap(id, text\_wrap) → void
ARGUMENTS
id (series box) A box object.
text_wrap (series string) The mode of the wrapping. Possible values: text.wrap_auto.
box.set_top(...)
DESCRIPTION
Sets the top coordinate of the box.
box.set\_top(id, top) → void
ARGUMENTS
id (series box) A box object.
top (series int/float) Price value of the top border.
color(...)
DESCRIPTION
Casts na to color
color(x) → const color
color(x) → input color
color(x) → simple color
color(x) → series color
RETURNS
The value of the argument after casting to color.
color.b(...)
DESCRIPTION
Retrieves the value of the color's blue component.
The value (0 to 255) of the color's blue component.
ARGUMENTS
color (series color) Color.
color.from_gradient(...)
DESCRIPTION
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.
color.from\_gradient(value, bottom\_value, top\_value, bottom\_color, top\_color) → series color
dayofmonth(time) → series int
dayofmonth(time, timezone) → series int
RETURNS
Day of month (in exchange timezone) for provided UNIX time.
ARGUMENTS
time (series int) UNIX time in milliseconds.
timezone (series string) Allows adjusting the returned value to a time zone specified in either UTC/GMT notation (e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). Optional. The default is syminfo.timezone.
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.
dayofweek(...)
DESCRIPTION
dayofweek(time) → series int
dayofweek(time, timezone) → series int
RETURNS
Day of week (in exchange timezone) for provided UNIX time.
ARGUMENTS
time (series int) UNIX time in milliseconds.
timezone (series string) Allows adjusting the returned value to a time zone specified in either UTC/GMT notation (e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). Optional. The default is syminfo.timezone.
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970.
fill(...)
DESCRIPTION
Fills background between two plots or hlines with a given color.
hline1 (hline) The first hline object. Required argument.
hline2 (hline) The second hline object. Required argument.
plot1 (plot) The first plot object. Required argument.
plot2 (plot) The second plot object. Required argument.
color (series color) Color of the background fill. You can use constants like 'color=color.red' or 'color=#ff001a' as well as complex expressions like 'color = close >= open ? color.green : color.red'. Optional argument.
title (const string) Title of the created fill object. Optional argument.
editable (const bool) If true then fill style will be editable in Format dialog. Default is true.
show_last (input int) If set, defines the number of bars (from the last bar back to the past) to fill on chart.
fillgaps (const bool) Controls continuing fills on gaps, i.e., when one of the plot() calls returns an na value. When true, the last fill will continue on gaps. The default is false.
display (input plot_simple_display) Controls where the fill is displayed. Possible values are: display.none.
top_value (series int/float) Value where the gradient uses the `top_color`.
bottom_value (series int/float) Value where the gradient uses the `bottom_color`.
top_color (series color) Color of the gradient at the topmost value.
bottom_color (series color) Color of the gradient at the bottommost value.
fixnan(...)
DESCRIPTION
For a given series replaces NaN values with previous nearest non-NaN value.
fixnan(source) → series float
fixnan(source) → series int
fixnan(source) → series bool
fixnan(source) → series color
RETURNS
Series without na gaps.
ARGUMENTS
source (series int/float/bool/color) Source used for the calculation.
//@version=5
indicator("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))
RETURNS
An hline object, that can be used in fill
ARGUMENTS
price (input int/float) Price value at which the object will be rendered. Required argument.
title (const string) Title of the object.
color (input color) Color of the rendered line. Must be a constant value (not an expression). Optional argument.
linestyle (input hline_style) Style of the rendered line. Possible values are: hline.style_solid. Optional argument.
linewidth (input int) Width of the rendered line. Default value is 1.
editable (const bool) If true then hline style will be editable in Format dialog. Default is true.
display (input plot_simple_display) Controls where the hline is displayed. Possible values are: display.none.
hour(...)
DESCRIPTION
hour(time) → series int
hour(time, timezone) → series int
RETURNS
Hour (in exchange timezone) for provided UNIX time.
ARGUMENTS
time (series int) UNIX time in milliseconds.
timezone (series string) Allows adjusting the returned value to a time zone specified in either UTC/GMT notation (e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). Optional. The default is syminfo.timezone.
indicator(...)
DESCRIPTION
This declaration statement designates the script as an indicator and sets a number of indicator-related properties.
title (const string) The title of the script. It is displayed on the chart when no `shorttitle` argument is used, and becomes the publication's default title when publishing the script.
shorttitle (const string) The script's display name on charts. If specified, it will replace the `title` argument in most chart-related windows. Optional. The default is the argument used for `title`.
overlay (const bool) If true.
format (const string) Specifies the formatting of the script's displayed values. Possible values: format.inherit.
precision (const int) Specifies the number of digits after the floating point of the script's displayed values. Must be a non-negative integer no greater than 16. If `format` is set to format.inherit. Optional. The default is inherited from the precision of the chart's symbol.
scale (scale_type) The price scale used. Possible values: scale.right value can only be applied in combination with `overlay = true`. Optional. By default, the script uses the same scale as the chart.
max_bars_back (const int) The length of the historical buffer the script keeps for every variable and function, which determines how many past values can be referenced using the `[]` history-referencing operator. The required buffer size is automatically detected by the Pine Script™ runtime. Using this parameter is only necessary when a runtime error occurs because automatic detection fails. More information on the underlying mechanics of the historical buffer can be found in our Help Center. Optional. The default is 0.
timeframe (const string) 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.
timeframe_gaps (const bool) Specifies how the indicator's values are displayed on chart bars when the `timeframe` is higher than the chart's. If true.
explicit_plot_zorder (const bool) Specifies the order in which the script's plots, fills, and hlines are rendered. If true.
max_lines_count (const int) The number of last line drawings displayed. Possible values: 1-500. The count is approximate; more drawings than the specified count may be displayed. Optional. The default is 50.
max_labels_count (const int) The number of last label drawings displayed. Possible values: 1-500. The count is approximate; more drawings than the specified count may be displayed. Optional. The default is 50.
max_boxes_count (const int) The number of last box drawings displayed. Possible values: 1-500. The count is approximate; more drawings than the specified count may be displayed. Optional. The default is 50.
input(...)
DESCRIPTION
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.
defval (const int/float/bool/string/color or source-type built-ins) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where script users can change it. Source-type built-ins are built-in series float variables that specify the source of the calculation: `close`, `hlc3`, etc.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
input.bool(...)
DESCRIPTION
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.
defval (const bool) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.color(...)
DESCRIPTION
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.
input.color(defval, title, tooltip, inline, group, confirm) → input color
defval (const color) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.float(...)
DESCRIPTION
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.
defval (const int/float) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where script users can change it. When a list of values is used with the `options` parameter, the value must be one of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
minval (const int/float) Minimal possible value of the input variable. Optional.
maxval (const int/float) Maximum possible value of the input variable. Optional.
step (const int/float) Step value used for incrementing/decrementing the input. Optional. The default is 1.
options (tuple of const int/float values: [val1, val2, ...]) A list of options to choose from a dropdown menu, separated by commas and enclosed in square brackets: [val1, val2, ...]. When using this parameter, the `minval`, `maxval` and `step` parameters cannot be used.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.int(...)
DESCRIPTION
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.
defval (const int) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where script users can change it. When a list of values is used with the `options` parameter, the value must be one of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
minval (const int) Minimal possible value of the input variable. Optional.
maxval (const int) Maximum possible value of the input variable. Optional.
step (const int) Step value used for incrementing/decrementing the input. Optional. The default is 1.
options (tuple of const int values: [val1, val2, ...]) A list of options to choose from a dropdown menu, separated by commas and enclosed in square brackets: [val1, val2, ...]. When using this parameter, the `minval`, `maxval` and `step` parameters cannot be used.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.price(...)
DESCRIPTION
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.
defval (const int/float) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, the interactive input mode is enabled and the selection is done by clicking on the chart when the indicator is added to the chart, or by selecting the indicator and moving the selection after that. Optional. The default is false.
input.session(...)
DESCRIPTION
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.
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it. When a list of values is used with the `options` parameter, the value must be one of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
options (tuple of const string values: [val1, val2, ...]) A list of options to choose from.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.source(...)
DESCRIPTION
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 call, the user can also select an output from another indicator on their chart as the source.
input.source(defval, title, tooltip, inline, group) → series float
defval (open/high/low/close/hl2/hlc3/ohlc4/hlcc4) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
input.string(...)
DESCRIPTION
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.
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it. When a list of values is used with the `options` parameter, the value must be one of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
options (tuple of const string values: [val1, val2, ...]) A list of options to choose from.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.symbol(...)
DESCRIPTION
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.
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.text_area(...)
DESCRIPTION
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.
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
input.time(...)
DESCRIPTION
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.
input.time(defval, title, tooltip, inline, group, confirm) → input int
defval (const int) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it. The value can be a timestamp function, but only if it uses a date argument in const string format.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, the interactive input mode is enabled and the selection is done by clicking on the chart when the indicator is added to the chart, or by selecting the indicator and moving the selection after that. Optional. The default is false.
input.timeframe(...)
DESCRIPTION
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.
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab, from where the user can change it. When a list of values is used with the `options` parameter, the value must be one of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is specified, but it is empty, the name will be an empty string.
options (tuple of const string values: [val1, val2, ...]) A list of options to choose from.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default value is false.
int(...)
DESCRIPTION
Casts na or truncates float value to int
int(x) → simple int
int(x) → input int
int(x) → const int
int(x) → series int
//@version=5
indicator("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)
ARGUMENTS
id (series label) A label object.
text_font_family (series string) The font family of the text. Possible values: font.family_default.
label.set_textalign(...)
DESCRIPTION
Sets the alignment for the label text.
label.set\_textalign(id, textalign) → void
ARGUMENTS
id (series label) Label object.
textalign (series string) Label text alignment. Possible values: text.align_left.
label.set_textcolor(...)
DESCRIPTION
Sets color of the label text.
label.set\_textcolor(id, textcolor) → void
ARGUMENTS
id (series label) Label object.
textcolor (series color) New text color.
label.set_tooltip(...)
DESCRIPTION
Sets the tooltip text.
label.set\_tooltip(id, tooltip) → void
ARGUMENTS
id (series label) Label object.
tooltip (series string) Tooltip text.
label.set_x(...)
DESCRIPTION
Sets bar index or bar time (depending on the xloc) of the label position.
label.set\_x(id, x) → void
ARGUMENTS
id (series label) Label object.
x (series int) New bar index or bar time of the label position. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
label.set_xloc(...)
DESCRIPTION
Sets x-location and new bar index/time value.
label.set\_xloc(id, x, xloc) → void
ARGUMENTS
id (series label) Label object.
x (series int) New bar index or bar time of the label position.
xloc (series string) New x-location value.
label.set_xy(...)
DESCRIPTION
Sets bar index/time and price of the label position.
label.set\_xy(id, x, y) → void
ARGUMENTS
id (series label) Label object.
x (series int) New bar index or bar time of the label position. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
y (series int/float) New price of the label position.
label.set_y(...)
DESCRIPTION
Sets price of the label position
label.set\_y(id, y) → void
ARGUMENTS
id (series label) Label object.
y (series int/float) New price of the label position.
label.set_yloc(...)
DESCRIPTION
Sets new y-location calculation algorithm.
label.set\_yloc(id, yloc) → void
ARGUMENTS
id (series label) Label object.
yloc (series string) New y-location value.
library(...)
DESCRIPTION
Declaration statement identifying a script as a library.
library(title, overlay) → void
EXAMPLE
//@version=5
// @description Math library
library("num_methods", overlay = true)
// Calculate "sinh()" from the float parameter `x`
export sinh(float x) =>
(math.exp(x) - math.exp(-x)) / 2.0
plot(sinh(0))
ARGUMENTS
title (const string) The title of the library and its identifier. It cannot contain spaces, special characters or begin with a digit. It is used as the publication's default title, and to uniquely identify the library in the import statement, when another script uses it. It is also used as the script's name on the chart.
overlay (const bool) If true, the library will be added over the chart. If false, it will be added in a separate pane. Optional. The default is false.
line(...)
DESCRIPTION
Casts na to line
line(x) → series line
RETURNS
The value of the argument after casting to line.
line.copy(...)
DESCRIPTION
Clones the line object.
line.copy(id) → series line
EXAMPLE
//@version=5
indicator('Last 100 bars price range', overlay = true)
LOOKBACK = 100
highest = 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.
ARGUMENTS
id (series line) Line object.
line.delete(...)
DESCRIPTION
Deletes the specified line object. If it has already been deleted, does nothing.
line.delete(id) → void
ARGUMENTS
id (series line) Line object to delete.
line.get_price(...)
DESCRIPTION
Returns the price level of a line at a given bar index.
line.get\_price(id, x) → series float
EXAMPLE
//@version=5
indicator("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'.
ARGUMENTS
id (series line) Line object.
x (series int) Bar index for which price is required.
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.
line.get_x1(...)
DESCRIPTION
Returns UNIX time or bar index (depending on the last xloc value set) of the first point of the line.
line.get\_x1(id) → series int
EXAMPLE
//@version=5
indicator("line.get_x1")
my_line = line.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time)
a = line.get_x1(my_line)
plot(time - line.get_x1(my_line)) //draws zero plot
RETURNS
UNIX timestamp (in milliseconds) or bar index.
ARGUMENTS
id (series line) Line object.
line.get_x2(...)
DESCRIPTION
Returns UNIX time or bar index (depending on the last xloc value set) of the second point of the line.
line.get\_x2(id) → series int
RETURNS
UNIX timestamp (in milliseconds) or bar index.
ARGUMENTS
id (series line) Line object.
line.get_y1(...)
DESCRIPTION
Returns price of the first point of the line.
line.get\_y1(id) → series float
RETURNS
Price value.
ARGUMENTS
id (series line) Line object.
line.get_y2(...)
DESCRIPTION
Returns price of the second point of the line.
line.get\_y2(id) → series float
RETURNS
Price value.
ARGUMENTS
id (series line) Line object.
line.new(...)
DESCRIPTION
Creates new line object.
line.new(x1, y1, x2, y2, xloc, extend, color, style, width) → series line
EXAMPLE
//@version=5
indicator("line.new")
var line1 = line.new(0, low, bar_index, high, extend=extend.right)
var line2 = line.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, style=line.style_dashed)
line.set_x2(line1, 0)
line.set_xloc(line1, time, time + 60 * 60 * 24, xloc.bar_time)
line.set_color(line2, color.green)
line.set_width(line2, 5)
RETURNS
Line ID object which may be passed to line.setXXX and line.getXXX functions.
ARGUMENTS
x1 (series int) Bar index (if xloc = xloc.bar_index cannot be drawn further than 500 bars into the future.
y1 (series int/float) Price of the first point of the line.
x2 (series int) Bar index (if xloc = xloc.bar_index cannot be drawn further than 500 bars into the future.
y2 (series int/float) Price of the second point of the line.
xloc (series string) See description of x1 argument. Possible values: xloc.bar_index.
extend (series string) If extend=[extend.none.
color (series color) Line color.
style (series string) Line style. Possible values: line.style_solid.
width (series int) Line width in pixels.
line.set_color(...)
DESCRIPTION
Sets the line color
line.set\_color(id, color) → void
ARGUMENTS
id (series line) Line object.
color (series color) New line color
line.set_extend(...)
DESCRIPTION
Sets extending type of this line object. If extend=[extend.none, draws a straight line that goes through these points.
line.set\_extend(id, extend) → void
ARGUMENTS
id (series line) Line object.
extend (series string) New extending type.
line.set_style(...)
DESCRIPTION
Sets the line style
line.set\_style(id, style) → void
ARGUMENTS
id (series line) Line object.
style (series string) New line style.
line.set_width(...)
DESCRIPTION
Sets the line width.
line.set\_width(id, width) → void
ARGUMENTS
id (series line) Line object.
width (series int) New line width in pixels.
line.set_x1(...)
DESCRIPTION
Sets bar index or bar time (depending on the xloc) of the first point.
line.set\_x1(id, x) → void
ARGUMENTS
id (series line) Line object.
x (series int) Bar index or bar time. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
line.set_x2(...)
DESCRIPTION
Sets bar index or bar time (depending on the xloc) of the second point.
line.set\_x2(id, x) → void
ARGUMENTS
id (series line) Line object.
x (series int) Bar index or bar time. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
line.set_xloc(...)
DESCRIPTION
Sets x-location and new bar index/time values.
line.set\_xloc(id, x1, x2, xloc) → void
ARGUMENTS
id (series line) Line object.
x1 (series int) Bar index or bar time of the first point.
x2 (series int) Bar index or bar time of the second point.
xloc (series string) New x-location value.
line.set_xy1(...)
DESCRIPTION
Sets bar index/time and price of the first point.
line.set\_xy1(id, x, y) → void
ARGUMENTS
id (series line) Line object.
x (series int) Bar index or bar time. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
y (series int/float) Price.
line.set_xy2(...)
DESCRIPTION
Sets bar index/time and price of the second point
line.set\_xy2(id, x, y) → void
ARGUMENTS
id (series line) Line object.
x (series int) Bar index or bar time.
y (series int/float) Price.
line.set_y1(...)
DESCRIPTION
Sets price of the first point
line.set\_y1(id, y) → void
ARGUMENTS
id (series line) Line object.
y (series int/float) Price.
line.set_y2(...)
DESCRIPTION
Sets price of the second point.
line.set\_y2(id, y) → void
ARGUMENTS
id (series line) Line object.
y (series int/float) Price.
linefill(...)
DESCRIPTION
Casts na to linefill.
linefill(x) → series linefill
RETURNS
The value of the argument after casting to linefill.
linefill.delete(...)
DESCRIPTION
Deletes the specified linefill object. If it has already been deleted, does nothing.
linefill.delete(id) → void
ARGUMENTS
id (series linefill) A linefill object.
linefill.get_line1(...)
DESCRIPTION
Returns the ID of the first line used in the `id` linefill.
linefill.get\_line1(id) → series line
ARGUMENTS
id (series linefill) A linefill object.
linefill.get_line2(...)
DESCRIPTION
Returns the ID of the second line used in the `id` linefill.
linefill.get\_line2(id) → series line
ARGUMENTS
id (series linefill) A linefill object.
linefill.new(...)
DESCRIPTION
Creates a new linefill object and displays it on the chart, filling the space between `line1` and `line2` with the color specified in `color`.
linefill.new(line1, line2, color) → series linefill
RETURNS
The ID of a linefill object that can be passed to other linefill.*() functions.
ARGUMENTS
line1 (series line) First line object.
line2 (series line) Second line object.
color (series color) The color used to fill the space between the lines.
If both lines are extended in the same direction relative to the lines themselves (e.g. both have extend.right, the space between line extensions will also be filled.
linefill.set_color(...)
DESCRIPTION
The function sets the color of the linefill object passed to it.
linefill.set\_color(id, color) → void
ARGUMENTS
id (series linefill) A linefill object.
color (series color) The color of the linefill object.
math.abs(...)
DESCRIPTION
Absolute value of `number` is `number` if `number` >= 0, or -`number` otherwise.
math.abs(number) → simple int
math.abs(number) → input int
math.abs(number) → const int
math.abs(number) → series int
math.abs(number) → simple float
math.abs(number) → input float
math.abs(number) → const float
math.abs(number) → series float
RETURNS
The absolute value of `number`.
math.acos(...)
DESCRIPTION
The acos function returns the arccosine (in radians) of number such that cos(acos(y)) = y for y in range [-1, 1].
`base` raised to the power of `exponent`. If `base` is a series, it is calculated elementwise.
ARGUMENTS
base (series int/float) Specify the base to use.
exponent (series int/float) Specifies the exponent.
math.random(...)
DESCRIPTION
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.
math.random(min, max, seed) → series float
RETURNS
A random value.
ARGUMENTS
min (series int/float) The lower bound of the range of random values. The value is not included in the range. The default is 0.
max (series int/float) The upper bound of the range of random values. The value is not included in the range. The default is 1.
seed (series int) Optional argument. When the same seed is used, allows successive calls to the function to produce a repeatable set of values.
math.round(...)
DESCRIPTION
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.
math.round(number) → simple int
math.round(number) → input int
math.round(number) → const int
math.round(number) → series int
math.round(number, precision) → simple float
math.round(number, precision) → input float
math.round(number, precision) → const float
math.round(number, precision) → series float
RETURNS
The value of `number` rounded to the nearest integer, or according to precision.
ARGUMENTS
number (series int/float) The value to be rounded.
precision (series int) Optional argument. Decimal places to which `number` will be rounded. When no argument is supplied, rounding is to the nearest integer.
math.round_to_mintick(...)
DESCRIPTION
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.
math.round\_to\_mintick(number) → simple float
math.round\_to\_mintick(number) → series float
RETURNS
The `number` rounded to tick precision.
ARGUMENTS
number (series int/float) The value to be rounded.
math.sign(...)
DESCRIPTION
Sign (signum) of `number` is zero if `number` is zero, 1.0 if `number` is greater than zero, -1.0 if `number` is less than zero.
//@version=5
indicator("`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=5
indicator("`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))
ARGUMENTS
id (any matrix type) A matrix object.
column (series int) The index of the column after which the new column will be inserted. Optional. The default value is matrix.columns.
array_id (any array type) An array to be inserted. Optional.
matrix.add_row(...)
DESCRIPTION
The function adds a row at the `row` index of the `id` matrix. The row can consist of `na` values, or an array can be used to provide values.
//@version=5
indicator("`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=5
indicator("`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))
ARGUMENTS
id (any matrix type) A matrix object.
row (series int) The index of the row after which the new row will be inserted. Optional. The default value is matrix.rows.
array_id (any array type) An array to be inserted. Optional.
matrix.avg(...)
DESCRIPTION
The function calculates the average of all elements in the matrix.
matrix.avg(id) → series float
matrix.avg(id) → series int
EXAMPLE
//@version=5
indicator("`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')
RETURNS
The average value from the `id` matrix.
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.col(...)
DESCRIPTION
The function creates a one-dimensional array from the elements of a matrix column.
matrix.col(id, column) → type\[\]
EXAMPLE
//@version=5
indicator("`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.
ARGUMENTS
id (any matrix type) A matrix object.
column (series int) Index of the required column.
matrix.columns(...)
DESCRIPTION
The function returns the number of columns in the matrix.
matrix.columns(id) → series int
EXAMPLE
//@version=5
indicator("`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) + "\n" + str.tostring(m))
RETURNS
The number of columns in the matrix `id`.
ARGUMENTS
id (any matrix type) A matrix object.
matrix.concat(...)
DESCRIPTION
The function appends the `m2` matrix to the `m1` matrix.
Returns the `id1` matrix concatenated with the `id2` matrix.
ARGUMENTS
id1 (any matrix type) Matrix object to concatenate into.
id2 (any matrix type) Matrix object whose elements will be appended to `id1`.
matrix.copy(...)
DESCRIPTION
The function creates a new matrix which is a copy of the original.
matrix.copy(id) → matrix<type>
EXAMPLE
//@version=5
indicator("`matrix.copy()` Example")
// For efficiency, 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))
RETURNS
A new matrix object of the copied `id` matrix.
ARGUMENTS
id (any matrix type) A matrix object to copy.
matrix.det(...)
DESCRIPTION
The function returns the determinant of a square matrix.
matrix.det(id) → series float
matrix.det(id) → series int
EXAMPLE
//@version=5
indicator("`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')
RETURNS
The determinant value of the `id` matrix.
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.diff(...)
DESCRIPTION
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=5
indicator("`matrix.diff()` Example 1")
// For efficiency, 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=5
indicator("`matrix.diff()` Example 2")
// For efficiency, 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`.
ARGUMENTS
id1 (matrix/matrix) Matrix to subtract from.
id2 (series int/float/matrix/matrix) Matrix object or a scalar value to be subtracted.
matrix.eigenvalues(...)
DESCRIPTION
The function returns an array containing the eigenvalues of a square matrix.
//@version=5
indicator("`matrix.eigenvectors()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix
var m1 = matrix.new<int>(2, 2, 1)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 2)
matrix.set(m1, 0, 1, 4)
matrix.set(m1, 1, 0, 6)
matrix.set(m1, 1, 1, 8)
// Get the eigenvectors of the matrix.
m2 = matrix.eigenvectors(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, "Matrix Eigenvectors:")
table.cell(t, 1, 1, str.tostring(m2))
RETURNS
A new matrix containing the eigenvectors of the `id` matrix.
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.elements_count(...)
DESCRIPTION
The function returns the total number of all matrix elements.
matrix.elements\_count(id) → series int
ARGUMENTS
id (any matrix type) A matrix object.
matrix.fill(...)
DESCRIPTION
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`.
//@version=5
indicator("`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 2 and 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))
ARGUMENTS
id (any matrix type) A matrix object.
value (series <type of the matrix's elements>) The value to fill with.
from_column (series int) Column index from which the fill will begin (inclusive). Optional. The default value is 0.
to_column (series int) Column index where the fill will end (non inclusive). Optional. The default value is matrix.columns.
from_row (series int) Row index from which the fill will begin (inclusive). Optional. The default value is 0.
to_row (series int) Row index where the fill will end (not inclusive). Optional. The default value is matrix.rows.
matrix.get(...)
DESCRIPTION
The function returns the element with the specified index of the matrix.
matrix.get(id, row, column) → <matrix\_type>
EXAMPLE
//@version=5
indicator("`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.
ARGUMENTS
id (any matrix type) A matrix object.
row (series int) Index of the required row.
column (series int) Index of the required column.
matrix.inv(...)
DESCRIPTION
The function returns the inverse of a square matrix.
//@version=5
indicator("`matrix.kron()` Example")
// Display using a table.
if barstate.islastconfirmedhistory
// Create two matrices with default values `1` and `2`.
var m1 = matrix.new<float>(2, 2, 1)
var m2 = matrix.new<float>(2, 2, 2)
// Calculate the Kronecker product of the matrices.
var m3 = matrix.kron(m1, m2)
// Display matrix elements.
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, "⊗")
table.cell(t, 2, 0, "Matrix 2:")
table.cell(t, 2, 1, str.tostring(m2))
table.cell(t, 3, 1, "=")
table.cell(t, 4, 0, "Kronecker product:")
table.cell(t, 4, 1, str.tostring(m3))
RETURNS
A new matrix containing the Kronecker product of `id1` and `id2`.
ARGUMENTS
id1 (matrix/matrix) First matrix object.
id2 (matrix/matrix) Second matrix object.
matrix.max(...)
DESCRIPTION
The function returns the largest value from the matrix elements.
matrix.max(id) → series float
matrix.max(id) → series int
EXAMPLE
//@version=5
indicator("`matrix.max()` Example")
// Create a 2x2 matrix.
var m = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m, 0, 0, 1)
matrix.set(m, 0, 1, 2)
matrix.set(m, 1, 0, 3)
matrix.set(m, 1, 1, 4)
// Get the maximum value in the matrix.
var x = matrix.max(m)
plot(x, 'Matrix maximum value')
RETURNS
The maximum value from the `id` matrix.
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.median(...)
DESCRIPTION
The function calculates the median of matrix elements.
matrix.median(id) → series float
matrix.median(id) → series int
EXAMPLE
//@version=5
indicator("`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')
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.min(...)
DESCRIPTION
The function returns the smallest value from the matrix elements.
matrix.min(id) → series float
matrix.min(id) → series int
EXAMPLE
//@version=5
indicator("`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')
RETURNS
The smallest value from the `id` matrix.
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.mode(...)
DESCRIPTION
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.
matrix.mode(id) → series float
matrix.mode(id) → series int
EXAMPLE
//@version=5
indicator("`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. Returns ‘na’ if none exists.
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.mult(...)
DESCRIPTION
The function returns a new matrix resulting from the product.
//@version=5
indicator("`matrix.mult()` Example 1")
// For efficiency, 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=5
indicator("`matrix.mult()` Example 2")
// For efficiency, 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=5
indicator("`matrix.mult()` Example 3")
// For efficiency, 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`.
ARGUMENTS
id1 (matrix/matrix) First matrix object.
id2 (series int/float/matrix/matrix/int[]/float[]) Second matrix object, value or array.
matrix.new(...)
DESCRIPTION
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 ("").
Create a matrix of elements with the same initial value
EXAMPLE
//@version=5
indicator("`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=5
indicator("`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)
for i = 0 to rows <= 0 ? na : rows - 1
for j = 0 to columns <= 0 ? na : columns - 1
matrix.set(m, i, j, array.get(data, i * columns + j))
m
// 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=5
indicator("`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, "\n")
var rows = array.size(rowsArray)
var cols = array.size(str.split(array.get(rowsArray, 0), " "))
var matrix = matrix.new<float>(rows, cols, na)
row = 0
for rowString in rowsArray
col = 0
values = str.split(rowString, " ")
for val in values
matrix.set(matrix, row, col, str.tonumber(val))
col += 1
row += 1
matrix
stringInput = input.text_area("1 2 3\n4 5 6\n7 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=5
indicator("`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)
for i = 0 to rows - 1
for j = 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))
RETURNS
The ID of the new matrix object.
ARGUMENTS
rows (series int) Initial row count of the matrix. Optional. The default value is 0.
columns (series int) Initial column count of the matrix. Optional. The default value is 0.
initial_value (<matrix_type>) Initial value of all matrix elements. Optional. The default is 'na'.
matrix.pinv(...)
DESCRIPTION
The function returns the pseudoinverse of a matrix.
//@version=5
indicator("`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, "Matrix³:")
table.cell(t, 1, 1, str.tostring(m2))
RETURNS
The product of the `id` matrix by itself `power` times.
ARGUMENTS
id (matrix/matrix) A matrix object.
power (series int) The number of times the matrix will be multiplied by itself.
matrix.rank(...)
DESCRIPTION
The function calculates the rank of the matrix.
matrix.rank(id) → series int
EXAMPLE
//@version=5
indicator("`matrix.rank()` Example")
// For efficiency, 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))
RETURNS
The rank of the `id` matrix.
ARGUMENTS
id (any matrix type) A matrix object.
matrix.remove_col(...)
DESCRIPTION
The function removes the column at `column` index of the `id` matrix and returns an array containing the removed column's values.
matrix.remove\_col(id, column) → type\[\]
EXAMPLE
//@version=5
indicator("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.
ARGUMENTS
id (any matrix type) A matrix object.
column (series int) The index of the column to be removed. Optional. The default value is matrix.columns.
matrix.remove_row(...)
DESCRIPTION
The function removes the row at `row` index of the `id` matrix and returns an array containing the removed row's values.
matrix.remove\_row(id, row) → type\[\]
EXAMPLE
//@version=5
indicator("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.
ARGUMENTS
id (any matrix type) A matrix object.
row (series int) The index of the row to be deleted. Optional. The default value is matrix.rows.
matrix.reshape(...)
DESCRIPTION
The function rebuilds the `id` matrix to `rows` x `cols` dimensions.
matrix.reshape(id, rows, columns) → void
EXAMPLE
//@version=5
indicator("`matrix.reshape()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix.
var m1 = matrix.new<float>(2, 3)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 0, 2, 3)
matrix.set(m1, 1, 0, 4)
matrix.set(m1, 1, 1, 5)
matrix.set(m1, 1, 2, 6)
// Copy the matrix to a new one.
var m2 = matrix.copy(m1)
// Reshape the copy to a 3x2.
matrix.reshape(m2, 3, 2)
// 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, "Reshaped matrix:")
table.cell(t, 1, 1, str.tostring(m2))
ARGUMENTS
id (any matrix type) A matrix object.
rows (series int) The number of rows of the reshaped matrix.
columns (series int) The number of columns of the reshaped matrix.
matrix.reverse(...)
DESCRIPTION
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.
matrix.reverse(id) → void
EXAMPLE
//@version=5
indicator("`matrix.reverse()` Example")
// For efficiency, 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))
ARGUMENTS
id (any matrix type) A matrix object.
matrix.row(...)
DESCRIPTION
The function creates a one-dimensional array from the elements of a matrix row.
matrix.row(id, row) → type\[\]
EXAMPLE
//@version=5
indicator("`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.
ARGUMENTS
id (any matrix type) A matrix object.
row (series int) Index of the required row.
matrix.rows(...)
DESCRIPTION
The function returns the number of rows in the matrix.
matrix.rows(id) → series int
EXAMPLE
//@version=5
indicator("`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) + "\n" + str.tostring(m))
RETURNS
The number of rows in the matrix `id`.
ARGUMENTS
id (any matrix type) A matrix object.
matrix.set(...)
DESCRIPTION
The function assigns `value` to the element at the `row` and `column` of the `id` matrix.
matrix.set(id, row, column, value) → void
EXAMPLE
//@version=5
indicator("`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 1 and 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))
ARGUMENTS
id (any matrix type) A matrix object.
row (series int) The row index of the element to be modified.
column (series int) The column index of the element to be modified.
value (series <type of the matrix's elements>) The new value to be set.
matrix.sort(...)
DESCRIPTION
The function rearranges the rows in the `id` matrix following the sorted order of the values in the `column`.
matrix.sort(id, column, order) → void
EXAMPLE
//@version=5
indicator("`matrix.sort()` Example")
// For efficiency, 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))
ARGUMENTS
id (matrix/matrix/matrix) A matrix object to be sorted.
column (series int) Index of the column whose sorted values determine the new order of rows. Optional. The default value is 0.
order (input sort_order) The sort order. Possible values: order.ascending.
matrix.submatrix(...)
DESCRIPTION
The function extracts a submatrix of the `id` matrix within the specified indices.
//@version=5
indicator("`matrix.sum()` Example 1")
// For efficiency, 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=5
indicator("`matrix.sum()` Example 2")
// For efficiency, 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`.
ARGUMENTS
id1 (matrix/matrix) First matrix object.
id2 (series int/float/matrix/matrix) Second matrix object, or scalar value.
matrix.swap_columns(...)
DESCRIPTION
The function swaps the columns at the index `column1` and `column2` in the `id` matrix.
matrix.swap\_columns(id, column1, column2) → void
EXAMPLE
//@version=5
indicator("`matrix.swap_columns()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix with ‘na’ 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))
ARGUMENTS
id (any matrix type) A matrix object.
column1 (series int) Index of the first column to be swapped.
column2 (series int) Index of the second column to be swapped.
matrix.swap_rows(...)
DESCRIPTION
The function swaps the rows at the index `row1` and `row2` in the `id` matrix.
matrix.swap\_rows(id, row1, row2) → void
EXAMPLE
//@version=5
indicator("`matrix.swap_rows()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 3x2 matrix with ‘na’ 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))
ARGUMENTS
id (any matrix type) A matrix object.
row1 (series int) Index of the first row to be swapped.
row2 (series int) Index of the second row to be swapped.
matrix.trace(...)
DESCRIPTION
The function calculates the trace.
matrix.trace(id) → series float
matrix.trace(id) → series int
EXAMPLE
//@version=5
indicator("`matrix.trace()` Example")
// For efficiency, 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 trace of the matrix.
tr = matrix.trace(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, "Trace of the matrix:")
table.cell(t, 1, 1, str.tostring(tr))
RETURNS
The trace of the `id` matrix.
ARGUMENTS
id (matrix/matrix) A matrix object.
matrix.transpose(...)
DESCRIPTION
The function creates a new, transposed version of the `id`. This interchanges the row and column index of each element.
matrix.transpose(id) → matrix<type>
EXAMPLE
//@version=5
indicator("`matrix.transpose()` Example")
// For efficiency, 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, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
// Create a transpose of the matrix.
var m2 = matrix.transpose(m1)
// 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, "Transposed matrix:")
table.cell(t, 1, 1, str.tostring(m2))
RETURNS
A new matrix containing the transposed version of the `id` matrix.
ARGUMENTS
id (any matrix type) A matrix object.
max_bars_back(...)
DESCRIPTION
Function sets the maximum number of bars that is available for historical reference of a given built-in or user variable. When operator '[]' is applied to a variable - it is a reference to a historical value of that variable.
If an argument of an operator '[]' is a compile time constant value (e.g. 'v[10]', 'close[500]') then there is no need to use 'max_bars_back' function for that variable. Pine Script™ compiler will use that constant value as history buffer size.
If an argument of an operator '[]' is a value, calculated at runtime (e.g. 'v[i]' where 'i' - is a series variable) then Pine Script™ attempts to autodetect the history buffer size at runtime. Sometimes it fails and the script crashes at runtime because it eventually refers to historical values that are out of the buffer. In that case you should use 'max_bars_back' to fix that problem manually.
max\_bars\_back(var, num) → void
EXAMPLE
//@version=5
indicator("max_bars_back")
close_() => close
depth() => 400
d = depth()
v = close_()
max_bars_back(v, 500)
out = if bar_index > 0
v[d]
else
v
plot(out)
RETURNS
void
ARGUMENTS
var (series int/float/bool/color/label/line) Series variable identifier for which history buffer should be resized. Possible values are: 'open', 'high', 'low', 'close', 'volume', 'time', or any user defined variable id.
num (const int) History buffer size which is the number of bars that could be referenced for variable 'var'.
If the indicator function instead.
minute(...)
DESCRIPTION
minute(time) → series int
minute(time, timezone) → series int
RETURNS
Minute (in exchange timezone) for provided UNIX time.
ARGUMENTS
time (series int) UNIX time in milliseconds.
timezone (series string) Allows adjusting the returned value to a time zone specified in either UTC/GMT notation (e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). Optional. The default is syminfo.timezone.
month(...)
DESCRIPTION
month(time) → series int
month(time, timezone) → series int
RETURNS
Month (in exchange timezone) for provided UNIX time.
ARGUMENTS
time (series int) UNIX time in milliseconds.
timezone (series string) Allows adjusting the returned value to a time zone specified in either UTC/GMT notation (e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). Optional. The default is syminfo.timezone.
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) t
https://gist.github.com/kaigouthro/b95a8b4c43e607ea71897e204904b9c0