TradingView Pine Script: The Trader's Guide, Not the Coder's
Education 18 min read

TradingView Pine Script: The Trader's Guide, Not the Coder's


TradingView Pine Script is the built-in coding language that turns a trading idea into a custom indicator or an automated alert, right inside the charts you already use. It was made for traders, not software engineers, so the syntax stays close to plain trading logic. A script reads price and volume, runs your rules on every bar, then plots a line, fires an alert, or runs a backtest through the Strategy Tester. You do not need a computer science degree to start. If you can describe a setup in words, such as buy when a fast moving average crosses a slow one, you can usually write it in a dozen lines. This guide skips the programmer jargon. It covers what Pine Script is, how a version 5 script is put together, and the three built-in functions you will actually reach for, shown on gold, the euro and Bitcoin.

What a finished Pine Script signal looks like

Before any syntax, look at the payoff. A working script watches your rule and marks the exact bar it fires on.

TradingView Pine Script EMA crossover signal on a spot gold daily chart, the blue EMA 20 crossing above the orange EMA 50 with a green triangle marking where ta.crossover fires the buy signal, and the later stretch where EMA 20 sits below EMA 50 labelled as a bearish regime
Spot gold (XAU/USD), daily. The blue line is the 20-period EMA, the orange line is the 50-period EMA. The green triangle marks where ta.crossover(ema20, ema50) returns true, the moment the fast average crosses above the slow one. Later, with EMA 20 below EMA 50, the script reads a bearish regime and stays out of longs.

Read that gold chart as three states, left to right.

  • The blue EMA 20 crosses up through the orange EMA 50. That single event is ta.crossover(ema20, ema50), and the green triangle is where the script printed the signal.
  • While EMA 20 stays above EMA 50, the fast average leads, so the script treats the market as trending up.
  • When EMA 20 drops back below EMA 50, the regime flips bearish and a long-only script simply does nothing.

That is the whole appeal. You wrote the rule once, and the script watches every bar for you, on every market, without you staring at the screen.

What TradingView Pine Script is, and why chart traders use it

Most trading languages assume you are a developer. Pine Script assumes you are a trader who wants a custom tool by tonight.

It is built around the chart. A script runs once per bar, reads the values on that bar, and draws or signals from them.

  • It lives inside TradingView. No install, no server, no separate app. You open the Pine Editor tab at the bottom of any chart and write there.
  • It is free to start. The free plan lets you write, save, and run scripts on your charts, with paid tiers adding more alerts and history.
  • The syntax is small. A handful of keywords, a big library of built-in functions, and trading words like close, high and volume baked in.
  • It ports across markets. The same script runs on gold, a Forex pair, a stock or Bitcoin, because it only reads price and volume.

The one-line version: if you can say the rule out loud, Pine Script is usually a short hop from there to a working alert.

What you can actually build with it

Pine Script covers three jobs. Most traders start with the first and rarely need the third.

The three things Pine Script is used for
Build typeWhat it doesBest for
Custom indicatorPlots a line or shape on the chartSeeing your own signal live
Alert scriptPings your phone when the rule firesTrading without watching
Strategy backtestSimulates the rule over past barsSanity-checking an idea

The line between them is one keyword, covered further down. For the wider picture of rules-based and automated systems, the algorithmic trading guide sets the context this fits into.

How a Pine Script is put together

Every v5 script has the same four parts, in the same order. Learn these once and you can read most scripts you find online.

The four parts of a Pine Script v5 file
PartWhat it isExample
Version tagTells TradingView which Pine version//@version=5
DeclarationNames it, sets indicator or strategyindicator("My Signal")
InputsSettings you can change in the panelinput.int(20, "EMA length")
Logic and plotThe rules, then what to draw or fireta.ema(close, 20), plot()

A few plain notes on that table:

  • The version tag is not optional. Leave off //@version=5 and the editor guesses an old version, which changes how functions behave.
  • indicator() versus strategy() is the single choice that decides whether the script plots or backtests. More on that below.
  • Inputs are what make a script reusable. Instead of hard-coding 20, an input.int puts a box in the settings so you change the length without editing code.
  • ta. is the built-in library. ta.ema, ta.rsi, ta.macd and dozens more do the maths, so you never build an indicator from scratch.

The built-ins you will use most

You do not memorise these. You reach for them and check the exact spelling in the editor, which auto-completes as you type.

A starter cheat sheet of ta. functions
FunctionWhat it returnsTypical use
ta.ema(close, 20)An exponential moving averageTrend direction
ta.sma(close, 50)A simple moving averageSlower trend line
ta.rsi(close, 14)The RSI, 0 to 100Overbought and oversold
ta.macd(close, 12, 26, 9)MACD, signal, histogramMomentum shifts
ta.crossover(a, b)True the bar a crosses above bBuy triggers
ta.crossunder(a, b)True the bar a crosses below bSell and exit triggers
ta.highest(high, 20)The highest high in 20 barsBreakout levels

The two crossover functions matter most. They turn a vague “when the lines cross” into an exact, single bar the script can act on.

Build one in twenty lines

Pine Script for beginners really comes down to this next block. Here is a complete, working Pine Script indicator.

It plots two moving averages and marks a long signal when the fast one crosses up, but only while momentum agrees.

//@version=5
indicator("EMA cross with RSI filter", overlay=true)

fastLen = input.int(20, "Fast EMA")
slowLen = input.int(50, "Slow EMA")
rsiLen  = input.int(14, "RSI length")

emaFast = ta.ema(close, fastLen)
emaSlow = ta.ema(close, slowLen)
rsi     = ta.rsi(close, rsiLen)

plot(emaFast, "Fast EMA", color=color.blue)
plot(emaSlow, "Slow EMA", color=color.orange)

longSignal = ta.crossover(emaFast, emaSlow) and rsi > 50

plotshape(longSignal, "Long", shape.triangleup, location.belowbar, color.green, size=size.small)
alertcondition(longSignal, "Long alert", "Long setup on {{ticker}}")

Read it block by block, and the jargon melts away.

  1. The version and declaration name the script and set overlay=true so it draws on price, not in a panel below.
  2. The three inputs give you settings boxes for the two EMA lengths and the RSI length.
  3. The ta. lines compute the fast EMA, the slow EMA and the RSI on every bar.
  4. The two plot lines draw the blue and orange averages you saw on the gold chart.
  5. The longSignal line is the whole idea: a fresh cross up, filtered so it only counts when RSI is above the midline.
  6. plotshape and alertcondition draw the green triangle and let you attach a phone alert to the exact event.

The takeaway: the rule is one readable line. Everything around it is just wiring the inputs, the maths and the output.

Indicator or strategy: the one keyword that changes everything

Swap indicator() for strategy() and the same rules stop drawing and start simulating trades over history. That is how a Pine Script strategy backtests itself.

indicator() versus strategy()
Featureindicator()strategy()
Main jobPlot and alert liveSimulate trades on past bars
Entries and exitsYou trade manuallystrategy.entry, strategy.close
OutputLines, shapes, alertsA Strategy Tester report
CostsNot modelledCommission and slippage settings

The strategy version of the same idea is short:

//@version=5
strategy("EMA cross test", overlay=true, commission_type=strategy.commission.percent, commission_value=0.05, slippage=2)

emaFast = ta.ema(close, 20)
emaSlow = ta.ema(close, 50)

if ta.crossover(emaFast, emaSlow)
    strategy.entry("Long", strategy.long)
if ta.crossunder(emaFast, emaSlow)
    strategy.close("Long")

Two honest cautions on the Strategy Tester, because this is where beginners fool themselves.

  • Set commission and slippage. The two settings above tell the tester to charge a fee and assume you fill a couple of ticks worse than the ideal price. Leave them at zero and every result flatters you.
  • A pretty backtest is not an edge. A rule tuned to look perfect on old bars often falls apart on new ones. The backtesting guide covers why, and how to test honestly.

Pine Script makes it trivial to run a test. It does not make the result trustworthy, and those are very different things.

Two more built-ins worth scripting

The crossover on the gold chart is one built-in. Two others cover most of what retail traders script, and each reads best on a different market and speed.

MACD momentum with ta.macd()

The ta.macd() function returns three values at once: the MACD line, the signal line and the histogram. Most scripts watch the histogram flip across zero.

MACD in Pine Script on a EUR/USD 4-hour chart, the blue MACD line and orange signal line in the lower panel with a green and red histogram, and a dashed vertical line marking where the histogram crosses above zero for a bullish momentum shift
EUR/USD, 4-hour. In the lower panel the blue line is the MACD line and the orange line is the signal line. The bars are the histogram, the gap between those two lines. The dashed vertical marks where the histogram crosses above zero, a shift toward bullish momentum.

How it looks in a script:

  • [macdLine, signalLine, hist] = ta.macd(close, 12, 26, 9) hands you all three parts in one line.
  • Histogram above zero means the MACD line is above its signal line, so momentum leans up.
  • Histogram crossing zero, as the dashed line marks, is the moment the balance tips, and the usual trigger.
  • A cross while the histogram bars are tiny is weak. The strong shifts come with the bars already growing.

Application table: scripting MACD

Where the ta.macd() histogram earns its keep
RoleHow you use itBest TF and market
Momentum triggerEnter on the zero crossH4 on EUR/USD, GBP/USD
Trend confirmTake signals that match the trendD1 on gold and Bitcoin
Second gaugeConfirm a price break has pushH1 and H4 on Forex majors
AvoidSkip crosses in a flat rangeQuiet mid-week sessions

For the full mechanics of the indicator itself, the MACD indicator guide breaks down the three lines and their settings.

RSI thresholds with ta.rsi()

ta.rsi(close, 14) returns one number between 0 and 100. Scripts act when it crosses a level you set, usually 70 or 30.

RSI in Pine Script on a Bitcoin 4-hour chart, the purple RSI 14 line in the lower panel with a red dashed 70 overbought level and a green dashed 30 oversold level, a red arrow marking where ta.crossunder fires as RSI drops back below 70
Bitcoin (BTC/USDT), 4-hour. The purple line in the lower panel is RSI with a length of 14. The red dashed line is the 70 overbought level, the green dashed line is 30 oversold. The red arrow marks where ta.crossunder(rsi, 70) fires, the bar RSI drops back below 70.

How it looks in a script:

  • overbought = ta.crossunder(rsi, 70) fires the exact bar RSI falls back under 70, not while it merely sits high.
  • The two dashed lines are just numbers you chose. 70 and 30 are the common defaults, and you set them as inputs.
  • A cross under 70 is a momentum-cooling signal, not an automatic short. In a strong uptrend RSI can stay high for a long time.
  • Use the crossunder, not the level. Acting the instant RSI touches 70 fires constantly in a trend, and that is the classic beginner bug.

Application table: scripting RSI

How traders script the ta.rsi() thresholds
RoleHow you use itBest TF and market
Exit cueTrim longs when RSI crosses under 70H4 on Bitcoin, gold
Mean reversionFade a cross up from 30 in a rangeH1 on ranging Forex
FilterOnly take longs while RSI above 50Any market, any TF
AvoidDo not short a strong trend on 70 aloneTrending gold or Bitcoin

The RSI indicator guide covers the settings and why the thresholds are a starting point, not a rule.

Which built-in to reach for

The three functions are not rivals. You pick by what you are trying to catch and how fast you trade.

The three core built-ins at a glance
Built-inCatchesReads best onWeakness
ta.crossoverTrend changesD1 gold, H4 ForexWhipsaws in a range
ta.macdMomentum shiftsH4 Forex, D1 cryptoLags fast reversals
ta.rsiStretched movesH4 crypto, H1 ForexStays pinned in trends

A few rules of thumb from that table:

  • Slower timeframes are kinder to all three. The same script that reads clean on the 4-hour churns out false signals on the 5-minute.
  • Trend tools want trending markets. The moving-average crossover shines on gold’s long legs and drowns in a quiet range.
  • Combine, do not stack blindly. The twenty-line script above pairs a crossover with an RSI filter for a reason: one catches the turn, the other throws out the weak ones.
  • The ADX makes a good regime filter. Add one line to skip signals when a trend gauge reads flat, and most range whipsaws vanish.

Common Pine Script mistakes

Every beginner hits the same handful of traps. None are hard to fix once you know the name.

  • Repainting. A signal that looks perfect on history but moves after the bar closes. Reference confirmed bars, and test with bar-replay before you trust an alert.
  • Using the level instead of the cross. rsi > 70 is true on many bars in a row. ta.crossunder(rsi, 70) is true on exactly one. Use the cross for a clean trigger.
  • Forgetting the version tag. No //@version=5 and functions silently behave like an old version. Always start with it.
  • Plotting on the wrong scale. An indicator with overlay=true draws on price. An oscillator like RSI needs its own panel, so leave overlay off.
  • Off-by-one on entries. A strategy that enters on the same bar it signals can fill at a price you never saw live. Enter on the next bar to stay honest.

The debugging habit: when a script misbehaves, print the value. plot() the number you are testing and watch it against the chart.

Nine times out of ten the bug is obvious once you can see it.

What works: three things to remember

If you keep only three points from this Pine Script tutorial, keep these.

  1. Say the rule, then wire it. The logic is one line. Inputs, maths and plotting are just the wiring around it.
  2. One keyword splits plotting from testing. indicator() draws and alerts. strategy() backtests, but only trust it with fees and slippage switched on.
  3. The built-ins do the heavy lifting. ta.crossover, ta.macd and ta.rsi cover most retail ideas, so start there before writing anything from scratch.

Pine Script will not hand you an edge. What it hands you is speed: an idea becomes a live alert in an evening, and a bad idea gets exposed just as fast.

For traders who would rather test a claim than argue about it, that is the whole point. From here, the same logic scales up into automated systems once a rule has earned your trust.

FAQ

What is TradingView Pine Script, in plain terms?
It is TradingView's built-in coding language for traders. You use it to build your own indicators, to fire alerts when a rule triggers, or to backtest an idea over past bars. A script reads price and volume, runs your rules on every bar, and then draws a line, marks a shape, or sends an alert. It lives inside the chart, so there is nothing to install.
Is Pine Script hard to learn?
It is one of the easier languages to pick up, because it was made for traders rather than developers. The syntax is small, trading words like close and volume are built in, and a big library of functions does the maths for you. If you can describe a setup in words, you can usually write a first version in a dozen lines. Getting a script truly reliable takes longer, but a basic one is an evening's work.
Do you need to know how to code to use Pine Script?
No prior coding is needed to start. Most traders learn by editing an existing script rather than writing from a blank page. You change an input, swap a built-in function, and watch what happens on the chart. That said, some basic logic helps once you move past simple ideas, because you are still telling a computer exactly what to do.
How do I write my first Pine Script?
Open any TradingView chart, click the Pine Editor tab at the bottom, and start with the version tag //@version=5 and an indicator() declaration. Add a built-in like ta.ema for a moving average, then a plot() line to draw it. Click Add to chart to see it live. From there you add a rule with ta.crossover and a plotshape to mark the signal. Editing a working example is faster than starting blank.
Can you backtest a strategy in Pine Script?
Yes. Change the indicator() declaration to strategy(), add strategy.entry and strategy.close for your entries and exits, and TradingView runs it through the Strategy Tester over past bars. The key is to set commission and slippage so the test charges realistic costs. A backtest with zero fees looks far better than anything you could trade, so treat a clean result with suspicion, not excitement.
Is Pine Script free?
The core is free. On a free TradingView plan you can write, save, and run scripts on your charts, and backtest with the Strategy Tester. Paid plans add more active alerts, more historical bars, and more indicators per chart. For learning and for a handful of live alerts, the free tier is enough to do real work.
What is the difference between an indicator and a strategy in Pine Script?
It comes down to one keyword. An indicator() script plots lines and shapes and can fire alerts, but you place the trades yourself. A strategy() script simulates entries and exits over history and produces a Strategy Tester report with a performance summary. You write the indicator version to see a signal live, and the strategy version to sanity-check whether the idea held up on past data.
Which version of Pine Script should I use?
Use version 5 or newer, and always put the version tag at the top of the file. Older scripts you find online may use version 3 or 4, where some functions behave differently and use older names. TradingView can auto-convert many older scripts, but writing fresh code on the current version saves a lot of confusion over function names and syntax.
What are the most useful built-in functions to learn first?
Start with the ta. library, which holds the technical functions. ta.ema and ta.sma give you moving averages, ta.rsi gives you the RSI, and ta.macd returns the MACD line, signal and histogram together. ta.crossover and ta.crossunder detect the exact bar two lines cross, which is how most signals are built. Those five cover a large share of everything retail traders script.
What do the key Pine Script terms mean?
Bar: one candle, the unit a script runs on. Built-in (the ta. library): ready-made functions like ta.rsi that do the maths for you. Input: a setting you can change in the panel without editing code. Overlay: whether the script draws on price or in its own panel below. Repainting: when a signal shifts after the bar closes, which makes it untrustworthy. Strategy Tester: the tool that reports how a strategy() script would have performed on past bars.

🌍 Our recommended brokers

★★★★☆ 4.4
CySEC · ASIC Since 2009 $5
EUR/USD spread 1.6 pips
Min deposit $5

Regulated broker, $30 no-deposit bonus. 1000+ instruments.

Claim Bonus →

74% of retail CFD accounts lose money.

Compare top forex brokers →
★★★★★ 4.6
FCA · CySEC Since 2007 $50
Copy trading ✓ Built-in
Min deposit $50

Trade stocks, crypto and forex. 30M+ users worldwide.

Join eToro →

74% of retail CFD accounts lose money.

Full eToro review →

Reader Reviews

0.0 No reviews yet

Be the first to review this — tell other traders what actually helped, or where it fell short.

Leave a Review

Nina Carr
Nina Carr

Quant Researcher & Systems Builder

Quantitative researcher who builds the automated systems behind Arxum strategy testing. Works in Python and Pine Script, using AI alongside classic backtesting to validate strategies on years of real data.

Strategy AutomationPython & Pine ScriptAI-Assisted BacktestingSystematic Validation