Skip to main content

Introduction to PineScript

What PineScript is, what is possible, the Pine Editor, your first Hello World script, the compiler, comments, and the anatomy of every Pine script.

What Is PineScript?

PineScript is a domain-specific programming language created by TradingView for one purpose: to let traders build custom technical indicators, automated strategies, visual alerts, and reusable libraries directly on TradingView charts. It is not a general-purpose language. You cannot build websites, mobile apps, or data pipelines with it. What you can do is turn any trading idea you can describe in words into a visual, backtestable, alertable tool that runs on every asset TradingView supports: crypto, stocks, forex, commodities, and indices.

PineScript runs entirely on TradingView's servers. You write code in the built-in Pine Editor, click “Add to chart,” and the script compiles and executes across the entire visible history of whatever asset is loaded. The feedback loop is instant: change a line of code, press Ctrl+S, and the chart updates in real time. There is nothing to install, no environment to configure, and no dependency management. If you have a TradingView account, you can write PineScript right now.

What You Can Build with PineScript

PineScript is far more powerful than most traders realize. Beyond simple moving average overlays, it enables sophisticated analytical tools that rival commercial indicator suites. Here is what is possible:

Custom Indicators

Build any oscillator, overlay, or visualization you can imagine, from custom RSI variants to multi-timeframe dashboards with gradient heatmaps.

Automated Strategies

Define entry/exit rules and backtest them against years of historical data. Evaluate win rate, profit factor, drawdown, and Sharpe ratio.

Real-Time Alerts

Fire push notifications, emails, or webhook calls to external services when your custom conditions are met on any asset, any timeframe.

Reusable Libraries

Package common functions into libraries that any script can import: risk calculators, custom smoothing algorithms, signal generators.

Dashboard Tables

Create information panels pinned to chart corners showing multi-timeframe data, portfolio metrics, or market scanners.

Drawing Automation

Automatically draw support/resistance lines, Fibonacci levels, trend channels, and zone boxes based on price action.

The Pine Editor Walkthrough

Open TradingView and look at the bottom panel of the chart. You will see tabs for “Pine Editor,” “Strategy Tester,” and others. Click “Pine Editor” to open the code editor. This is where every PineScript file is written, saved, and compiled. The editor provides syntax highlighting, auto-completion for built-in functions, inline documentation via hover tooltips, and an error console that shows compilation errors with exact line numbers.

When you click “Add to chart” (or press Ctrl+Enter), TradingView's compiler reads your code, checks for syntax errors, and if everything is valid, executes the script across every bar on the chart. The output (whether it is a plotted line, a colored background, a shape marker, or a full strategy with simulated trades) appears immediately. If there is an error, the console tells you the exact line number and a clear description of the problem.

1

Open the Pine Editor

Click the “Pine Editor” tab at the bottom of any TradingView chart. A default script skeleton may already be loaded. You can clear it and start from scratch.
2

Write or paste your code

Type your PineScript code in the editor. The editor supports standard keyboard shortcuts like Ctrl+Z (undo), Ctrl+/ (toggle comment), and Ctrl+Space (auto-complete).
3

Add to chart

Click “Add to chart” or press Ctrl+Enter. The script compiles and executes. If successful, the indicator or strategy appears on the chart. If there is an error, fix the reported line and try again.
4

Iterate and save

Make changes, press Ctrl+S to save and re-execute. TradingView automatically maintains version history so you can revert to earlier versions.

Comments in PineScript

Comments are non-executable text that document your code. PineScript supports two types: single-line comments starting with // and block comments wrapped in /* */. Write comments to explain why you made a decision, not what the code does.

pine-Comment syntax
1//@version=6
2indicator("Comments Demo")
3
4// This is a single-line comment: the compiler ignores everything after //
5
6/*
7 This is a block comment.
8 It can span multiple lines.
9 Useful for temporarily disabling large sections of code
10 or writing detailed documentation headers.
11*/
12
13sma20 = ta.sma(close, 20) // inline comment after code
14plot(sma20, "SMA 20")

Programming Concepts for Non-Programmers

If you have never written code before, here is a rapid primer on the core concepts you need. PineScript is one of the easiest programming languages to learn because of its narrow scope. You only need to understand a handful of concepts to build powerful tools.

VariableA named container that stores a value. Like a cell in a spreadsheet with a label: fastMA = ta.sma(close, 10) stores the 10-period SMA in a variable called fastMA.
FunctionA reusable block of code that takes inputs and returns outputs. ta.sma(close, 10) is a function that takes a data source and a length, and returns the moving average.
OperatorSymbols that perform operations: + (add), - (subtract), > (greater than), == (equals), and/or/not (logical). They combine values and produce results.
ConditionAn expression that evaluates to true or false: close > open means "is the close higher than the open?" Conditions drive all trading logic.
ExpressionAny combination of values, variables, operators, and functions that produces a result: ta.rsi(close, 14) > 70 is an expression that returns true or false.

Anatomy of a PineScript File

Every PineScript file has four essential parts that always appear in the same order. This structure is non-negotiable: violate it and the script will not compile. Once you internalize this anatomy, every script you encounter will be immediately readable.

pine-The four parts of every PineScript file
1//@version=6 // 1. Version annotation
2indicator("BTC Momentum Check", overlay=false) // 2. Declaration statement
3
4// 3. Logic body: calculations and conditions
5rsiValue = ta.rsi(close, 14)
6smaOfRSI = ta.sma(rsiValue, 9)
7isBullish = rsiValue > smaOfRSI
8
9// 4. Output: visual rendering
10plot(rsiValue, "RSI", color.white, 2)
11plot(smaOfRSI, "RSI Signal", color.orange, 1)
12bgcolor(isBullish ? color.new(color.green, 90) : color.new(color.red, 90))
1

Version Annotation

The first line must always be //@version=6 (or 5 for v5 scripts). This is not a comment. It is a compiler directive that tells TradingView which PineScript language version to use. The version determines which syntax, functions, and features are available.
2

Declaration Statement

The second functional line is either indicator() or strategy(). This tells TradingView the type of script and configures its behavior: the display name, whether it overlays the price chart or lives in a separate pane, the number of decimal places, and more.
3

Logic Body

The middle section is where calculations, conditions, and variables live. PineScript executes this section once per bar, from the oldest bar on the chart to the current live bar. Every variable is recalculated on every bar.
4

Output Statements

The final section renders results on the chart using functions like plot(), plotshape(), bgcolor(), and barcolor(). Without output statements, your script computes values but displays nothing.

The indicator() Function Parameters

The indicator() declaration accepts many parameters that control how your script behaves and displays. Here are the most important ones:

title (required)The display name shown in the chart legend and indicator list. Example: "BTC RSI Dashboard"
shorttitleAn abbreviated name for the legend when space is limited. Example: "RSI Dash"
overlaytrue = render on the price chart (use for MAs, S/R lines). false = render in a separate pane below (use for oscillators like RSI, MACD). Default: false.
precisionNumber of decimal places in the legend values. For BTC prices use 2; for percentages use 1.
max_lines_countMaximum number of line drawing objects the script can maintain (default 50, max 500).
max_labels_countMaximum number of label drawing objects the script can maintain (default 50, max 500).
max_bars_backHow many historical bars the script can reference with the [] operator (default varies, max 5000).

Namespaces

PineScript organizes its built-in functions into namespaces: logical groupings that prevent name collisions and make the language discoverable. When you see ta.sma(), the ta part is the namespace (technical analysis) and sma is the function. This is how you know where to look for related functions.

ta.*

Technical analysis: moving averages, RSI, MACD, Bollinger Bands, crossover/crossunder, pivot detection, and more.

math.*

Mathematical operations: abs, round, max, min, pow, sqrt, log, ceil, floor, random.

str.*

String manipulation: tostring, format, contains, replace, split, length, upper, lower.

color.*

Color creation: new (with transparency), rgb, from_gradient, r/g/b component access.

array.*

Array operations: new, push, get, set, size, sort, avg, max, min, median, stdev, slice, copy.

request.*

External data: security (multi-timeframe), financial (fundamentals), quandl (economic data), dividends, splits, earnings.

syminfo.*

Symbol information: tickerid, currency, type, mintick, timezone, session, description.

strategy.*

Strategy engine: entry, exit, close, cancel, position_size, equity, netprofit, opentrades.

Hello World: Your First Indicator

Let's build the simplest possible indicator and walk through every line. This script plots a 20-period simple moving average on a Bitcoin chart with a colored background that tells you instantly whether price is above or below the trend.

pine-Hello World: SMA Trend Indicator
1//@version=6
2indicator("Hello PineScript", overlay=true)
3
4sma20 = ta.sma(close, 20)
5isAbove = close > sma20
6
7plot(sma20, "SMA 20", color.new(#5ce1e6, 0), 2)
8bgcolor(isAbove ? color.new(color.green, 92) : color.new(color.red, 92))
1

//@version=6

Compiler directive. Tells TradingView to use PineScript version 6. This must be the first line of every script. Without it, the compiler defaults to an older version and modern syntax will produce errors.
2

indicator("Hello PineScript", overlay=true)

Creates an indicator named “Hello PineScript” that renders directly on the price chart. The overlay=true parameter is critical for moving averages, without it, the SMA would appear in a separate pane below the chart, disconnected from the candles.
3

sma20 = ta.sma(close, 20)

Calculates the 20-period simple moving average of the closing price. The ta.sma() function takes two arguments: the source data (close) and the lookback period (20). The result is stored in a variable called sma20. This variable is a series. It has a different value on every bar of the chart.
4

isAbove = close > sma20

Creates a boolean (true/false) variable that is true when the current bar's close is above the SMA, and false when it is below. This condition drives the background coloring.
5

plot(sma20, "SMA 20", color.new(#5ce1e6, 0), 2)

Draws the SMA as a line on the chart. The arguments are: the data series, a display name, the color (Thrive blue with 0% transparency), and the line width (2). The display name appears in the chart legend.
6

bgcolor(isAbove ? ... : ...)

Colors the chart background. The ternary operator condition ? valueIfTrue : valueIfFalse selects green (92% transparent) when price is above the SMA, and red (92% transparent) when below. The high transparency ensures candles remain clearly visible.

PineScript v5 vs v6

Version 5 was the dominant PineScript version for years and introduced user-defined types, methods, maps, matrices, and libraries. Version 6 builds on v5 with further improvements to type inference, error messages, and function overloading. Most community scripts are still written in v5, and TradingView maintains backward compatibility.

v5 introducedLibraries, user-defined types (UDTs), methods, maps, matrices, switch statements, for...in loops, improved string functions, and the import keyword.
v6 improvementsBetter type inference, improved error messages, function overloading, enhanced runtime performance, and stricter type checking that catches bugs earlier.
MigrationMost v5 scripts work in v6 with minimal changes. TradingView provides a migration guide covering the specific syntax differences. Always start new scripts in the latest version.
Community scriptsWhen you find a community script in v4, you can usually convert it to v5/v6 with minor changes: mainly adding the ta., math., and str. namespace prefixes to built-in functions.

Making It Configurable with Inputs

Hard-coding values like 20 for the SMA length works for learning, but real indicators must be configurable. The input family of functions creates a settings panel where users can adjust parameters without touching the code. This is how professional indicators are built: smart defaults with full user control.

pine-Configurable Hello World indicator
1//@version=6
2indicator("Configurable Trend Overlay", overlay=true)
3
4// Inputs: these appear in the indicator settings panel
5length = input.int(20, "SMA Length", minval=1, maxval=500,
6 tooltip="Number of bars for the moving average calculation")
7srcInput = input.source(close, "Source",
8 tooltip="Price data to calculate the MA from")
9showBG = input.bool(true, "Show Background Color")
10maColor = input.color(#5ce1e6, "MA Line Color")
11
12// Calculation using user inputs
13sma = ta.sma(srcInput, length)
14
15// Output with conditional background
16plot(sma, "SMA", maColor, 2)
17bgcolor(showBG ? (close > sma ? color.new(color.green, 92) :
18 color.new(color.red, 92)) : na)

Inputs are your interface

Every magic number in your script should be an input. If you find yourself changing a number in the code and re-adding the script to test different values, that number should be an input. Inputs make your indicator reusable across different assets and timeframes without code changes.

Put this lesson to work

Free on Thrive, no account needed.