Pine Script Basics: Write and Test Your First Indicator in Version 6

A Pine Script v6 file has three parts in order: a version line, one declaration (indicator, strategy or library) and your code. This page walks through opening the Pine Editor, three short scripts, and the v6 changes that cause most compile errors. We wrote the code to the documentation but did not compile it in TradingView.

What does a Pine Script file contain?

TradingView's Pine Script documentation says a script follows the order version annotation, declaration statement, code. The version annotation, //@version=6, tells the compiler which language version to use. It is optional, and if it is left out the compiler assumes version 1, so always write it. The documentation strongly recommends using the latest version.

Every script needs exactly one declaration statement: indicator(), strategy() or library(). An indicator must produce an output, such as plot(). A strategy must place orders or produce output. A library must export at least one function, method, type or enum. The rest is your code. Global statements start in the first column, and code inside an if block or a function is indented by a tab or four spaces. Comments start with //.

The smallest valid script, from the documentation, is three lines: the version line, indicator("My Script") and plot(close).

PartExampleRule
Version//@version=6Optional but recommended; omitted means version 1
Declarationindicator("My Script")Exactly one per script
Codeplot(close)Global lines start in column one; blocks are indented

How do you open the editor and run a script?

The steps below follow the Pine Script primer. Select the Pine Editor tab at the bottom of a TradingView chart. Open the dropdown beside the script name at top left and choose Create new, then Indicator. Select all the existing code and replace it with yours. Save with Ctrl+S and give the script a name. Choose Add to chart in the editor's menu bar.

If the script compiles it appears on the chart. If not, the editor shows an error with a line number. Read the line it points to and the line above it; the cause is often one line earlier. Your plan limits how many indicators fit on a chart: 2 on Basic, 5 on Essential, 10 on Plus, 25 on Premium and 50 on Ultimate, per TradingView's pricing page on 23 November 2026.

Script 1: the documentation's MACD

The primer's first example is a MACD built from two exponential moving averages. We reproduce it as the documentation prints it, so you can confirm your editor works before writing your own code.

//@version=6
indicator("MACD #1")
fast = 12
slow = 26
fastMA = ta.ema(close, fast)
slowMA = ta.ema(close, slow)
macd = fastMA - slowMA
signal = ta.ema(macd, 9)
plot(macd, color = color.blue)
plot(signal, color = color.orange)

The fast average (12 bars) minus the slow average (26 bars) is the MACD line. The signal line is a 9-bar exponential average of the MACD line. The script does not set overlay, so it appears in a separate pane below the chart, as the primer says.

Script 2: your own indicator, with an input and an alert

This one is ours. It plots a 20 and 50 bar simple moving average over the price, marks each upward cross and defines an alert condition. input.int() adds a setting you can change without editing code. ta.crossover() is true on the bar where the first series moves above the second. We wrote it to the documentation but did not run it in TradingView, so paste it in and fix anything the editor flags.

//@version=6
indicator("SMA cross alert", overlay = true)
fastLen = input.int(20, "Fast SMA", minval = 1)
slowLen = input.int(50, "Slow SMA", minval = 2)
fast = ta.sma(close, fastLen)
slow = ta.sma(close, slowLen)
plot(fast, "Fast SMA", color = color.blue)
plot(slow, "Slow SMA", color = color.orange)
crossUp = ta.crossover(fast, slow)
plotshape(crossUp, "Cross up", shape.triangleup, location.belowbar, color.green)
alertcondition(crossUp, "Fast crossed above slow", "Fast SMA crossed above slow SMA")

A worked example with simple numbers (hypothetical): on one bar the 20-bar average is 99.8 and the 50-bar average is 100.0. On the next bar the 20-bar is 100.1 and the 50-bar is 100.0. On the first bar 99.8 is below 100.0; on the second 100.1 is above 100.0. crossUp is true on the second bar only, so one triangle prints there and the alert condition is true for that bar.

A second small indicator plots each bar's range as a percentage of its close, with a 20-bar average of that, as a volatility check. For a bar that runs from a low of 4,980 to a high of 5,000 and closes at 4,992, the range is 20 points and the range percentage is 20 / 4,992 x 100 = 0.40%.

//@version=6
indicator("Range % of close, 20-bar average")
rangePct = (high - low) / close * 100
avgPct = ta.sma(rangePct, 20)
plot(rangePct, "Range %", color = color.gray)
plot(avgPct, "20-bar average", color = color.orange)

Script 3: a strategy you can test

A strategy places simulated orders and fills the Strategy Tester report. This one buys on an upward cross and uses strategy.exit() with a stop of 40 ticks and a profit target of 80 ticks, a 1 to 2 risk to reward. In strategy.exit(), the loss and profit arguments are measured in ticks. It is an example of method, not a recommended strategy.

//@version=6
strategy("SMA cross with stop and target", overlay = true,
     default_qty_type = strategy.fixed, default_qty_value = 1)
fast = ta.sma(close, 20)
slow = ta.sma(close, 50)
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long)
strategy.exit("Long exit", "Long", loss = 40, profit = 80)

TradingView's default backtest fills market orders at the next bar's open, with no commission and no slippage unless you set them. Our TradingView backtesting page shows how to add costs for a Micro E-mini contract and what the fill model assumes. Do not read the report as a promise of future results.

Which Pine Script v6 changes cause the most errors?

Most online examples were written for version 4 or 5. TradingView's migration guide to version 6 lists changes that break them. The ones traders hit most are in the table.

Change in v6What goes wrongFix
No implicit number-to-bool castingA number used as a condition fails to compileWrap it, for example bool(x)
bool values cannot be nana(), nz() and fixnan() reject bool argumentsRemove them from bool values
when parameter removed from strategy ordersOld strategy.entry(..., when = cond) failsPut the order inside an if block
Lazy and / orA function such as ta.rsi() inside an and / or can stop updatingCalculate it on its own line first, then use the result
Constant integer division is fractional5 / 2 is now 2.5Use int(), math.floor() or math.round()
timeframe.period always includes a multiplierA comparison with "D" is never trueCompare with "1D"
transp argument removedOld transparency code failsUse color.new(color, 80)
Default strategy margins are 100Results differ from the same v5 scriptSet margin_long and margin_short to 0 to match v5

What are the most common beginner errors?

Based on the documentation's rules, check these first. Copying a v5 script under a //@version=6 line: see the table above. A missing or wrong version line: the compiler assumes version 1 and rejects modern syntax. Bad indentation: local blocks need a tab or four spaces. Two declaration statements in one script: only one is allowed. An indicator with no output: add a plot. A changing value where a fixed one is required, such as a moving-average length that is a series: the migration guide says mutable variables are series values and cannot be used where a simple integer is required.

A different kind of problem is a script that compiles but misleads. A script runs once on each bar from the first to the latest. On the open rightmost bar, values change until the bar closes, so an indicator that looks perfect on history can repaint live. By default strategies run once per bar at close; setting calc_on_every_tick = true runs them on each tick like an indicator. Judge a signal on closed bars, using barstate.isconfirmed if you need to test for it.

Who should not write Pine Script?

If you only want a ready-made indicator, use TradingView's public library; writing your own is a time cost with no guarantee of an edge. If you want automated live trading, a script on its own produces chart signals and alerts. Connecting them to a broker is a separate step, and your broker and any prop firm must allow it. Check the firm's automation rules before you automate anything on a funded or evaluation account. If you need heavy statistical testing, a general programming language will serve better than the Strategy Tester.

Frequently asked questions

Which Pine Script version should I use?

Version 6, declared with //@version=6 on the first line. TradingView's documentation strongly recommends the latest version, and a script without a version line is treated as version 1.

How many Pine Script indicators can I add to a chart?

Per the pricing page on 23 November 2026, indicators per chart are 2 on Basic, 5 on Essential, 10 on Plus, 25 on Premium and 50 on Ultimate.

Why does my old Pine Script code fail in version 6?

Version 6 removed several things: the when parameter on strategy orders, implicit number-to-bool casts, na on bool values and the transp argument. Integer division of constants is now fractional too.

What is the difference between indicator and strategy?

An indicator plots values or signals on the chart. A strategy also places simulated orders and fills the Strategy Tester report. Each script has exactly one declaration.

Does the code on this page work?

The MACD script is from TradingView's primer. The other scripts are ours, written to the documentation, but we did not compile them in TradingView. Paste them into the editor and fix any error it shows.

Sources

Provider documents behind this page, checked November 23, 2026.