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:
Build any oscillator, overlay, or visualization you can imagine, from custom RSI variants to multi-timeframe dashboards with gradient heatmaps.
Define entry/exit rules and backtest them against years of historical data. Evaluate win rate, profit factor, drawdown, and Sharpe ratio.
Fire push notifications, emails, or webhook calls to external services when your custom conditions are met on any asset, any timeframe.
Package common functions into libraries that any script can import: risk calculators, custom smoothing algorithms, signal generators.
Create information panels pinned to chart corners showing multi-timeframe data, portfolio metrics, or market scanners.
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.
Open the Pine Editor
Write or paste your code
Ctrl+Z (undo), Ctrl+/ (toggle comment), and Ctrl+Space (auto-complete).Add to chart
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.Iterate and save
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.
1//@version=62indicator("Comments Demo")34// This is a single-line comment: the compiler ignores everything after //56/*7 This is a block comment.8 It can span multiple lines.9 Useful for temporarily disabling large sections of code10 or writing detailed documentation headers.11*/1213sma20 = ta.sma(close, 20) // inline comment after code14plot(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.
| Variable | A 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. |
| Function | A 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. |
| Operator | Symbols that perform operations: + (add), - (subtract), > (greater than), == (equals), and/or/not (logical). They combine values and produce results. |
| Condition | An expression that evaluates to true or false: close > open means "is the close higher than the open?" Conditions drive all trading logic. |
| Expression | Any 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.
1//@version=6 // 1. Version annotation2indicator("BTC Momentum Check", overlay=false) // 2. Declaration statement34// 3. Logic body: calculations and conditions5rsiValue = ta.rsi(close, 14)6smaOfRSI = ta.sma(rsiValue, 9)7isBullish = rsiValue > smaOfRSI89// 4. Output: visual rendering10plot(rsiValue, "RSI", color.white, 2)11plot(smaOfRSI, "RSI Signal", color.orange, 1)12bgcolor(isBullish ? color.new(color.green, 90) : color.new(color.red, 90))Version Annotation
//@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.Declaration Statement
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.Logic Body
Output Statements
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" |
| shorttitle | An abbreviated name for the legend when space is limited. Example: "RSI Dash" |
| overlay | true = 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. |
| precision | Number of decimal places in the legend values. For BTC prices use 2; for percentages use 1. |
| max_lines_count | Maximum number of line drawing objects the script can maintain (default 50, max 500). |
| max_labels_count | Maximum number of label drawing objects the script can maintain (default 50, max 500). |
| max_bars_back | How 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.
Technical analysis: moving averages, RSI, MACD, Bollinger Bands, crossover/crossunder, pivot detection, and more.
Mathematical operations: abs, round, max, min, pow, sqrt, log, ceil, floor, random.
String manipulation: tostring, format, contains, replace, split, length, upper, lower.
Color creation: new (with transparency), rgb, from_gradient, r/g/b component access.
Array operations: new, push, get, set, size, sort, avg, max, min, median, stdev, slice, copy.
External data: security (multi-timeframe), financial (fundamentals), quandl (economic data), dividends, splits, earnings.
Symbol information: tickerid, currency, type, mintick, timezone, session, description.
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.
1//@version=62indicator("Hello PineScript", overlay=true)34sma20 = ta.sma(close, 20)5isAbove = close > sma2067plot(sma20, "SMA 20", color.new(#5ce1e6, 0), 2)8bgcolor(isAbove ? color.new(color.green, 92) : color.new(color.red, 92))//@version=6
indicator("Hello PineScript", overlay=true)
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.sma20 = ta.sma(close, 20)
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.isAbove = close > sma20
plot(sma20, "SMA 20", color.new(#5ce1e6, 0), 2)
bgcolor(isAbove ? ... : ...)
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 introduced | Libraries, user-defined types (UDTs), methods, maps, matrices, switch statements, for...in loops, improved string functions, and the import keyword. |
| v6 improvements | Better type inference, improved error messages, function overloading, enhanced runtime performance, and stricter type checking that catches bugs earlier. |
| Migration | Most 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 scripts | When 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.
1//@version=62indicator("Configurable Trend Overlay", overlay=true)34// Inputs: these appear in the indicator settings panel5length = 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")1112// Calculation using user inputs13sma = ta.sma(srcInput, length)1415// Output with conditional background16plot(sma, "SMA", maColor, 2)17bgcolor(showBG ? (close > sma ? color.new(color.green, 92) :18 color.new(color.red, 92)) : na)Inputs are your interface
Put this lesson to work
Free on Thrive, no account needed.