Pine Script Cheatsheet
A searchable index with 33 categories and 857 Pine Script reference entries
A selected reference index, reviewed October 21, 2026. Entries are brief descriptions, not complete call signatures or runnable scripts. For argument types, overloads, version changes and runtime limits, use the official Pine Script v6 reference and release notes.
Script Types
3 itemsindicatorDeclaration statement that designates the script as an indicator
strategyDeclaration statement that designates the script as a strategy
libraryDeclaration statement identifying a script as a library
Types
18 itemsarrayKeyword used to explicitly declare the "array" type of a variable or a parameter
boolKeyword used to explicitly declare the "bool" (boolean) type of a variable or a parameter
boxKeyword used to explicitly declare the "box" type of a variable or a parameter
chart.pointKeyword to explicitly declare the type of a variable or parameter as chart.point
colorKeyword used to explicitly declare the "color" type of a variable or a parameter
constThe const keyword explicitly assigns the "const" type qualifier to variables and the parameters of non-exported functions
floatKeyword used to explicitly declare the "float" (floating point) type of a variable or a parameter
intKeyword used to explicitly declare the "int" (integer) type of a variable or a parameter
labelKeyword used to explicitly declare the "label" type of a variable or a parameter
lineKeyword used to explicitly declare the "line" type of a variable or a parameter
linefillKeyword used to explicitly declare the "linefill" type of a variable or a parameter
mapKeyword used to explicitly declare the "map" type of a variable or a parameter
matrixKeyword used to explicitly declare the "matrix" type of a variable or a parameter
polylineKeyword to explicitly declare the type of a variable or parameter as polyline
seriesThe series keyword explicitly assigns the "series" type qualifier to variables and function parameters
simpleThe simple keyword explicitly assigns the "simple" type qualifier to variables and function parameters
stringKeyword used to explicitly declare the "string" type of a variable or a parameter
tableKeyword used to explicitly declare the "table" type of a variable or a parameter
Operators
20 items-Subtraction or unary minus
-=Subtraction assignment
:=Reassignment operator
!=Not equal to
?:Ternary conditional operator
[]Series subscript
*Multiplication
*=Multiplication assignment
/Division
/=Division assignment
%Modulo (remainder after division); accepts numeric operands, including floats
%=Modulo assignment
+Addition, unary plus, or string concatenation
+=Addition assignment
<Less than
<=Less than or equal to
==Equal to
=>The '=>' operator is used in user-defined function declarations and in switch statements
>Greater than
>=Greater than or equal to
Strings
19 itemsstr.contains()Returns true if the source string contains the str substring, false otherwise
str.endswith()Returns true if the source string ends with the substring specified in str, false otherwise
str.format_time()Converts the time timestamp into a string formatted according to format and timezone
str.format()Converts the formatting string and value(s) into a formatted string
str.length()Returns an integer corresponding to the amount of chars in that string
str.lower()Returns a new string with all letters converted to lowercase
str.match()Returns the new substring of the source string if it matches a regex regular expression, an empty string otherwise
str.pos()Returns the position of the first occurrence of the str string in the source string, 'na' otherwise
str.repeat()Constructs a new string containing the source string repeated repeat times with the separator injected between each repeated instance
str.replace_all()Replaces each occurrence of the target string in the source string with the replacement string
str.replace()Returns a new string with the Nth occurrence of the target string replaced by the replacement string, where N is specified in occurrence
str.split()Divides a string into an array of substrings and returns its array id
str.startswith()Returns true if the source string starts with the substring specified in str, false otherwise
str.substring()Returns a new string that is a substring of the source string
str.tonumber()Converts a value represented in string to its "float" equivalent
str.tostring()Converts a value to its string representation
str.trim()Constructs a new string with all consecutive whitespaces and other control characters (e.g., “\\n”, “\\t”, etc.) removed from the left and right of the source
str.upper()Returns a new string with all letters converted to uppercase
string()Casts na to string
Maths
31 itemsmath.abs()Absolute value of number is number if number >= 0, or -number otherwise
math.acos()The acos function returns the arccosine (in radians) of number such that cos(acos(y)) = y for y in range \[-1, 1\]
math.asin()The asin function returns the arcsine (in radians) of number such that sin(asin(y)) = y for y in range \[-1, 1\]
math.atan()The atan function returns the arctangent (in radians) of number such that tan(atan(y)) = y for any y
math.avg()Calculates average of all given series (elementwise)
math.ceil()Rounds the specified number up to the smallest whole number ("int" value) that is greater than or equal to it
math.cos()The cos function returns the trigonometric cosine of an angle
math.eEuler's number
math.exp()The exp function of number is e raised to the power of number, where e is Euler's number
math.floor()Rounds the specified number down to the largest whole number ("int" value) that is less than or equal to it
math.log()Natural logarithm of any number > 0 is the unique y such that e^y = number
math.log10()The common (or base 10) logarithm of number is the power to which 10 must be raised to obtain the number
math.max()Returns the greatest of multiple values
math.min()Returns the smallest of multiple values
math.phiIs a named constant for the golden ratio
math.piIs a named constant for Archimedes' constant
math.pow()Mathematical power function
math.random()Returns a pseudo-random value
math.round_to_mintick()Rounds a value to a multiple of syminfo.mintick, with ties rounding up
math.round()Returns the value of number rounded to the nearest integer, with ties rounding up
math.rphiIs a named constant for the golden ratio conjugate
math.sign()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
math.sin()The sin function returns the trigonometric sine of an angle
math.sqrt()Square root of any number >= 0 is the unique y >= 0 such that y^2 = number
math.sum()The sum function returns the sliding sum of last y values of x
math.tan()The tan function returns the trigonometric tangent of an angle
math.todegrees()Returns an approximately equivalent angle in degrees from an angle measured in radians
math.toradians()Returns an approximately equivalent angle in radians from an angle measured in degrees
naTests if x is na
fixnanFor a given series replaces NaN values with previous nearest non-NaN value
nzReplaces NaN values with zeros (or given value) in a series
Bar State
7 itemsbarstate.isconfirmedTrue on every historical bar and on the closing update of a realtime bar; not a confirmation mechanism inside request.security()
barstate.isfirstReturns true if current bar is first bar in barset, false otherwise
barstate.ishistoryReturns true if current bar is a historical bar, false otherwise
barstate.islastReturns true if current bar is the last bar in barset, false otherwise
barstate.islastconfirmedhistoryReturns 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
barstate.isnewTrue on all historical bars and on the first update of a realtime bar
barstate.isrealtimeReturns true if current bar is a real-time bar, false otherwise
Plotting
42 itemsbarcolor()Set color of bars
bgcolor()Fill background of bars with specified color
display.allA named constant for use with the display parameter of plot*() and input*() functions
display.data_windowA named constant for use with the display parameter of plot*() and input*() functions
display.noneA named constant for use with the display parameter of plot*() and input*() functions
display.paneA named constant for use with the display parameter of plot*() functions
display.price_scaleA named constant for use with the display parameter of plot*() functions
display.status_lineA named constant for use with the display parameter of plot*() and input*() functions
fill()Fills background between two plots or hlines with a given color
hline.style_dashedIs a named constant for dashed linestyle of hline function
hline.style_dottedIs a named constant for dotted linestyle of hline function
hline.style_solidIs a named constant for solid linestyle of hline function
hline()Renders a horizontal line at a given fixed price level
plot.style_areaA named constant for the 'Area' style, to be used as an argument for the style parameter in the plot function
plot.style_areabrA named constant for the 'Area With Breaks' style, to be used as an argument for the style parameter in the plot function
plot.style_circlesA named constant for the 'Circles' style, to be used as an argument for the style parameter in the plot function
plot.style_columnsA named constant for the 'Columns' style, to be used as an argument for the style parameter in the plot function
plot.style_crossA named constant for the 'Cross' style, to be used as an argument for the style parameter in the plot function
plot.style_histogramA named constant for the 'Histogram' style, to be used as an argument for the style parameter in the plot function
plot.style_lineA named constant for the 'Line' style, to be used as an argument for the style parameter in the plot function
plot.style_linebrA named constant for the 'Line With Breaks' style, to be used as an argument for the style parameter in the plot function
plot.style_steplineA named constant for the 'Step Line' style, to be used as an argument for the style parameter in the plot function
plot.style_stepline_diamondA named constant for the 'Step Line With Diamonds' style, to be used as an argument for the style parameter in the plot function
plot.style_steplinebrA named constant for the 'Step line with Breaks' style, to be used as an argument for the style parameter in the plot function
plot()Plots a series of data on the chart
plotarrow()Plots up and down arrows on the chart
plotbar()Plots ohlc bars on the chart
plotcandle()Plots candles on the chart
plotchar()Plots visual shapes using any given one Unicode character on the chart
plotshape()Plots visual shapes on the chart
shape.arrowdownShape style for plotshape function
shape.arrowupShape style for plotshape function
shape.circleShape style for plotshape function
shape.crossShape style for plotshape function
shape.diamondShape style for plotshape function
shape.flagShape style for plotshape function
shape.labeldownShape style for plotshape function
shape.labelupShape style for plotshape function
shape.squareShape style for plotshape function
shape.triangledownShape style for plotshape function
shape.triangleupShape style for plotshape function
shape.xcrossShape style for plotshape function
Indicators
69 itemsta.accdistAccumulation/distribution index
ta.alma()Arnaud Legoux Moving Average
ta.atr()Function atr (average true range) returns the RMA of true range
ta.barssince()Counts the number of bars since the last time the condition was true
ta.bb()Bollinger Bands
ta.bbw()Bollinger Bands Width
ta.cci()Commodity Channel Index: deviation from a moving average, divided by 0.015 times mean absolute deviation
ta.change()Compares the current source value to its value length bars ago and returns the difference
ta.cmo()Chande Momentum Oscillator
ta.cog()Center of Gravity oscillator calculated from a weighted sum of source values over a lookback
ta.correlation()Correlation coefficient
ta.cross()Returns true if two series have crossed each other
ta.crossover()The source1-series is defined as having crossed over source2-series if, on the current bar, the value of source1 is greater than the value of source2, and on the previous bar, the value of source1 was less than or equal to the value of source2
ta.crossunder()The source1-series is defined as having crossed under source2-series if, on the current bar, the value of source1 is less than the value of source2, and on the previous bar, the value of source1 was greater than or equal to the value of source2
ta.cum()Cumulative (total) sum of source
ta.dev()Measure of difference between the series and it's ta.sma
ta.dmi()The dmi function returns the directional movement index
ta.ema()The ema function returns the exponentially weighted moving average
ta.falling()Tests whether the current source is lower than previous values in the lookback; does not require consecutive decreases
ta.highest()Highest value for a given number of bars back
ta.highestbars()Highest value offset for a given number of bars back
ta.hma()The hma function returns the Hull Moving Average
ta.iiiIntraday Intensity Index
ta.kc()Keltner Channels
ta.kcw()Keltner Channels Width
ta.linreg()Linear regression curve
ta.lowest()Lowest value for a given number of bars back
ta.lowestbars()Lowest value offset for a given number of bars back
ta.macd()MACD (moving average convergence/divergence)
ta.max()Returns the all-time high value of source from the beginning of the chart up to the current bar
ta.median()Returns the median of the series
ta.mfi()Money Flow Index
ta.min()Returns the all-time low value of source from the beginning of the chart up to the current bar
ta.mode()Returns the mode of the series
ta.mom()Momentum of source price and source price length bars ago
ta.nviNegative Volume Index
ta.obvOn Balance Volume
ta.percentile_linear_interpolation()Calculates percentile using method of linear interpolation between the two nearest ranks
ta.percentile_nearest_rank()Calculates percentile using method of Nearest Rank
ta.percentrank()Percent rank is the percents of how many previous values was less than or equal to the current value of given series
ta.pivot_point_levels()Calculates the pivot point levels using the specified type and anchor
ta.pivothigh()This function returns price of the pivot high point
ta.pivotlow()This function returns price of the pivot low point
ta.pviPositive Volume Index
ta.pvtPrice-Volume Trend
ta.range()Returns the difference between the min and max values in a series
ta.rci()Calculates the Rank Correlation Index (RCI), which measures the directional consistency of price movements
ta.rising()Tests whether the current source is greater than previous values in the lookback; does not require consecutive increases
ta.rma()Moving average used in RSI
ta.roc()Calculates the percentage of change (rate of change) between the current value of source and its value length bars ago
ta.rsi()Relative strength index
ta.sar()Parabolic SAR, a stop-and-reverse calculation developed by J. Welles Wilder
ta.sma()The sma function returns the moving average, that is the sum of last y values of x, divided by y
ta.stdev()Returns the standard deviation of a series
ta.stoch()Stochastic
ta.supertrend()The Supertrend Indicator
ta.swma()Symmetrically weighted moving average with fixed length: 4
ta.trTrue range using the previous close; equivalent to ta.tr(false)
ta.tr()Returns true range; when handle_na is true and the previous close is missing, uses high minus low
ta.tsi()True strength index
ta.valuewhen()Returns the value of the source series on the bar where the condition was true on the nth most recent occurrence
ta.variance()Variance is the expectation of the squared deviation of a series from its mean (ta.sma), and it informally measures how far a set of numbers are spread out from their mean
ta.vwapVolume Weighted Average Price
ta.vwap()Volume Weighted Average Price
ta.vwma()The vwma function returns volume-weighted moving average of source for length bars back
ta.wadWilliams Accumulation/Distribution
ta.wma()The wma function returns weighted moving average of source for length bars back
ta.wpr()Williams %R
ta.wvadWilliams Variable Accumulation/Distribution
Inputs
14 itemsinput.bool()Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users
input.color()Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users
input.enum()Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users
input.float()Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users
input.int()Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users
input.price()Adds a price input to the script's "Settings/Inputs" tab
input.session()Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users
input.source()Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users
input.string()Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users
input.symbol()Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users
input.text_area()Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users
input.time()Adds a time input to the script's "Settings/Inputs" tab
input.timeframe()Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users
input()Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script users
Boxes
30 itemsbox.allReturns an array filled with all the current boxes drawn by the script
box.copy()Clones the box object
box.delete()Deletes the specified box object
box.get_bottom()Returns the price value of the bottom border of the box
box.get_left()Returns the bar index or the UNIX time (depending on the last value used for 'xloc') of the left border of the box
box.get_right()Returns the bar index or the UNIX time (depending on the last value used for 'xloc') of the right border of the box
box.get_top()Returns the price value of the top border of the box
box.new()Creates a new box object
box.set_bgcolor()Sets the background color of the box
box.set_border_color()Sets the border color of the box
box.set_border_style()Sets the border style of the box
box.set_border_width()Sets the border width of the box
box.set_bottom_right_point()Sets the bottom-right corner location of the id box to point
box.set_bottom()Sets the bottom coordinate of the box
box.set_extend()Sets extending type of the border of this box object
box.set_left()Sets the left coordinate of the box
box.set_lefttop()Sets the left and top coordinates of the box
box.set_right()Sets the right coordinate of the box
box.set_rightbottom()Sets the right and bottom coordinates of the box
box.set_text_color()The function sets the color of the text inside the box
box.set_text_font_family()The function sets the font family of the text inside the box
box.set_text_formatting()Sets the formatting attributes the drawing applies to displayed text
box.set_text_halign()The function sets the horizontal alignment of the box's text
box.set_text_size()The function sets the size of the box's text
box.set_text_valign()The function sets the vertical alignment of a box's text
box.set_text_wrap()The function sets the mode of wrapping of the text inside the box
box.set_text()The function sets the text in the box
box.set_top_left_point()Sets the top-left corner location of the id box to point
box.set_top()Sets the top coordinate of the box
box()Keyword used to explicitly declare the "box" type of a variable or a parameter
Sessions
9 itemssession.extendedConstant for extended session type (with extended hours data)
session.isfirstbarReturns true if the current bar is the first bar of the day's session, false otherwise
session.isfirstbar_regularReturns true on the first regular session bar of the day, false otherwise
session.islastbarReturns true if the current bar is the last bar of the day's session, false otherwise
session.islastbar_regularReturns true on the last regular session bar of the day, false otherwise
session.ismarketTrue when the bar belongs to the regular trading session
session.ispostmarketReturns true if the current bar is a part of the post-market, false otherwise
session.ispremarketReturns true if the current bar is a part of the pre-market, false otherwise
session.regularConstant for regular session type (no extended hours data)
Logging & Debugging
4 itemslog.error()Sends a formatted string to the Pine logs with the error level
log.info()Sends a formatted string to the Pine logs with the info level
log.warning()Sends a formatted string to the Pine logs with the warning level
runtime.error()Causes a runtime error with a specified message
Texts & Formatting
17 itemsfont.family_defaultDefault text font for drawings
font.family_monospaceMonospace text font for drawings
format.inheritSelects formatting from the parent series
format.mintickRounds to the nearest value divisible by syminfo.mintick
format.percentFormats output values as a percentage
format.priceFormats output values as prices
format.volumeFormats output values as volume (e.g., 1.5K)
text.format_noneSignifies no special text formatting
text.format_boldMakes the text bold
text.format_italicItalicizes the text
text.align_bottomVertical text alignment (bottom)
text.align_centerHorizontal/Vertical text alignment (center)
text.align_leftHorizontal text alignment (left)
text.align_rightHorizontal text alignment (right)
text.align_topVertical text alignment (top)
text.wrap_autoAutomatic wrapping mode for drawings
text.wrap_noneDisabled wrapping mode for drawings
Annotations
10 items@descriptionSets a custom description for scripts that use the library declaration statement
@enumIf placed above an enum declaration, it adds a custom description for the enum
@fieldIf placed above a type or enum declaration, it adds a custom description for a field of the type/enum
@functionIf placed above a function declaration, it adds a custom description for the function
@paramIf placed above a function declaration, it adds a custom description for a function parameter
@returnsIf placed above a function declaration, it adds a custom description for what that function returns
@strategy_alert_messageIf used within a strategy script, it provides a default message to pre-fill the "Message" field in the alert creation dialogue
@typeIf placed above a type declaration, it adds a custom description for the type
@variableIf placed above a variable declaration, it adds a custom description for the variable
@version=Specifies the Pine Script® version that the script will use
Bar Data
13 itemsbar_indexCurrent bar index
closeClose price of the current bar when it has closed, or last traded price of a yet incomplete, realtime bar
highCurrent high price
lowCurrent low price
openCurrent open price
volumeCurrent bar volume
hl2Is a shortcut for (high + low)/2
hlc3Is a shortcut for (high + low + close)/3
hlcc4Is a shortcut for (high + low + close + close)/4
ohlc4Is a shortcut for (open + high + low + close)/4
last_bar_indexBar index of the last chart bar. Bar indices begin at zero on the first bar
last_bar_timeTime in UNIX format of the last chart bar
timestampReturns UNIX time of specified date and time
Maps
11 itemsmap.new<keyType, valueType>Creates a new map object: a collection that consists of key-value pairs
map.copyCreates a copy of an existing map
map.sizeReturns the number of key-value pairs in the map
map.getReturns the value associated with the specified key in the map
map.containsReturns true if the key was found in the map
map.keysReturns an array of all the keys in the map
map.valuesReturns an array of all the values in the map
map.putPuts a new key-value pair into the map
map.put_allPuts all key-value pairs from one map into another
map.removeRemoves a key-value pair from the map
map.clearClears the map, removing all key-value pairs from it
Arrays
57 itemsarray.abs()Returns an array containing the absolute value of each element in the original array
array.avg()The function returns the mean of an array's elements
array.binary_search_leftmost()The function returns the index of the value if it is found
array.binary_search_rightmost()The function returns the index of the value if it is found
array.binary_search()The function returns the index of the value, or -1 if the value is not found
array.clear()The function removes all elements from an array
array.concat()The function is used to merge two arrays
array.copy()The function creates a copy of an existing array
array.covariance()The function returns the covariance of two arrays
array.every()Returns true if all elements of the id array are true, false otherwise
array.fill()The function sets elements of an array to a single value
array.first()Returns the array's first element
array.from()Creates an array from compatible values; all elements must share a supported element type
array.get()The function returns the value of the element at the specified index
array.includes()The function returns true if the value was found in an array, false otherwise
array.indexof()The function returns the index of the first occurrence of the value, or -1 if the value is not found
array.insert()The function changes the contents of an array by adding new elements in place
array.join()The function creates and returns a new string by concatenating all the elements of an array, separated by the specified separator string
array.last()Returns the array's last element
array.lastindexof()The function returns the index of the last occurrence of the value, or -1 if the value is not found
array.max()The function returns the greatest value, or the nth greatest value in a given array
array.median()The function returns the median of an array's elements
array.min()The function returns the smallest value, or the nth smallest value in a given array
array.mode()The function returns the mode of an array's elements
array.new_bool()The function creates a new array object of bool type elements
array.new_box()The function creates a new array object of box type elements
array.new_color()The function creates a new array object of color type elements
array.new_float()The function creates a new array object of float type elements
array.new_int()The function creates a new array object of int type elements
array.new_label()The function creates a new array object of label type elements
array.new_line()The function creates a new array object of line type elements
array.new_linefill()The function creates a new array object of linefill type elements
array.new_string()The function creates a new array object of string type elements
array.new_table()The function creates a new array object of table type elements
array.new<type>()The function creates a new array object of <type> elements
array.percentile_linear_interpolation()Returns the value for which the specified percentage of array values (percentile) are less than or equal to it, using linear interpolation
array.percentile_nearest_rank()Returns the value for which the specified percentage of array values (percentile) are less than or equal to it, using the nearest-rank method
array.percentrank()Returns the percentile rank of the element at the specified index
array.pop()The function removes the last element from an array and returns its value
array.push()The function appends a value to an array
array.range()The function returns the difference between the min and max values from a given array
array.remove()The function changes the contents of an array by removing the element with the specified index
array.reverse()The function reverses an array
array.set()The function sets the value of the element at the specified index
array.shift()The function removes an array's first element and returns its value
array.size()The function returns the number of elements in an array
array.slice()The function creates a slice from an existing array
array.some()Returns true if at least one element of the id array is true, false otherwise
array.sort_indices()Returns an array of indices which, when used to index the original array, will access its elements in their sorted order
array.sort()The function sorts the elements of an array
array.standardize()The function returns the array of standardized elements
array.stdev()The function returns the standard deviation of an array's elements
array.sum()The function returns the sum of an array's elements
array.unshift()The function inserts the value at the beginning of the array
array.variance()The function returns the variance of an array's elements
order.ascendingDetermines the sort order of the array from the smallest to the largest value
order.descendingDetermines the sort order of the array from the largest to the smallest value
Matrixes
49 itemsmatrix.add_col()The function adds a column at the column index of the id matrix
matrix.add_row()The function adds a row at the row index of the id matrix
matrix.avg()The function calculates the average of all elements in the matrix
matrix.col()The function creates a one-dimensional array from the elements of a matrix column
matrix.columns()The function returns the number of columns in the matrix
matrix.concat()The function appends the m2 matrix to the m1 matrix
matrix.copy()The function creates a new matrix which is a copy of the original
matrix.det()The function returns the determinant of a square matrix
matrix.diff()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)
matrix.eigenvalues()The function returns an array containing the eigenvalues of a square matrix
matrix.eigenvectors()Returns a matrix of eigenvectors, in which each column is an eigenvector of the id matrix
matrix.elements_count()The function returns the total number of all matrix elements
matrix.fill()The function fills a rectangular area of the id matrix defined by the indices from_column to to_column (not including it) and from_row to to_row(not including it) with the value
matrix.get()The function returns the element with the specified index of the matrix
matrix.inv()The function returns the inverse of a square matrix
matrix.is_antidiagonal()The function determines if the matrix is anti-diagonal (all elements outside the secondary diagonal are zero)
matrix.is_antisymmetric()The function determines if a matrix is antisymmetric (its transpose equals its negative)
matrix.is_binary()The function determines if the matrix is binary (when all elements of the matrix are 0 or 1)
matrix.is_diagonal()The function determines if the matrix is diagonal (all elements outside the main diagonal are zero)
matrix.is_identity()The function determines if a matrix is an identity matrix (elements with ones on the main diagonal and zeros elsewhere)
matrix.is_square()The function determines if the matrix is square (it has the same number of rows and columns)
matrix.is_stochastic()The function determines if the matrix is stochastic
matrix.is_symmetric()The function determines if a square matrix is symmetric (elements are symmetric with respect to the main diagonal)
matrix.is_triangular()The function determines if the matrix is triangular (if all elements above or below the main diagonal are zero)
matrix.is_zero()The function determines if all elements of the matrix are zero
matrix.kron()The function returns the Kronecker product for the id1 and id2 matrices
matrix.max()The function returns the largest value from the matrix elements
matrix.median()The function calculates the median ("the middle" value) of matrix elements
matrix.min()The function returns the smallest value from the matrix elements
matrix.mode()The function calculates the mode of the matrix, which is the most frequently occurring value from the matrix elements
matrix.mult()The function returns a new matrix resulting from the product between the matrices id1 and id2, or between an id1 matrix and an id2 scalar (a numerical value), or between an id1 matrix and an id2 vector (an array of values)
matrix.new<type>()The function creates a new matrix object
matrix.pinv()The function returns the pseudoinverse of a matrix
matrix.pow()The function calculates the product of the matrix by itself power times
matrix.rank()The function calculates the rank of the matrix
matrix.remove_col()The function removes the column at column index of the id matrix and returns an array containing the removed column's values
matrix.remove_row()The function removes the row at row index of the id matrix and returns an array containing the removed row's values
matrix.reshape()The function rebuilds the id matrix to rows x cols dimensions
matrix.reverse()The function reverses the order of rows and columns in the matrix id
matrix.row()The function creates a one-dimensional array from the elements of a matrix row
matrix.rows()The function returns the number of rows in the matrix
matrix.set()The function assigns value to the element at the row and column of the id matrix
matrix.sort()The function rearranges the rows in the id matrix following the sorted order of the values in the column
matrix.submatrix()The function extracts a submatrix of the id matrix within the specified indices
matrix.sum()The function returns a new matrix resulting from the sum of two matrices id1 and id2, or of an id1 matrix and an id2 scalar (a numerical value)
matrix.swap_columns()The function swaps the columns at the index column1 and column2 in the id matrix
matrix.swap_rows()The function swaps the rows at the index row1 and row2 in the id matrix
matrix.trace()The function calculates the trace of a matrix (the sum of the main diagonal's elements)
matrix.transpose()The function creates a new, transposed version of the id
Datetime
27 itemsdayofmonthDate of current bar time in exchange timezone
dayofmonth()Date of current bar time in exchange timezone
dayofweekDay of week for current bar time in exchange timezone
dayofweek.fridayIs a named constant for return value of dayofweek function and value of dayofweek variable
dayofweek.mondayIs a named constant for return value of dayofweek function and value of dayofweek variable
dayofweek.saturdayIs a named constant for return value of dayofweek function and value of dayofweek variable
dayofweek.sundayIs a named constant for return value of dayofweek function and value of dayofweek variable
dayofweek.thursdayIs a named constant for return value of dayofweek function and value of dayofweek variable
dayofweek.tuesdayIs a named constant for return value of dayofweek function and value of dayofweek variable
dayofweek.wednesdayIs a named constant for return value of dayofweek function and value of dayofweek variable
dayofweek()Day of week for current bar time in exchange timezone
hourCurrent bar hour in exchange timezone
hour()Current bar hour in exchange timezone
minuteCurrent bar minute in exchange timezone
minute()Current bar minute in exchange timezone
monthCurrent bar month in exchange timezone
month()Current bar month in exchange timezone
secondCurrent bar second in exchange timezone
second()Current bar second in exchange timezone
timeCurrent bar time in UNIX format
time_closeThe time of the current bar's close in UNIX format
time_tradingdayThe 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)
timenowCurrent time in UNIX format
weekofyearWeek number of current bar time in exchange timezone
weekofyear()Week number of current bar time in exchange timezone
yearCurrent bar year in exchange timezone
year()Current bar year in exchange timezone
Tables
33 itemstable.allReturns an array filled with all the current tables drawn by the script
table.cell_set_bgcolor()The function sets the background color of the cell
table.cell_set_height()The function sets the height of cell
table.cell_set_text_color()The function sets the color of the text inside the cell
table.cell_set_text_font_family()The function sets the font family of the text inside the cell
table.cell_set_text_formatting()Sets the formatting attributes the drawing applies to displayed text
table.cell_set_text_halign()The function sets the horizontal alignment of the cell's text
table.cell_set_text_size()The function sets the size of the cell's text
table.cell_set_text_valign()The function sets the vertical alignment of a cell's text
table.cell_set_text()The function sets the text in the specified cell
table.cell_set_tooltip()The function sets the tooltip in the specified cell
table.cell_set_width()The function sets the width of the cell
table.cell()The function defines a cell in the table and sets its attributes
table.clear()The function removes a cell or a sequence of cells from the table
table.delete()The function deletes a table
table.merge_cells()The function merges a sequence of cells in the table into one cell
table.new()The function creates a new table
table.set_bgcolor()The function sets the background color of a table
table.set_border_color()The function sets the color of the borders (excluding the outer frame) of the table's cells
table.set_border_width()The function sets the width of the borders (excluding the outer frame) of the table's cells
table.set_frame_color()The function sets the color of the outer frame of a table
table.set_frame_width()The function set the width of the outer frame of a table
table.set_position()The function sets the position of a table
table()Keyword used to explicitly declare the "table" type of a variable or a parameter
position.bottom_centerBinds the table to the bottom edge in the center
position.bottom_leftBinds the table to the bottom left of the screen
position.bottom_rightBinds the table to the bottom right of the screen
position.middle_centerBinds the table to the center of the screen
position.middle_leftBinds the table to the left side of the screen
position.middle_rightBinds the table to the right side of the screen
position.top_centerBinds the table to the top edge in the center
position.top_leftBinds the table to the upper-left edge
position.top_rightBinds the table to the upper-right edge
Labels
47 itemslabel.allReturns an array filled with all the current labels drawn by the script
label.copy()Clones the label object
label.delete()Deletes the specified label object
label.get_text()Returns the text of this label object
label.get_x()Returns UNIX time or bar index (depending on the last xloc value set) of this label's position
label.get_y()Returns price of this label's position
label.new()Creates new label object
label.set_color()Sets label border and arrow color
label.set_point()Sets the location of the id label to point
label.set_size()Sets arrow and text size of the specified label object
label.set_style()Sets label style
label.set_text_font_family()The function sets the font family of the text inside the label
label.set_text_formatting()Sets the formatting attributes the drawing applies to displayed text
label.set_text()Sets label text
label.set_textalign()Sets the alignment for the label text
label.set_textcolor()Sets color of the label text
label.set_tooltip()Sets the tooltip text
label.set_x()Sets bar index or bar time (depending on the xloc) of the label position
label.set_xloc()Sets x-location and new bar index/time value
label.set_xy()Sets bar index/time and price of the label position
label.set_y()Sets price of the label position
label.set_yloc()Sets new y-location calculation algorithm
label.style_arrowdownLabel style for label.new and label.set_style functions
label.style_arrowupLabel style for label.new and label.set_style functions
label.style_circleLabel style for label.new and label.set_style functions
label.style_crossLabel style for label.new and label.set_style functions
label.style_diamondLabel style for label.new and label.set_style functions
label.style_flagLabel style for label.new and label.set_style functions
label.style_label_centerLabel style for label.new and label.set_style functions
label.style_label_downLabel style for label.new and label.set_style functions
label.style_label_leftLabel style for label.new and label.set_style functions
label.style_label_lower_leftLabel style for label.new and label.set_style functions
label.style_label_lower_rightLabel style for label.new and label.set_style functions
label.style_label_rightLabel style for label.new and label.set_style functions
label.style_label_upLabel style for label.new and label.set_style functions
label.style_label_upper_leftLabel style for label.new and label.set_style functions
label.style_label_upper_rightLabel style for label.new and label.set_style functions
label.style_noneLabel style for label.new and label.set_style functions
label.style_squareLabel style for label.new and label.set_style functions
label.style_text_outlineLabel style for label.new and label.set_style functions
label.style_triangledownLabel style for label.new and label.set_style functions
label.style_triangleupLabel style for label.new and label.set_style functions
label.style_xcrossLabel style for label.new and label.set_style functions
label()Keyword used to explicitly declare the "label" type of a variable or a parameter
yloc.abovebarA named constant that specifies the algorithm of interpretation of y-value in function label.new
yloc.belowbarA named constant that specifies the algorithm of interpretation of y-value in function label.new
yloc.priceA named constant that specifies the algorithm of interpretation of y-value in function label.new
Lines
36 itemsline.allReturns an array filled with all the current lines drawn by the script
line.copy()Clones the line object
line.delete()Deletes the specified line object
line.get_price()Returns the price level of a line at a given bar index
line.get_x1()Returns UNIX time or bar index (depending on the last xloc value set) of the first point of the line
line.get_x2()Returns UNIX time or bar index (depending on the last xloc value set) of the second point of the line
line.get_y1()Returns price of the first point of the line
line.get_y2()Returns price of the second point of the line
line.new()Creates new line object
line.set_color()Sets the line color
line.set_extend()Sets extending type of this line object
line.set_first_point()Sets the first point of the id line to point
line.set_second_point()Sets the second point of the id line to point
line.set_style()Sets the line style
line.set_width()Sets the line width
line.set_x1()Sets bar index or bar time (depending on the xloc) of the first point
line.set_x2()Sets bar index or bar time (depending on the xloc) of the second point
line.set_xloc()Sets x-location and new bar index/time values
line.set_xy1()Sets bar index/time and price of the first point
line.set_xy2()Sets bar index/time and price of the second point
line.set_y1()Sets price of the first point
line.set_y2()Sets price of the second point
line.style_arrow_bothLine style for line.new and line.set_style functions
line.style_arrow_leftLine style for line.new and line.set_style functions
line.style_arrow_rightLine style for line.new and line.set_style functions
line.style_dashedLine style for line.new and line.set_style functions
line.style_dottedLine style for line.new and line.set_style functions
line.style_solidLine style for line.new and line.set_style functions
line()Keyword used to explicitly declare the "line" type of a variable or a parameter
linefill.allReturns an array filled with all the current linefill objects drawn by the script
linefill.delete()Deletes the specified linefill object
linefill.get_line1()Returns the ID of the first line used in the id linefill
linefill.get_line2()Returns the ID of the second line used in the id linefill
linefill.new()Creates a new linefill object and displays it on the chart, filling the space between line1 and line2 with the color specified in color
linefill.set_color()The function sets the color of the linefill object passed to it
linefill()Keyword used to explicitly declare the "linefill" type of a variable or a parameter
Polylines
3 itemspolyline.allReturns an array containing all current polyline instances drawn by the script
polyline.delete()Deletes the specified polyline object
polyline.new()Creates a new polyline instance and displays it on the chart, sequentially connecting all of the points in the points array with line segments
Keywords
22 itemsandLogical AND
asDefines an optional namespace alias in an import statement
breakExits the current for or while loop
bySpecifies the step value in a for loop
continueSkips the current iteration in a for or while loop
elseDefines the block of code to execute when the if condition is false
enumThis keyword allows the creation of an enumeration, enum for short
exportUsed in libraries to prefix the declaration of functions or user-defined type definitions that will be available from other scripts importing the library
forThe 'for' structure allows the repeated execution of a number of statements:
for...inIterates over elements of supported collections, including arrays, matrices and maps
ifIf statement defines what block of statements must be executed when conditions of the expression are satisfied
importUsed to load an external library into a script and bind its functions to a namespace
inPart of a for...in loop over a supported collection
methodThis 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
notLogical negation (NOT)
orLogical OR
switchThe switch operator transfers control to one of the several statements, depending on the values of a condition and expressions
toSpecifies the end value in a for loop
typeThis keyword allows the declaration of user-defined types (UDT) from which scripts can instantiate objects
varvar is the keyword used for assigning and one-time initializing of the variable
varipvarip (var intrabar persist) is the keyword used for the assignment and one-time initialization of a variable or a field of a user-defined type
whileThe while statement allows the conditional iteration of a local code block
Colors
25 itemscolor.aquaIs a named constant for #00BCD4 color
color.b()Retrieves the value of the color's blue component
color.blackIs a named constant for #363A45 color
color.blueIs a named constant for #2962ff color
color.from_gradient()Based on the relative position of value in the bottom_value to top_value range, the function returns a color from the gradient defined by bottom_color to top_color
color.fuchsiaIs a named constant for #E040FB color
color.g()Retrieves the value of the color's green component
color.grayIs a named constant for #787B86 color
color.greenIs a named constant for #4CAF50 color
color.limeIs a named constant for #00E676 color
color.maroonIs a named constant for #880E4F color
color.navyIs a named constant for #311B92 color
color.new()Function color applies the specified transparency to the given color
color.oliveIs a named constant for #808000 color
color.orangeIs a named constant for #FF9800 color
color.purpleIs a named constant for #9C27B0 color
color.r()Retrieves the value of the color's red component
color.redIs a named constant for #F23645 color
color.rgb()Creates a new color with transparency using the RGB color model
color.silverIs a named constant for #B2B5BE color
color.t()Retrieves the color's transparency
color.tealIs a named constant for #089981 color
color.whiteIs a named constant for #FFFFFF color
color.yellowIs a named constant for #FDD835 color
color()Keyword used to explicitly declare the "color" type of a variable or a parameter
Currency
22 itemscurrency.AUDAustralian dollar
currency.BTCBitcoin
currency.CADCanadian dollar
currency.CHFSwiss franc
currency.ETHEthereum
currency.EUREuro
currency.GBPPound sterling
currency.HKDHong Kong dollar
currency.INRIndian rupee
currency.JPYJapanese yen
currency.KRWSouth Korean won
currency.MYRMalaysian ringgit
currency.NOKNorwegian krone
currency.NONEUnspecified currency
currency.NZDNew Zealand dollar
currency.RUBRussian ruble
currency.SEKSwedish krona
currency.SGDSingapore dollar
currency.TRYTurkish lira
currency.USDUnited States dollar
currency.USDTTether
currency.ZARSouth African rand
Alerts
5 itemsalert.freq_allA named constant for use with the freq parameter of the alert() function
alert.freq_once_per_barA named constant for use with the freq parameter of the alert() function
alert.freq_once_per_bar_closeA named constant for use with the freq parameter of the alert() function
alert()Creates an alert trigger for an indicator or strategy, with a specified frequency, when called on the latest realtime bar
alertcondition()Creates alert condition, that is available in Create Alert dialog
Symbol Info
40 itemssyminfo.basecurrencyReturns a string containing the code representing the symbol's base currency (i.e., the traded currency or coin) if the instrument is a Forex or Crypto pair or a derivative based on such a pair
syminfo.countryReturns the two-letter code of the country where the symbol is traded, in the ISO 3166-1 alpha-2 format, or na if the exchange is not directly tied to a specific country
syminfo.currencyReturns a string containing the code representing the currency of the symbol's prices
syminfo.descriptionDescription for the current symbol
syminfo.employeesThe number of employees the company has
syminfo.expiration_dateA UNIX timestamp representing the start of the last day of the current futures contract
syminfo.industryReturns the industry of the symbol, or na if the symbol has no industry
syminfo.main_tickeridA ticker identifier representing the current chart's symbol
syminfo.mincontractThe smallest amount of the current symbol that can be traded
syminfo.minmoveReturns a whole number used to calculate the smallest increment between a symbol's price movements (syminfo.mintick)
syminfo.mintickMin tick value for the current symbol
syminfo.pointvaluePoint value for the current symbol
syminfo.prefixExchange or data-source prefix of the chart symbol
syminfo.prefix()Returns the exchange or data-source prefix from a ticker identifier
syminfo.pricescaleReturns a whole number used to calculate the smallest increment between a symbol's price movements (syminfo.mintick)
syminfo.recommendations_buyThe number of analysts who gave the current symbol a "Buy" rating
syminfo.recommendations_buy_strongThe number of analysts who gave the current symbol a "Strong Buy" rating
syminfo.recommendations_dateThe starting date of the last set of recommendations for the current symbol
syminfo.recommendations_holdThe number of analysts who gave the current symbol a "Hold" rating
syminfo.recommendations_sellThe number of analysts who gave the current symbol a "Sell" rating
syminfo.recommendations_sell_strongThe number of analysts who gave the current symbol a "Strong Sell" rating
syminfo.recommendations_totalThe total number of recommendations for the current symbol
syminfo.rootRoot for derivatives like futures contract
syminfo.sectorReturns the sector of the symbol, or na if the symbol has no sector
syminfo.sessionSession type of the chart main series
syminfo.shareholdersThe number of shareholders the company has
syminfo.shares_outstanding_floatThe total number of shares outstanding a company has available, excluding any of its restricted shares
syminfo.shares_outstanding_totalThe total number of shares outstanding a company has available, including restricted shares held by insiders, major shareholders, and employees
syminfo.target_price_averageThe average of the last yearly price targets for the symbol predicted by analysts
syminfo.target_price_dateThe starting date of the last price target prediction for the current symbol
syminfo.target_price_estimatesThe latest total number of price target predictions for the current symbol
syminfo.target_price_highThe last highest yearly price target for the symbol predicted by analysts
syminfo.target_price_lowThe last lowest yearly price target for the symbol predicted by analysts
syminfo.target_price_medianThe median of the last yearly price targets for the symbol predicted by analysts
syminfo.tickerChart symbol name without its exchange prefix
syminfo.ticker()Returns a symbol name without its exchange prefix from a ticker identifier
syminfo.tickeridA ticker identifier representing the chart's symbol or a requested symbol, depending on how the script uses it
syminfo.timezoneTimezone of the exchange of the chart main series
syminfo.typeThe type of market the symbol belongs to
syminfo.volumetypeVolume type of the current symbol
Requests
40 itemsadjustment.dividendsConstant for dividends adjustment type (dividends adjustment is applied)
adjustment.noneConstant for none adjustment type (no adjustment is applied)
adjustment.splitsConstant for splits adjustment type (splits adjustment is applied)
barmerge.gaps_offMerge strategy for requested data
barmerge.gaps_onMerge strategy for requested data
barmerge.lookahead_offMerge strategy for the requested data position
barmerge.lookahead_onMerge strategy for the requested data position
dividends.future_amountReturns the payment amount of the upcoming dividend in the currency of the current instrument, or na if this data isn't available
dividends.future_ex_dateReturns the Ex-dividend date (Ex-date) of the current instrument's next dividend payment, or na if this data isn't available
dividends.future_pay_dateReturns the Payment date (Pay date) of the current instrument's next dividend payment, or na if this data isn't available
dividends.grossA named constant for the request.dividends function
dividends.netA named constant for the request.dividends function
earnings.actualA named constant for the request.earnings function
earnings.estimateA named constant for the request.earnings function
earnings.future_epsReturns the estimated Earnings per Share of the next earnings report in the currency of the instrument, or na if this data isn't available
earnings.future_period_end_timeChecks the data for the next earnings report and returns the UNIX timestamp of the day when the financial period covered by those earnings ends, or na if this data isn't available
earnings.future_revenueReturns the estimated Revenue of the next earnings report in the currency of the instrument, or na if this data isn't available
earnings.future_timeReturns a UNIX timestamp indicating the expected time of the next earnings report, or na if this data isn't available
earnings.standardizedA named constant for the request.earnings function
request.currency_rate()Provides a daily rate that can be used to convert a value expressed in the from currency to another in the to currency
request.dividends()Requests dividends data for the specified symbol
request.earnings()Requests earnings data for the specified symbol
request.economic()Requests economic data for a symbol
request.financial()Requests financial series for symbol
request.quandl()Deprecated following changes to the Nasdaq Data Link API; do not use for new data-feed integrations
request.security_lower_tf()Requests the results of an expression from a specified symbol on a timeframe lower than or equal to the chart's timeframe
request.security()Requests the result of an expression from a specified context (symbol and timeframe)
request.seed()Reads an existing Pine Seeds GitHub data feed; creating new Pine Seeds repositories is currently unavailable
request.splits()Requests splits data for the specified symbol
splits.denominatorA named constant for the request.splits function
splits.numeratorA named constant for the request.splits function
ticker.heikinashi()Creates a ticker identifier for requesting Heikin Ashi bar values
ticker.inherit()Constructs a ticker ID for the specified symbol with additional parameters inherited from the ticker ID passed into the function call, allowing the script to request a symbol's data using the same modifiers that the from_tickerid has, including extended session, dividend adjustment, currency conversion, non-standard chart types, back-adjustment, settlement-as-close, etc
ticker.kagi()Creates a ticker identifier for requesting Kagi values
ticker.linebreak()Creates a ticker identifier for requesting Line Break values
ticker.modify()Creates a ticker identifier for requesting additional data for the script
ticker.new()Creates a ticker identifier for requesting additional data for the script
ticker.pointfigure()Creates a ticker identifier for requesting Point & Figure values
ticker.renko()Creates a ticker identifier for requesting Renko values
ticker.standard()Creates a ticker to request data from a standard chart that is unaffected by modifiers like extended session, dividend adjustment, currency conversion, and the calculations of non-standard chart types: Heikin Ashi, Renko, etc
Timeframe
14 itemstimeframe.change()Detects changes in the specified timeframe
timeframe.from_seconds()Converts a number of seconds into a valid timeframe string
timeframe.in_seconds()Converts a timeframe string into seconds
timeframe.isdailyReturns true if current resolution is a daily resolution, false otherwise
timeframe.isdwmReturns true if current resolution is a daily or weekly or monthly resolution, false otherwise
timeframe.isintradayReturns true if current resolution is an intraday (minutes or seconds) resolution, false otherwise
timeframe.isminutesReturns true if current resolution is a minutes resolution, false otherwise
timeframe.ismonthlyReturns true if current resolution is a monthly resolution, false otherwise
timeframe.issecondsReturns true if current resolution is a seconds resolution, false otherwise
timeframe.isticksReturns true if current resolution is a ticks resolution, false otherwise
timeframe.isweeklyReturns true if current resolution is a weekly resolution, false otherwise
timeframe.main_periodA string representation of the script's main timeframe
timeframe.multiplierNumeric multiplier of the current interval: for example 60 for a 60-minute chart; units depend on interval type
timeframe.periodA string representation of the script's main timeframe or a requested timeframe, depending on how the script uses it
Strategy
97 itemsstrategy.account_currencyReturns the currency used to calculate results, which can be set in the strategy's properties
strategy.avg_losing_tradeReturns the average amount of money lost per losing trade
strategy.avg_losing_trade_percentReturns the average percentage loss per losing trade
strategy.avg_tradeReturns the average amount of money gained or lost per trade
strategy.avg_trade_percentReturns the average percentage gain or loss per trade
strategy.avg_winning_tradeReturns the average amount of money gained per winning trade
strategy.avg_winning_trade_percentReturns the average percentage gain per winning trade
strategy.cancel_all()Cancels all pending or unfilled orders, regardless of their identifiers
strategy.cancel()Cancels a pending or unfilled order with a specific identifier
strategy.cashThis is one of the arguments that can be supplied to the default_qty_type parameter in the strategy declaration statement
strategy.close_all()Creates an order to close an open position completely, regardless of the identifiers of the entry orders that opened or added to it
strategy.close()Creates an order to exit from the part of a position opened by entry orders with a specific identifier
strategy.closedtradesNumber of trades, which were closed for the whole trading range
strategy.closedtrades.commission()Returns the sum of entry and exit fees paid in the closed trade, expressed in strategy.account_currency
strategy.closedtrades.entry_bar_index()Returns the bar_index of the closed trade's entry
strategy.closedtrades.entry_comment()Returns the comment message of the closed trade's entry, or na if there is no entry with this trade_num
strategy.closedtrades.entry_id()Returns the id of the closed trade's entry
strategy.closedtrades.entry_price()Returns the price of the closed trade's entry
strategy.closedtrades.entry_time()Returns the UNIX time of the closed trade's entry, expressed in milliseconds
strategy.closedtrades.exit_bar_index()Returns the bar_index of the closed trade's exit
strategy.closedtrades.exit_comment()Returns the comment message of the closed trade's exit, or na if there is no entry with this trade_num
strategy.closedtrades.exit_id()Returns the id of the closed trade's exit
strategy.closedtrades.exit_price()Returns the price of the closed trade's exit
strategy.closedtrades.exit_time()Returns the UNIX time of the closed trade's exit, expressed in milliseconds
strategy.closedtrades.first_indexThe index, or trade number, of the first (oldest) trade listed in the List of Trades
strategy.closedtrades.max_drawdown_percent()Returns the maximum adverse excursion for the specified trade, expressed as a percentage of its entry value
strategy.closedtrades.max_drawdown()Returns the maximum drawdown of the closed trade, i.e., the maximum possible loss during the trade, expressed in strategy.account_currency
strategy.closedtrades.max_runup_percent()Returns the maximum favorable excursion for the specified trade, expressed as a percentage of its entry value
strategy.closedtrades.max_runup()Returns the maximum run up of the closed trade, i.e., the maximum possible profit during the trade, expressed in strategy.account_currency
strategy.closedtrades.profit_percent()Returns the profit/loss value of the closed trade, expressed as a percentage
strategy.closedtrades.profit()Returns the profit/loss of the closed trade, expressed in strategy.account_currency
strategy.closedtrades.size()Returns the direction and the number of contracts traded in the closed trade
strategy.commission.cash_per_contractCommission type for an order
strategy.commission.cash_per_orderCommission type for an order
strategy.commission.percentCommission type for an order
strategy.convert_to_account()Converts the value from the currency that the symbol on the chart is traded in (syminfo.currency) to the currency used by the strategy (strategy.account_currency)
strategy.convert_to_symbol()Converts the value from the currency used by the strategy (strategy.account_currency) to the currency that the symbol on the chart is traded in (syminfo.currency)
strategy.default_entry_qty()Calculates the default quantity, in units, of an entry order from strategy.entry or strategy.order if it were to fill at the specified fill_price value
strategy.direction.allIt allows strategy to open both long and short positions
strategy.direction.longIt allows strategy to open only long positions
strategy.direction.shortIt allows strategy to open only short positions
strategy.entry()Creates a new order to open or add to a position
strategy.equityCurrent equity (strategy.initial_capital + strategy.netprofit + strategy.openprofit)
strategy.eventradesNumber of breakeven trades for the whole trading range
strategy.exit()Creates price-based orders to exit from an open position
strategy.fixedThis is one of the arguments that can be supplied to the default_qty_type parameter in the strategy declaration statement
strategy.grosslossTotal currency value of all completed losing trades
strategy.grossloss_percentThe total value of all completed losing trades, expressed as a percentage of the initial capital
strategy.grossprofitTotal currency value of all completed winning trades
strategy.grossprofit_percentThe total currency value of all completed winning trades, expressed as a percentage of the initial capital
strategy.initial_capitalThe amount of initial capital set in the strategy properties
strategy.longA named constant for use with the direction parameter of the strategy.entry and strategy.order commands
strategy.losstradesNumber of unprofitable trades for the whole trading range
strategy.margin_liquidation_priceWhen margin is used in a strategy, returns the price point where a simulated margin call will occur and liquidate enough of the position to meet the margin requirements
strategy.max_contracts_held_allMaximum number of contracts/shares/lots/units in one trade for the whole trading range
strategy.max_contracts_held_longMaximum number of contracts/shares/lots/units in one long trade for the whole trading range
strategy.max_contracts_held_shortMaximum number of contracts/shares/lots/units in one short trade for the whole trading range
strategy.max_drawdownMaximum equity drawdown value for the whole trading range
strategy.max_drawdown_percentMaximum strategy equity drawdown expressed as a percentage; use the strategy metric definition rather than a lowest-price divided by entry-price ratio
strategy.max_runupMaximum equity run-up value for the whole trading range
strategy.max_runup_percentMaximum strategy equity run-up expressed as a percentage; distinct from an individual trade price-return calculation
strategy.netprofitTotal currency value of all completed trades
strategy.netprofit_percentThe total value of all completed trades, expressed as a percentage of the initial capital
strategy.oca.cancelA named constant for use with the oca_type parameter of the strategy.entry and strategy.order commands
strategy.oca.noneA named constant for use with the oca_type parameter of the strategy.entry and strategy.order commands
strategy.oca.reduceA named constant for use with the oca_type parameter of the strategy.entry and strategy.order commands
strategy.openprofitCurrent unrealized profit or loss for all open positions
strategy.openprofit_percentThe current unrealized profit or loss for all open positions, expressed as a percentage and calculated by formula: openPL / realizedEquity * 100
strategy.opentradesNumber of market position entries, which were not closed and remain opened
strategy.opentrades.capital_heldReturns the capital amount currently held by open trades
strategy.opentrades.commission()Returns the sum of entry and exit fees paid in the open trade, expressed in strategy.account_currency
strategy.opentrades.entry_bar_index()Returns the bar_index of the open trade's entry
strategy.opentrades.entry_comment()Returns the comment message of the open trade's entry, or na if there is no entry with this trade_num
strategy.opentrades.entry_id()Returns the id of the open trade's entry
strategy.opentrades.entry_price()Returns the price of the open trade's entry
strategy.opentrades.entry_time()Returns the UNIX time of the open trade's entry, expressed in milliseconds
strategy.opentrades.max_drawdown_percent()Returns the maximum adverse excursion for the specified trade, expressed as a percentage of its entry value
strategy.opentrades.max_drawdown()Returns the maximum drawdown of the open trade, i.e., the maximum possible loss during the trade, expressed in strategy.account_currency
strategy.opentrades.max_runup_percent()Returns the maximum favorable excursion for the specified trade, expressed as a percentage of its entry value
strategy.opentrades.max_runup()Returns the maximum run up of the open trade, i.e., the maximum possible profit during the trade, expressed in strategy.account_currency
strategy.opentrades.profit_percent()Returns the profit/loss of the open trade, expressed as a percentage
strategy.opentrades.profit()Returns the profit/loss of the open trade, expressed in strategy.account_currency
strategy.opentrades.size()Returns the direction and the number of contracts traded in the open trade
strategy.order()Creates a new order to open, add to, or exit from a position
strategy.percent_of_equityThis is one of the arguments that can be supplied to the default_qty_type parameter in the strategy declaration statement
strategy.position_avg_priceAverage entry price of current market position
strategy.position_entry_nameName of the order that initially opened current market position
strategy.position_sizeDirection and size of the current market position
strategy.risk.allow_entry_in()This function can be used to specify in which market direction the strategy.entry function is allowed to open positions
strategy.risk.max_cons_loss_days()The purpose of this rule is to cancel all pending orders, close all open positions and stop placing orders after a specified number of consecutive days with losses
strategy.risk.max_drawdown()The purpose of this rule is to determine maximum drawdown
strategy.risk.max_intraday_filled_orders()The purpose of this rule is to determine maximum number of filled orders per 1 day (per 1 bar, if chart resolution is higher than 1 day)
strategy.risk.max_intraday_loss()The maximum loss value allowed during a day
strategy.risk.max_position_size()The purpose of this rule is to determine maximum size of a market position
strategy.shortA named constant for use with the direction parameter of the strategy.entry and strategy.order commands
strategy.wintradesNumber of profitable trades for the whole trading range
strategy()This declaration statement designates the script as a strategy and sets a number of strategy-related properties
Positions & Locations
10 itemslocation.abovebarShape is plotted above main series bars
location.belowbarShape is plotted below main series bars
location.topShape is plotted near the top chart border
location.bottomShape is plotted near the bottom chart border
location.absoluteShape is plotted on chart using indicator value as a price coordinate
xloc.bar_indexDrawing object treats each x-coordinate as a bar_index value
xloc.bar_timeDrawing object treats each x-coordinate as a UNIX timestamp
yloc.priceSpecifies interpretation of y-value as a price coordinate
yloc.abovebarSpecifies interpretation of y-value as above the bar
yloc.belowbarSpecifies interpretation of y-value as below the bar
Styling & Layout
13 itemsextend.noneA named constant for line extensions (none)
extend.leftA named constant for line extensions (left)
extend.rightA named constant for line extensions (right)
extend.bothA named constant for line extensions (both)
scale.rightIndicator is added to the right price scale
scale.leftIndicator is added to the left price scale
scale.noneIndicator is added in 'No Scale' mode
size.autoSize of the shape automatically adapts to the size of the bars
size.tinySize of the shape is constantly tiny
size.smallSize of the shape is constantly small
size.normalSize of the shape is constantly normal
size.largeSize of the shape is constantly large
size.hugeSize of the shape is constantly huge
Ready to create your Pine Script indicators?
Use Pineify to draft Pine source from a defined rule. Review the code, check its syntax and test behavior on the intended chart.