Introduction to Pine Script

Welcome to the start of your Pine Script journey. By the end of this tutorial, you will have written your first custom indicator and added it to a live TradingView chart. No prior programming experience is required.

What is Pine Script?

Pine Script is a programming language built by TradingView for one specific purpose: analyzing financial markets. Think of it as a calculator that already knows what "closing price," "volume," and "moving average" mean. You don't need to teach it finance - it already speaks the language.

If you've ever used a spreadsheet to track stock prices, you've done something similar to what Pine Script does. The difference is that a spreadsheet requires you to set up columns, write formulas, and update data manually. Pine Script connects directly to TradingView's live market data and runs your logic on every single bar of a chart, automatically.

A useful analogy: imagine you hired a research assistant who sits in front of your charts 24 hours a day, watching every candle form, checking your rules, and highlighting things that matter to you. Pine Script is that assistant - except it never sleeps, never makes arithmetic mistakes, and works for free.

Why Should a Trader Learn Pine Script?

Let's make this concrete. Here are real tasks that traders do manually every day, and how Pine Script eliminates the tedium.

Checking if RSI is overbought across your watchlist. Without Pine Script, you open each chart, add the RSI indicator, and visually scan for values above 70. With Pine Script, you write three lines of code, and every chart you open automatically highlights overbought conditions with a colored background.

Tracking whether price is above or below a moving average. Manually, you add an SMA, squint at the chart, and try to figure out when price crossed over. With Pine Script, you calculate the crossover and place a clear arrow on the exact bar it happened.

Backtesting a strategy idea. You've heard that buying when the 50 SMA crosses above the 200 SMA ("golden cross") works well. Without code, you scroll through years of chart history and try to count wins and losses by eye. With Pine Script, you write a strategy, click one button, and get a full performance report with profit factor, win rate, and drawdown - across every bar in the chart's history.

These aren't hypothetical benefits. They're the reason Pine Script has become the most widely used retail trading language in the world.

Prerequisites

You need three things to follow along:

  1. A TradingView account. A free account works perfectly. Go to tradingview.com and sign up if you haven't already.
  2. A basic understanding of what a candlestick chart shows. You should know what "open," "high," "low," and "close" mean.
  3. Curiosity. No programming background is needed. We'll explain every concept from scratch.

Opening the Pine Script Editor

Let's get you into the coding environment. Follow these steps exactly:

  1. Log in to TradingView and open any chart. It doesn't matter which ticker - AAPL, BTCUSD, EURUSD, anything works.

  2. Find the Pine Editor panel. Look at the very bottom of your screen. You'll see a row of tabs: "Pine Editor," "Strategy Tester," "Trading Panel." Click Pine Editor. A text editor panel will open at the bottom of the screen.

  3. Clear the default content. TradingView may pre-fill the editor with a template script. Select all the text and delete it. We're going to write everything from scratch so you understand each piece.

  4. Familiarize yourself with the buttons. At the top of the Pine Editor panel, you'll see:

  • Add to Chart - this compiles your code and adds the indicator to the chart above
  • Save - saves your script to your TradingView account
  • Open - opens previously saved scripts
  • The editor also provides autocomplete suggestions as you type, and underlines errors in red

You're now ready to write your first script.

Your First Script

Before we write any code, let's talk about what we want to accomplish. Our goal is simple: create a custom indicator that draws a line on the chart following the closing price of each bar. This is the "Hello, World!" of Pine Script - the smallest possible script that produces a visible result.

Here is the complete script. Type it into the Pine Editor exactly as shown:

Pine Script
//@version=5
indicator("My First Indicator")

plot(close)

Now click Add to Chart. You should see a new panel appear below your main chart with a line that mirrors the price movement. Congratulations - you've just written and deployed a Pine Script indicator.

Let's break down what each line does.

Line-by-line breakdown

//@version=5 - This tells TradingView which version of the Pine Script language to use. Pine Script has gone through multiple versions over the years (v1, v2, v3, v4, v5), and each version changed how certain things work. Version 5 is the current and most capable version. You should always use v5 for new scripts. This line must always be the very first line in your script.

indicator("My First Indicator") - This declares that your script is an indicator (as opposed to a strategy or library - we'll cover the difference later). The text in quotes is the name that appears on your chart. You can change it to anything you like. This line is required - without it, TradingView doesn't know what kind of script you're writing.

plot(close) - This is where the magic happens. plot() is a built-in function that draws a line on your indicator's panel. close is a built-in variable that TradingView provides - it contains the closing price of each bar. So this line says: "For every bar on the chart, draw a point at the closing price, and connect the points with a line."

💡Three lines is all it takes

The smallest valid Pine Script indicator is just three lines: a version declaration, a script type declaration, and at least one output statement. Everything else you'll learn builds on this foundation.

What Happened When You Added It to Chart

When you clicked "Add to Chart," several things happened behind the scenes:

  1. TradingView compiled your code. It checked for syntax errors, verified that all functions and variables exist, and converted your script into something it can execute.

  2. The script ran on every bar. Pine Script doesn't run once - it runs once per bar. If your chart shows 500 daily candles, your script executed 500 times, once for each bar, from the oldest bar on the left to the newest bar on the right.

  3. Each execution produced a value. On each bar, close contained that bar's closing price, and plot() recorded that value.

  4. TradingView drew the result. After running through all bars, TradingView connected all the plotted values into a continuous line.

This "once per bar, left to right" execution model is the single most important concept in Pine Script. Every script you write will follow this pattern. Keep it in mind as we go forward.

Making It More Interesting

A line that copies the closing price isn't very useful on its own. Let's modify the script to do something a trader would actually care about: plotting a 20-period Simple Moving Average (SMA).

The idea: instead of plotting the raw closing price, we'll calculate the average of the last 20 closing prices and plot that smoothed line. This is one of the most common technical indicators in the world, and you're about to build it yourself.

Pine Script
//@version=5
indicator("My SMA Indicator", overlay=true)

smaValue = ta.sma(close, 20)
plot(smaValue, color=color.blue, linewidth=2)

Add this to your chart. You should see a blue line drawn directly on top of your candlestick chart, smoothing out the price action.

Line-by-line breakdown

indicator("My SMA Indicator", overlay=true) - We added overlay=true this time. This tells TradingView to draw the indicator directly on the main price chart, rather than in a separate panel below. Since an SMA should be compared against price, overlaying it makes visual sense.

smaValue = ta.sma(close, 20) - This line does two things. First, ta.sma(close, 20) calls a built-in function from Pine Script's ta (technical analysis) library. It calculates the Simple Moving Average of the closing price over the last 20 bars. Second, we store that result in a variable called smaValue so we can use it on the next line. You could name this variable anything - mySma, average, banana - but descriptive names make your code easier to read later.

plot(smaValue, color=color.blue, linewidth=2) - We plot the SMA value, but this time we customize the appearance. color=color.blue makes the line blue, and linewidth=2 makes it slightly thicker than the default. These are optional parameters - plot(smaValue) would work fine, but the customization makes it easier to see.

⚠️Common first-timer mistake

If you forget overlay=true when plotting something that should align with price (like a moving average), it will appear in a separate panel and the scale will match, but it won't visually overlay on the candles. If your SMA appears in the wrong place, check this parameter first.

Understanding Built-in Variables

In the examples above, we used close without defining it anywhere. That's because TradingView provides a set of built-in variables that are available in every script. The most important ones for now are:

VariableWhat it contains
openThe opening price of the current bar
highThe highest price reached during the current bar
lowThe lowest price reached during the current bar
closeThe closing price of the current bar
volumeThe number of shares/contracts traded during the current bar
bar_indexThe position of the current bar (0 for the first bar, 1 for the second, etc.)

These variables are series - meaning they have a different value on every bar. When the script runs on bar 100, close contains bar 100's closing price. When it runs on bar 101, close contains bar 101's closing price. You don't need to loop through bars yourself; Pine Script does it for you.

What You'll Learn in This Course

Now that you've seen what Pine Script can do with just a few lines, here's the roadmap for the rest of the course:

  1. Basic Syntax - The structure and grammar rules of Pine Script. How to write code that the compiler understands.
  2. Variables and Types - How to store and work with different kinds of data: numbers, text, true/false values, and colors.
  3. Operators and Expressions - Math, comparisons, and logical operations. How to express trading rules in code.
  4. Control Flow - Making decisions in your code with if statements and loops.
  5. Built-in Functions - The extensive library of technical analysis functions that Pine Script provides out of the box.
  6. Creating Indicators - Building real, useful indicators from scratch.
  7. Building Strategies - Writing automated trading strategies with entry/exit rules and backtesting.
  8. Advanced Concepts - Tables, alerts, multi-timeframe analysis, and more.

Each lesson builds on the previous one. By the end, you'll be able to take a trading idea from your head, express it as code, and test it against real market data.

💡Keep the reference manual handy

The Pine Script v5 Reference Manual documents every built-in function, variable, and parameter. You don't need to memorize everything - professional developers look things up constantly. Bookmark that page and refer to it whenever you encounter a function you haven't seen before.

Next Steps

You've written your first two indicators, learned how Pine Script executes, and seen the core structure that every script follows. In the next lesson, we'll dive into Pine Script's syntax rules - the grammar that governs how you write valid code.