Draft:Pine Script
Review waiting, please be patient.
This may take 3 months or more, since drafts are reviewed in no specific order. There are 4,502 pending submissions waiting for review.
Where to get help
How to improve a draft
You can also browse Wikipedia:Featured articles and Wikipedia:Good articles to find examples of Wikipedia's best writing on topics similar to your proposed article. Improving your odds of a speedy review To improve your odds of a faster review, tag your draft with relevant WikiProject tags using the button below. This will let reviewers know a new draft has been submitted in their area of interest. For instance, if you wrote about a female astronomer, you would want to add the Biography, Astronomy, and Women scientists tags. Editor resources
Reviewer tools
|
Where to get help
How to improve a draft
You can also browse Wikipedia:Featured articles and Wikipedia:Good articles to find examples of Wikipedia's best writing on topics similar to your proposed article. Improving your odds of a speedy review To improve your odds of a faster review, tag your draft with relevant WikiProject tags using the button below. This will let reviewers know a new draft has been submitted in their area of interest. For instance, if you wrote about a female astronomer, you would want to add the Biography, Astronomy, and Women scientists tags. Editor resources
This draft has been resubmitted and is currently awaiting re-review. |
| Pine Script | |
|---|---|
| Paradigm | Imperative, event-driven, expression-oriented, object-based |
| Developer | TradingView |
| Stable release | v6
/ November 2024 |
| Typing discipline | Static, strong, nominal, inferred |
| Scope | Technical analysis, algorithmic trading |
| Platform | Cloud-based |
| Influenced by | |
| Java, Python, JavaScript | |
Pine Script is a proprietary scripting language developed by TradingView for use in its online platform. It is a high-level, domain-specific language designed for programming custom technical indicators and algorithmic trading strategies that perform sequential calculations, display visuals, and generate alerts on time-series data for financial markets. Pine Script code is compiled and executed exclusively on TradingView's servers. Platform users write and save scripts in TradingView's online code editor, then apply them to a dataset to run them. Users can also publish Pine Script code on TradingView to share custom indicators, strategies, and code libraries with other users.
History
TradingView created Pine Script to provide traders with an efficient, cloud-based language for developing indicators and trading strategies that natively run on the platform's available market data. They aimed to keep the language accessible and easy to understand for the largest possible audience, so that platform users with different programming backgrounds could create custom trading tools.
The first version of Pine Script was released in December 2013 and maintained until September 2015. Successive versions of the language were gradually released to support new requested features and improvements, as outlined in TradingView's release notes.
Pine Script v1 introduced a core set of language components for defining calculations across a time series. The initial version included two distinct script types for indicators and strategy simulations, a static type system with primitive types and other types for visuals, built-in variables for accessing chart and symbol data, built-in functions for creating inputs, requesting data, generating plots, and performing other common tasks, syntax for variable declarations and user-defined functions, and a basic set of operators.
Pine Script v2 was released in October 2015 and maintained until February 2017. Notable additions to the language included `if...else` statements, mutable variables, `for` loops, improved strategy script behaviors and metrics, script alerts, and the ability to publish closed-source scripts.
Pine Script v3, released in March 2017 and maintained until June 2019, added several changes to the language, including updated data types for constant variables and values, automatic conversion of numeric values in Boolean expressions, the removal of variable self-referencing and forward references, new metrics and behaviors for strategy scripts, and improvements to the `security()` function for data requests.
Pine Script v4, released in June 2019 and maintained until October 2021, added new data types and usability improvements. Notable additions included keywords for declaring persistent variables, built-in type keywords, functions for explicit type casting, `else if` conditional branches, short-circuit evaluation of ternary operators, compound assignment operators, reference types for generating chart drawings, an array data type, additional types of alerts, several new built-in functions and variables for common tasks, and improvements to script inputs.
Pine Script v5, maintained from October 2021 to November 2024, added multiple syntax changes and new features to the language, with a focus on expanding support for some object-oriented capabilities. Notable additions included library scripts, `switch` statements, `for...in` loops, `while` loops, type qualifier keywords, matrix and map data types, user-defined types, enumerated types, additional drawing types, function overloading, method syntax, logging functions, and a built-in runtime profiler. This version also added multiple new built-in functions and variables for data requests, mathematical calculations, string parsing, strategy analysis, and other common routines.
Pine Script v6 is the latest version of the language. The initial release in November 2024 removed undefined "bool" (Boolean) values and implicit "bool" type casting, and introduced short-circuit evaluation of logical operators (`and` and `or`) for efficiency. It also added full support for dynamic data requests, negative indexing for arrays, text formatting features for drawing types, and improved data management for strategy scripts. TradingView regularly updates the latest version. As of April 2026, some notable additions over recent months include a new function and data types for requesting footprint candle data, a new `active` parameter for script inputs, dynamic stopping criteria in `for` loops, updated line-wrapping rules, and the ability to sort arrays and matrices that store object references.
Design and execution model
In contrast to general-purpose languages, Pine Script is intended specifically for computing technical indicators and simulating trading strategies using the market data available on TradingView. The language is designed to be relatively easy to learn for first-time programmers, with sufficient capabilities for knowledgeable programmers to build moderately complex trading tools directly on the platform.
Pine Script's structure is highly abstracted for simplicity; written source code primarily defines the language version, the script settings, and the sequence of calculations and logic that must execute across the data points in a given time-series dataset. The written code is translated into an intermediate language and processed by an optimizing compiler. The final compiled code then executes in the server-side runtime environment.
Pine Script relies on an event-driven, sequential execution model to automatically execute the computations defined by a script repeatedly across successive data points in a time series. When a user runs a script, its compiled code executes once for each bar (data point) or tick (an update to a data point) in the dataset, in chronological order. Each execution performs separate calculations and generates output data, such as chart visuals, for a specific bar using the price, volume, and other information available on that bar. After an execution ends, the runtime system saves (commits) data for all necessary variables, expressions, and objects to internal time-series structures, which subsequent executions can reference to access previously saved data. If the code is running on an open chart or in an active alert, repeated executions and storage continue indefinitely as new data becomes available, enabling the process to update calculations and outputs in real time.
Pine Script's runtime uses processes such as automatic buffer allocation and garbage collection to manage memory across all code executions in a script run. The system dynamically maintains a historical buffer for each series of values required by the script based on the historical references in the code. For efficiency, each buffer is sized to store a series of data for only the number of past bars required by all executions. Most objects created by a script use memory for as long as their references are in use. After executions stop using a reference, the garbage collector eventually releases the allocated memory. However, if the code refers to the history of the expression that constructs an object, copies of that object's state from previous executions will temporarily remain in memory and be accessible from the historical buffer.
Pine Script uses an internal backtesting system to simplify the construction of trading strategy simulations. Programmers define the logic of their strategy's orders using high-level commands. The system automatically processes orders based on the script's properties and the commands executed on each bar, then displays simulated trading results and performance metrics in a dedicated tab.
A primary focus in Pine Script's design is to provide sufficient high-level features to minimize the code required from the programmer. In addition to the automatic compilation, runtime, and memory features, the language includes multiple built-in functions and variables to simplify tasks common to indicator and strategy design, such as computing widely used technical indicators and metrics, requesting additional data for multi-timeframe and multi-instrument analysis, simulating and modifying orders, and generating dynamic visuals and alerts.
Syntax and characteristics
Pine Script syntax is influenced by some general-purpose languages, most notably Java. However, it also relies on distinct code constructions and different semantics.
Structure, statements, and expressions
A script written in Pine Script consists of three primary parts:
- The `//@version=` compiler annotation, a special comment that specifies the Pine Script language version to the compiler.
- An `indicator()`, `strategy()`, or `library()` script declaration statement, which specifies the type of script and its default properties.
- The sequence of expressions and statements to execute. Indicators and strategies must include at least one expression that defines outputs, such as chart visuals or strategy commands. Libraries must contain at least one `export` statement.
Expressions in Pine Script primarily include the following:
- Function and method calls
- Arithmetic operations using the `+`, `-`, `*`, `\`, or `%` operators
- Comparison (relational) operations using the `>`, `<`, `>=`, `<=`, `==`, or `!=` operators
- Logical and conditional operations using the `and`, `or`, or `not` and `?:` operators
- History-referencing operations in the format `x[n]`, where `x` represents a variable or expression, and `n` represents the number of bars back, relative to the current bar, to reference in the time series.
Statements in Pine Script include the following:
- The script declaration statement
- A variable declaration, which declares a variable or a tuple of variables, and initializes them using the assignment operator (`=`)
- A variable or field reassignment, which assigns a new value to a declared variable or field using the reassignment operator (`:=`) or a compound assignment operator such as `+=` (addition assignment)
- An `if` or `switch` conditional structure, which conditionally executes blocks of code
- A `for`, `for...in`, or `while` loop statement, which iteratively executes a block of code
- The `type` statement, which declares a user-defined type
- The `enum` statement, which declares an enumerated type
- A function or method definition
- An `export` statement, which library scripts use to export functions, data types, and constant variables
- An `import` statement, which imports exported code from a published library
Pine Script partly follows an expression-oriented paradigm. Although the above are all primarily statements, variable declarations, variable and field reassignments, conditional statements, and loops can also yield values. Scripts can assign variables and fields directly using the result of a conditional statement or loop. Similarly, variable declarations, reassignments, conditional statements, and loops can be used as return statements in function definitions.
Typing
Pine Script is a statically typed language; the data type of each variable and value must be known at compile time and cannot change at runtime. The language's type system includes a set of primitive (fundamental) value types, unique value types for use in specific functions, and reference types for creating objects.
Value types in Pine Script include the following:
- The "int" type for signed integers.
- The "float" type for double-precision floating-point numbers. Literal "float" values can use standard decimal notation, or use E notation to express very large or very small numbers.
- The "bool" type for Boolean values. Boolean literals in Pine Script are either `true` or `false`.
- The "color" type for specifying sRGB color information in script visuals. Color literals in Pine Script are expressed in the format `#RRGGBBAA`, where each set of two hexadecimal digits defines the value of the color's red, green, blue, or alpha channel.
- The "string" type for strings. String literals can be enclosed by a pair of one or three quotation marks or apostrophes.
- Unique types for specific built-in function parameters, such as the "plot_display" type for setting the allowed display locations for a plot.
- Enumerated types declared using the `enum` keyword.
Reference types include the following:
- Drawing types for creating objects that contain data for drawing visuals, such as lines, labels, polylines, boxes, and tables.
- Collection types for creating array, matrix, and map data structures.
- Types for objects that store other specific kinds of data, such as chart coordinates and footprint information.
- Unique reference types for displaying plots and horizontal levels.
- User-defined types declared using the `type` keyword.
Pine Script includes a "void" type, which represents the absence of a value. Calls to built-in functions that produce only side effects return "void" results. Scripts cannot use expressions that evaluate to "void" in other expressions or variable assignments.
Programmers can use the identifiers for most data types, excluding unique built-in types and the "void" type, as keywords to specify the type of a declared variable, parameter, or field. For collection types, the type identifier consists of the `array`, `matrix`, or `map` keyword followed by a type template containing the keywords for the collection's element types in angle brackets. For example, the type identifier for an array of integers is `array<int>`.
Using type keywords is often optional; in most cases, the compiler infers a variable's type using its assigned expression. Explicit typing is required only in the following cases:
- The initial or default value of a variable, parameter, or field is `na` (undefined), and the expression in the declaration does not convert the `na` value to a specific type.
- The identifier refers to the first parameter of a method.
- The identifier refers to any parameter of an exported function or method.
Type casting
Pine Script uses implicit type-casting rules only for the "int" type. If a value is an integer, it is automatically converted to the "float" type if either of the following applies:
- The value is part of an arithmetic or comparison operation that includes an operand of the "float" type.
- The value is passed to a declared variable, parameter, or field of the "float" type.
All other type conversions in Pine Script are explicit. The language includes type-casting functions that convert numeric and `na` (undefined) values to a subset of built-in types. For conversions not supported by these functions, such as directly casting "bool" values to "int" or "float" types, programmers can write logical expressions that yield a result of the target type.
Type qualifiers
Pine Script's type system includes four distinct type qualifiers. These qualifiers indicate whether data of a specific type is known at compile time or at runtime, and whether the data can change across code executions:
- Values with the "const" qualifier are available at compile time and do not change at runtime.
- Values with the "input" qualifier are returned from script inputs. Similar to "const" values, "input" values do not change at runtime.
- Values with the "simple" qualifier are available as of the first bar in the dataset. They do not change during executions for subsequent bars.
- Values with the "series" qualifier are computed at runtime and can change during script executions for any bar.
Value types can inherit any type qualifier. However, instances of reference types always inherit the "series" qualifier.
Pine Script uses a hierarchy to determine a value's type qualifier. The "const" qualifier is lowest in the hierarchy, and "series" is the highest. The type qualifier of a returned value is the highest qualifier used by an expression or statement. For instance, an expression that depends on values qualified as "const" and "series" evaluates to a "series" result.
Programmers can optionally prefix type keywords with the `const`, `simple`, and `series` keywords to specify the type qualifiers required by variables and function parameters of value types. When used in a variable declaration, the `const` keyword also specifies that the variable cannot be reassigned.
Variables and function parameters that expect a value with a specific type qualifier can also accept a value of the same type with a lower qualifier. For example, if a function parameter has the "simple float" qualified type, it also allows "input float" or "const float" arguments. However, it cannot accept a "series float" argument.
Variable declaration modes
Pine Script includes a `var` keyword for use in variable declarations. In contrast to similar keywords in other languages, the `var` keyword in Pine Script specifies that a declared variable's data persists across bars.
If a variable declaration does not include a keyword, the variable's data does not persist after each execution ends; the statements in the declaration execute again on each execution of the scope to reinitialize the variable with data for the current bar in the series. By contrast, if the declaration is prefixed with `var`, the variable remains initialized upon the first execution of the scope on a closed bar, and the statements in the declaration do not execute again after that point in the script run. The assigned value persists across executions for subsequent bars, changing only after reassignment operations. However, if the code executes on data for an open bar, a rollback process resets the variable to its latest committed state, as of the previous closed bar, before the system executes the code on the open bar again. This process prevents the open bar's temporary data from affecting the variable indefinitely across subsequent executions.
Programmers can declare a persistent variable, or a type field, that is not subject to rollback by prefixing the declaration with the `varip` keyword instead of `var`. The `varip` keyword specifies that a declared variable or field remains initialized after the first execution of the scope, even if that execution occurs before a bar closes. From that point onward in the script run, the assigned value persists across all subsequent executions without resetting to a previous state. Each reassignment operation permanently affects the stored value on future executions while the script remains active.
Line formatting and code blocks
Individual single-line expressions and statements are typically defined on separate lines of code. However, programmers can list multiple expressions and statements on the same line of code by separating them using commas.
Pine Script supports line wrapping to condense the horizontal length of written code. The wrapping rules are as follows:
- If an expression is not enclosed in parentheses, each wrapped code line must be indented by any number of spaces that is not a multiple of four.
- If an expression is enclosed in parentheses, all wrapped lines can use any number of spaces for indentation, including zero and multiples of four.
- If an expression includes a multiline string literal, enclosed by a pair of three quotation marks or apostrophes, the string can span multiple code lines. Indentation is optional; all leading spaces used for indentation are included in the string.
Unlike many other languages, Pine Script uses indentation rather than curly brackets or keywords to delimit code blocks for function definitions, control flow statements, and type declarations. Each statement and expression within a block must have an indentation of four spaces relative to the indentation of the beginning of the full statement. The last indented statement or expression in the block marks the block's end.
Functions, return statements, and side effects
A function definition in Pine Script separates the declared signature (the function's identifier and its parameters) from the function body (the set of instructions to execute) using `=>` as the delimiter. Function definitions support single-line and multiline syntax; the instructions that a function call executes can be defined on the same line as the signature or in a block of indented statements. Prefixing a function definition with the `method` keyword defines a function as a method associated with a specific data type.
Pine Script supports function overloading. A function or method is a valid overload if it shares the same identifier as a previously defined function, and either of the following conditions applies:
- The function includes a different number of parameters without default arguments.
- The function has the same number of required parameters as other overloads, and at least one parameter is of a different type than the parameter at the same position in the signatures of the other overloads.
Unlike several other languages, Pine Script does not use a keyword or symbol to define a function's return statement. The return statement and the function's return type are implicitly defined by the final statement or expression, or the final tuple of expressions, within the function's body. A call to the function returns the result of evaluating the final defined code in the body using the specified arguments. Similar behavior applies to conditional statements and loops: they can return the result of evaluating the final statement in the executed code block.
Pine Script allows user-defined functions to produce a limited set of side effects before returning a value. Such side effects include:
- Modifying objects referenced by global variables
- Generating visuals using drawing types
- Creating alert events with the `alert()` function
- Generating logs with the `log.*()` functions
- Defining strategy orders with `strategy.*()` commands
Tuples
Tuples in Pine Script are sets of expressions or identifiers enclosed in square brackets (`[expr1, expr2, …]`). The language uses these data structures for the following purposes:
- Defining functions and structures that return multiple values. If a code block ends with a tuple of expressions, it returns a tuple containing the results from evaluating those expressions in order.
- Tuple declarations. If a call or structure returns multiple values, programmers declare a tuple of variables to store the results.
- Multi-value arguments for specific built-in function parameters. For example, the `options` parameter for `input*()` functions requires a tuple of strings to define a list of options for script inputs. The `expression` parameter for `request.*()` functions can accept a tuple of expressions to evaluate on a requested dataset.
Code examples
The following is an example indicator that logs "Hello, World!" on a dataset's first bar and displays a line plot of price returns:
//@version=6
indicator("My script") // Declares that the script is an indicator named "My script", with default properties.
// The code below defines the process that executes on each bar in the dataset.
// Log a "Hello, World!" message on the dataset's first bar.
if barstate.isfirst
log.info("Hello, World!")
// Calculate the close-based price return on the current bar and assign the result to a variable.
// The variable is reinitialized on each bar and tick.
// The `float` keyword is optional in this declaration, but preferred for readability.
float priceReturn = ta.change(close) / close[1]
// Create a plot named "Price return", with default settings, to display the `priceReturn` value for each bar.
plot(priceReturn, "Price return")
This example indicator defines a function that counts the number of previous bars with prices above and below the price of the current bar over a specified period, then returns a tuple containing both values:
//@version=6
indicator("Function example")
// This defines a function named `barsAboveBelow` that accepts two arguments and returns a two-item tuple.
barsAboveBelow(float source, int window) =>
int aboveCount = 0
int belowCount = 0
// A `for` loop statement. The counter `i` starts at 1 and increments by 1 until reaching the `window` value.
for i = 1 to window
float pastSource = source[i] // Retrieves the `source` value from `i` bars back.
if source > pastSource
aboveCount += 1
if source < pastSource
belowCount -= 1
// This tuple is the final code in the function's body. Therefore, the function returns a tuple of two values.
[aboveCount, belowCount]
// Calling the function requires a tuple declaration, which declares one new variable for each returned value.
[above, below] = barsAboveBelow(close, 20)
// Plot the `above` and `below` values as columns, and an exponential moving average of their sum as a line.
plot(above, color = #00897b, style = plot.style_columns)
plot(below, color = #880e4f, style = plot.style_columns)
plot(ta.ema(above + below, 20), color = color.orange, linewidth = 3)
The example below is a simple strategy script that conditionally simulates market orders to open and close trades based on a simple moving average and volume:
//@version=6
strategy("Simple strategy", overlay = true) // The script is a strategy that displays visuals on the main chart.
// This `input.int()` call generates an input named "Length" in the script's "Settings" menu.
int lengthInput = input.int(20, "Length", minval = 1)
// Assigns a simple moving average of (open + high + low + close) / 4 values to a variable.
// The `lengthInput` value defines the length of the average (number of most recent bars).
float avgPrice = ta.sma(ohlc4, lengthInput)
if close > avgPrice and volume > volume[1]
strategy.entry("Buy", strategy.long) // Creates a long market order named "Buy" using the default quantity.
else if close <= avgPrice
strategy.close("Buy") // Creates a market order to close any open "Buy" trade.
// Plot the `avgPrice` value.
plot(avgPrice, "Avg. price", color = color.orange, linewidth = 3)
Limitations
Pine Script does not run locally on a user's device; it runs exclusively on TradingView's servers. The Pine Script compiler and runtime system are closed source, as is the compiled form of a written script. Only the written source code is visible to users. Saving scripts in the Pine Editor and running them on a dataset requires a TradingView account.
Because each script runs using TradingView's computing resources, the platform imposes multiple script computation and data limits to distribute available resources fairly among users. These limitations apply to multiple script-related features, including the following:
- Script compilation time, compilation requests, and the overall size of compiled code
- The total runtime across code executions, and the runtime of individual loops
- The total amount of allocated memory
- The maximum number of plots
- The total number of drawing objects of each type
- The total number of variables per scope
- The number of characters in a string
- The number of elements in a collection
- The maximum number of historical bars that a script can access from a chart dataset or a requested dataset
- The total number of data requests and the types of data requests that a script can execute
- The maximum sizes of historical buffers
- The maximum number of orders maintained in a strategy's history
- The total number of active scripts on a chart
While Pine Script can simulate algorithmic trading strategies, it does not directly integrate with brokers or other technologies to manage real-world trades or perform external tasks. Currently, the primary method to automate trading or other actions with Pine Script is to send script-based webhook alerts to a third-party service.
See also
- Electronic trading platform
- List of electronic trading platforms
- Technical analysis
- Technical analysis software
- List of charting software
References
1. [1] 2. [2] 3. [3] 4. [4] 5. [5] 6. [6] 7. [7] 8. [8]
- ^ "Pine Script User Guide". Forex.com. Retrieved June 3, 2026.
- ^ "How to use Pine Script". Fusion Markets. Retrieved June 3, 2026.
- ^ "What is Pine Script". TradersPost. Retrieved June 3, 2026.
- ^ "Pine Script Analysis". Binance Square. Retrieved June 3, 2026.
- ^ "Learning Pine Roadmap". PineCoders. Retrieved June 3, 2026.
- ^ "TradingView Pine Script Course". TradingCode.net. Retrieved June 3, 2026.
- ^ "Pine Script TradingView Guide". AlgoTrading101. Retrieved June 3, 2026.
- ^ "A Comprehensive Guide to Pine Script". PineConnector. Retrieved June 3, 2026.
Content Disclaimer
Informasi ini disarikan dari Wikipedia dan disajikan kembali untuk tujuan edukasi. Konten tersedia di bawah lisensi CC BY-SA 3.0. Kami tidak bertanggung jawab atas ketidakakuratan data yang bersumber dari kontribusi publik tersebut.
- The information displayed on this website is sourced in part or in whole from Wikipedia and has been adapted for the purpose of restating it. We strive to provide accurate and relevant information, however:
- There is no guarantee of absolute accuracy. Wikipedia is an open, collaborative project that can be edited by anyone, so information is subject to change.
- It is not intended to constitute professional advice. The content displayed is for informational and educational purposes only. For important decisions (e.g., medical, legal, or financial), please consult a professional.
- Content copyright. Wikipedia is licensed under the Creative Commons Attribution-ShareAlike License (CC BY-SA). This means that content may be reused with appropriate attribution and shared under a similar license.
- Responsible use. Any risk arising from the use of information from this website is entirely the responsibility of the user.


LLM-generated pages with certain obvious signs of being machine generated may be deleted without notice.
These tools are prone to specific issues that violate our policies:
Instead, only summarize in your own words a range of independent, reliable, published sources that discuss the subject.
See the advice page on large language models for more information.