How to use TradingView’s Pine Script
What is Pine Script?
Pine Script is TradingView’s native programming language designed to create custom trading tools such as indicators, strategies, and alerts on the platform. TradingView is one of the most popular technical analysis and trading platforms, used by over 50 million traders across the globe.
Compared to other programming languages, Pine Script is a lightweight script, designed to interact with TradingView in as few lines as possible. Many users compare it to Python, but traders experienced with any programming language should have an easy time learning Pine Script. Pine code is created with Pine editor, a native element of TradingView’s online platform.
Pros and cons of Pine Script
Pros |
Cons |
TradingView isn’t just a trading and charting platform, it’s also a social network for millions of traders. Many users publish Pine Script to the TradingView library, which you can modify or use as pre-created scripts. Browsing the open-source library is also a good way to become more familiar with Pine Script and learn the language. |
Using Pine Script limits you to the confines of TradingView’s platform and data. While TradingView has an extensive database, obscure markets and select price data may not be available. |
Using TradingView also gives you access to the platform’s plethora of data. Instead of having to source your own data to create indicators or backtest strategies, you can quickly grab data from the platform with a single line of Pine Script. This resource lets you skip the harvesting and formatting of data so you can test more ideas faster. |
TradingView lacks automated execution, so your Pine Script cannot execute trades without your approval. You can integrate outside software with Pine Script, but that will require third-party workarounds. |
It’s worth emphasizing Pine Script is simpler than most other programming languages. If you’ve tried to code your own trading algorithms with little prior experience, you know how challenging it is to learn a new script. In addition, TradingView’s Pine editor can check for errors and give you suggestions on your scripts. |
There are select databooks unavailable when using Pine Script. These include order book data, buy/sell volume, and tick data. If you’re looking to build indicators around these factors, you’ll be hampered by Pine Script. |
How to use Pine Script
You can start using Pine Script in a few quick steps.
- Log in to TradingView or open an account
- Go to tradingview.com/chart and open the Trading Panel
- Select FOREX.com from the list of brokers and log in using a live or demo account
- Select the Pine Editor button on the same toolbar as the Trading Panel
From there you can create custom indicators and strategies using Pine Script. Keep reading for introductions on how to create with Pine Script.
Need a FOREX.com account? Create an account here.
If you’re looking to use pre-defined TradingView indicators and charts, you can log in to FOREX.com’s web or mobile trading platforms and choose from over 50 TradingView indicators. They are integrated directly into FOREX.com web and mobile trading platforms.
How to write code in Pine Script
To create a Pine Script script, start by defining an indicator or strategy using the ‘indicator’ or ‘strategy’ keywords. Next, define the inputs such as the length of a moving average or the threshold for a particular indicator. Then, establish trading signals or alerts based on the indicator(s) used.
For example, a script could be designed to generate a buy signal when a particular indicator crosses above a certain threshold or a sell signal when it crosses below a threshold. Before implementing, you can use TradingView’s backtesting feature to see how your scripted strategy would play out in past market conditions.
Below, we go through examples of both creating indicators and strategies in Pine Script.
How to create an indicator with Pine Script
You will see this configuration upon opening Pine Script. The first two lines are comments, denoted by two forward slashes. The ‘author’ in the second line will be replaced with your TradingView username. These lines can be manually deleted. The fourth line, however, is not a comment but a directive signifying which version of Pine Script to use.
Line five is a declaration. You can specify whether you’re writing an indicator or a strategy, then assign it a name. The default name is ‘My Script’. Line six identifies what you would like to plot. In this example, close is a variable that contains the closing price of each bar.
Line five has a variety of modifiers. For example, if you’d like the closing price to be plotted on top of the price chart, you can write:
indicator("My script", overlay=true)
Designating the overlay as ‘false’ would open the plots of the closing price in a new window below the price chart. This option is the default, so you could exclude the declaration altogether.
If you want to overlay a 50-period SMA over the price chart, you would write:
To see your script in action, press the ‘Add to chart’ button. This will also save your script. Once added to your chart, a control panel will appear in the top left of the price chart.
How to create a strategy with Pine Script
Now that we’ve covered how to create indicators with Pine Script, let’s look at strategies. For this example, we’ll stick with moving averages and create a simple strategy based on moving average crossovers. The Pine Script code outlined below establishes a strategy that utilizes moving averages to identify buy and sell signals based on crossovers between a 20-period moving average and the price level.
//@version=5
strategy("Simple Moving Average Strategy", overlay=true)
First, swap out the indicator declaration with a strategy declaration.
ma_length = input(title="Moving Average Length", type=input.integer, defval=20)
Then, define the length of the moving average.
ma = sma(close, ma_length)
plot(ma, color=color.blue)
These two lines define the plot of the moving average on the chart. The first line calculates the MA, and the second plots it on the chart.
buy_signal = crossover(close, ma)
sell_signal = crossunder(close, ma)
These lines define the buy and sell signals based on the crossover of price and the moving average.
if (buy_signal)
strategy.entry("Buy", strategy.long)
if (sell_signal)
strategy.close("Buy")
if (sell_signal)
strategy.entry("Sell", strategy.short)
if (buy_signal)
strategy.close("Sell")
These eight lines define the entry and exit conditions for your strategy.
Here is the complete strategy written out in Pine Script. This is a fairly short example, and strategies written with Pine code can become much more complex depending on the number of indicators, conditions, and calculations you include.
The most thorough way to learn Pine script is to start with TradingView’s user manual, updated for Pine Script v5. You can also find trade ideas, educational content, and video walkthroughs in the TradingView community hub. With the proliferation of AI technology, a growing number of traders with some coding experience are using chatbots like ChatGPT to code trading strategies in Pine Script.
How to backtest your Pine Script strategy
Backtesting your strategy with Pine Script in TradingView is incredibly simple. Open the strategy tester tab above the script window. You’ll then be shown an overview of how your strategy performed in the time period selected including your net profit, total closed trades, and the percent of profitable trades. Check out the above strategy in action and notice the Strategy Tester results at the bottom of the image.
The information on this web site is not targeted at the general public of any particular country. It is not intended for distribution to residents in any country where such distribution or use would contravene any local law or regulatory requirement. The information and opinions in this report are for general information use only and are not intended as an offer or solicitation with respect to the purchase or sale of any currency or CFD contract. All opinions and information contained in this report are subject to change without notice. This report has been prepared without regard to the specific investment objectives, financial situation and needs of any particular recipient. Any references to historical price movements or levels is informational based on our analysis and we do not represent or warranty that any such movements or levels are likely to reoccur in the future. While the information contained herein was obtained from sources believed to be reliable, author does not guarantee its accuracy or completeness, nor does author assume any liability for any direct, indirect or consequential loss that may result from the reliance by any person upon any such information or opinions.
Futures, Options on Futures, Foreign Exchange and other leveraged products involves significant risk of loss and is not suitable for all investors. Losses can exceed your deposits. Increasing leverage increases risk. Spot Gold and Silver contracts are not subject to regulation under the U.S. Commodity Exchange Act. Contracts for Difference (CFDs) are not available for US residents. Before deciding to trade forex, commodity futures, or digital assets, you should carefully consider your financial objectives, level of experience and risk appetite. Any opinions, news, research, analyses, prices or other information contained herein is intended as general information about the subject matter covered and is provided with the understanding that we do not provide any investment, legal, or tax advice. You should consult with appropriate counsel or other advisors on all investment, legal, or tax matters. References to FOREX.com or GAIN Capital refer to StoneX Group Inc. and its subsidiaries. Please read Characteristics and Risks of Standardized Options.
Please note that foreign exchange and other leveraged trading involves significant risk of loss. It is not suitable for all investors and you should make sure you understand the risks involved, seeking independent advice if necessary.
The products and services available to you at FOREX.com will depend on your location and on which of its regulated entities holds your account.
FOREX.com is a trading name of GAIN Global Markets Inc. which is authorized and regulated by the Cayman Islands Monetary Authority under the Securities Investment Business Law of the Cayman Islands (as revised) with License number 25033.
FOREX.com may, from time to time, offer payment processing services with respect to card deposits through StoneX Financial Ltd, Moor House First Floor, 120 London Wall, London, EC2Y 5ET.
GAIN Global Markets Inc. has its principal place of business at 30 Independence Blvd, Suite 300 (3rd floor), Warren, NJ 07059, USA., and is a wholly-owned subsidiary of StoneX Group Inc.
© FOREX.COM 2025