Introduction to Pine Script
What is Pine Script and Why Use It?
Pine Script is TradingView’s proprietary scripting language designed for creating custom indicators, strategies, and tools for analyzing financial markets. Its primary advantage lies in its seamless integration with the TradingView platform, allowing you to visualize and backtest your ideas directly on the charts.
Unlike general-purpose programming languages, Pine Script is specifically tailored for trading. This means it has built-in functions and variables for accessing market data (OHLCV), calculating technical indicators (RSI, MACD, etc.), and implementing trading logic. Furthermore, it simplifies the process of sharing your creations with the TradingView community.
Understanding the TradingView Environment
Before diving into the code, it’s crucial to understand the TradingView environment. The Pine Editor is your workspace, accessible from the bottom panel of any chart. Here you’ll write, compile, and apply your scripts. Familiarize yourself with the editor’s features, including syntax highlighting, auto-completion, and error reporting. Also, remember that the chart’s timeframe affects the script’s calculations; choose wisely based on your trading style.
Pine Script Versions and Compatibility
Pine Script has evolved through several versions (v1 to v5). It’s essential to specify the version at the beginning of your script using the //@version= declaration. Always use the latest version (v5) for new scripts, as it offers the most features and optimizations. When working with older scripts, be aware of potential compatibility issues and consider migrating them to the current version if possible.
Pine Script Fundamentals
Basic Syntax and Structure
A Pine Script program typically starts with the //@version=5 declaration. Then follows the indicator() or strategy() function, which defines the script’s type. The indicator() function is used for creating indicators that display data on the chart, while the strategy() function is used for creating trading strategies that can be backtested. After that, you define inputs, calculations, and plotting instructions.
//@version=5
indicator(title="My First Indicator", shorttitle="MFI", overlay=true)
plot(close)
This simple script plots the closing price of the instrument on the chart.
Variables and Data Types
Pine Script supports various data types, including int, float, bool, and string. Variables are declared using the var keyword (for variables that retain their value across bars) or simply assigned a value (for variables calculated on each bar). Understanding data types is critical for performing calculations correctly and avoiding errors.
//@version=5
indicator(title="Example Variables", overlay=true)
float myFloat = close + 1.5
int myInt = volume
bool myBool = close > open
string myString = syminfo.ticker
plot(myFloat)
Operators and Expressions
Pine Script supports standard arithmetic, comparison, and logical operators. Understanding operator precedence is crucial for writing correct expressions. Use parentheses to explicitly define the order of operations when needed.
//@version=5
indicator(title="Operators Example", overlay=true)
float result = (close + open) * 0.5 // Average price
bool condition = close > open and volume > 1000 // Bullish bar with high volume
plot(result)
Built-in Functions and Variables
Pine Script offers a rich set of built-in functions for accessing market data, calculating technical indicators, and implementing trading logic. Explore the TradingView documentation to discover available functions and variables. Some essential functions include sma(), rsi(), macd(), security(), and time(). Built-in variables provide information about the current symbol (syminfo.ticker), timeframe (timeframe.period), and date/time (time).
Creating Your First Pine Script
Writing a Simple Indicator
Let’s create a simple moving average indicator. This example demonstrates how to use the sma() function and plot the result on the chart.
//@version=5
indicator(title="Simple Moving Average", shorttitle="SMA", overlay=true)
length = input.int(20, title="SMA Length")
smaValue = ta.sma(close, length)
plot(smaValue, color=color.blue)
This script calculates the 20-period simple moving average of the closing price and plots it on the chart as a blue line.
Adding Input Options for Customization
Inputs allow users to customize the indicator’s parameters. Use the input.*() functions to define inputs for various data types. Give meaningful titles and default values to enhance the user experience.
//@version=5
indicator(title="Customizable SMA", shorttitle="CSMA", overlay=true)
length = input.int(20, title="SMA Length", minval=1)
source = input.source(close, title="Source")
color = input.color(color.blue, title="Color")
smaValue = ta.sma(source, length)
plot(smaValue, color=color)
This script adds inputs for the SMA length, the data source (e.g., open, high, low, close), and the plot color.
Plotting Data on the Chart
The plot() function is used to display data on the chart. You can customize the plot’s color, style, and width. Consider using plotshape(), plotchar(), and plotbar() for more advanced visualizations.
//@version=5
indicator(title="Plotting Examples", overlay=true)
rsiValue = ta.rsi(close, 14)
plot(rsiValue, color=color.purple)
plotshape(ta.crossover(rsiValue, 70), style=shape.triangledown, color=color.red, size=size.small)
plotshape(ta.crossunder(rsiValue, 30), style=shape.triangleup, color=color.green, size=size.small)
This script plots the RSI and displays triangle markers when the RSI crosses above 70 or below 30.
Understanding and Using Alerts
Alerts can be triggered based on conditions in your script. Use the alertcondition() function to define alert conditions and the alert() function to trigger alerts.
//@version=5
indicator(title="Alert Example", overlay=true)
closeAboveSMA = close > ta.sma(close, 20)
alertcondition(closeAboveSMA, title="Close Above SMA", message="Price closed above 20 SMA!")
if (closeAboveSMA)
alert("Price closed above 20 SMA!", alert.freq_once_per_bar)
This script triggers an alert when the closing price crosses above the 20-period SMA. alert.freq_once_per_bar is used to prevent multiple alerts on the same bar.
Advanced Pine Script Techniques
Working with Timeframes and Security Function
The security() function allows you to access data from different symbols and timeframes. This is powerful for creating indicators that consider information from multiple sources. Use it judiciously, as excessive use can impact script performance.
//@version=5
indicator(title="Multi-Timeframe Analysis", overlay=true)
higherTimeframeSMA = request.security(syminfo.tickerid, "D", ta.sma(close, 20))
plot(higherTimeframeSMA, color=color.orange)
This script fetches the 20-period SMA from the daily timeframe and plots it on the current chart.
Implementing Trading Strategies with strategy()
The strategy() function enables you to create backtestable trading strategies. Use strategy.entry(), strategy.exit(), and strategy.close() to define entry and exit rules. Remember to set commission costs realistically for accurate backtesting results.
//@version=5
strategy(title="Simple SMA Strategy", shorttitle="SMAS", overlay=true)
longCondition = ta.crossover(close, ta.sma(close, 20))
shortCondition = ta.crossunder(close, ta.sma(close, 20))
if (longCondition)
strategy.entry("Long", strategy.long)
if (shortCondition)
strategy.entry("Short", strategy.short)
This strategy enters a long position when the price crosses above the 20-period SMA and a short position when it crosses below. Note: proper exit strategy is needed in real world scenarios.
Using Arrays and Loops
Arrays allow you to store and manipulate collections of data. Loops enable you to perform repetitive tasks. Use arrays and loops carefully, as they can impact script performance if not optimized.
//@version=5
indicator(title="Array Example", overlay=true)
var float[] myPrices = array.new_float(0)
array.push(myPrices, close)
if array.size(myPrices) > 10
array.shift(myPrices)
sum = 0.0
for i = 0 to array.size(myPrices) - 1
sum := sum + array.get(myPrices, i)
average = sum / array.size(myPrices)
plot(average)
This script stores the last 10 closing prices in an array and calculates their average.
Drawing Tools and Visualizations
Pine Script provides functions for drawing lines, labels, and boxes on the chart. Use these tools to enhance the visual representation of your indicators and strategies.
//@version=5
indicator(title="Drawing Example", overlay=true)
if ta.crossover(close, ta.sma(close, 20))
line.new(bar_index[1], low[1], bar_index, high, color=color.green, width=2)
label.new(bar_index, high, text="Crossover!", color=color.green, style=label.style_label_up)
This script draws a green line and label when the price crosses above the 20-period SMA.
Debugging and Publishing Pine Scripts
Troubleshooting Common Errors
Common errors in Pine Script include syntax errors, type mismatches, and runtime errors (e.g., division by zero). Pay close attention to the error messages in the Pine Editor and use the debugging tools to identify and fix issues.
Using the Pine Script Editor’s Debugging Tools
The Pine Editor provides debugging tools like breakpoints and the ability to step through your code. Use these tools to inspect variable values and identify the source of errors.
Publishing Your Script on TradingView
To publish your script, click the “Publish Script” button in the Pine Editor. You’ll need to provide a description, choose a category, and set permissions. Consider making your script open source to contribute to the TradingView community.
Understanding Script Permissions and Open Source
When publishing a script, you can choose between three permission options: public, protected, and private. Public scripts are visible to everyone and their source code is also available. Protected scripts are visible to everyone, but their source code is hidden. Private scripts are only visible to you. Choose the option that best suits your needs and preferences. Also, remember to follow TradingView’s guidelines for publishing scripts to avoid any issues. Consider adding a license to your open-source scripts to specify how others can use and distribute your code.