⬡ TECHNICAL TUTORIAL · WITH CODE · 13 MIN READ

Pine Script from scratch: indicators and strategies on TradingView.

The most accessible language for anyone who wants to code trading. We go from your first indicator to a full strategy with backtesting and alerts for automation — all inside TradingView, with nothing to install.

By the RoboTraderIA team· updated May 2026· beginner level

If Python is the way into exchange bots, Pine Script is the way into chart automation. It's TradingView's native language, designed specifically for technical analysis, and it has a huge advantage for beginners: you code, plot and backtest on the same screen, with nothing to install. This tutorial uses the current version, Pine Script v5.

01What Pine Script is (and why to start with it)

Pine Script is a scripting language created by TradingView for two purposes: building custom indicators (which plot on the chart) and building strategies (which generate buy/sell signals and can be tested on historical data). It's simple, purpose-built and runs in TradingView's cloud — you don't need a server or an install.

Why it's great for learning: the write→plot→test cycle is instant and visual. You see the result on the chart right away. Compared to building a whole data pipeline in Python, it's much faster for validating a strategy idea.

02Your first indicator

In TradingView, open the Pine Editor (the tab at the bottom of the chart). Every script starts by declaring the version and the type. Let's plot a simple moving average:

//@version=5
indicator("Minha Primeira MM", overlay=true)

// input: makes the period adjustable from the interface
periodo = input.int(20, "Período da Média")

// calculates the simple moving average of the close
media = ta.sma(close, periodo)

// plots it on the chart
plot(media, "MM", color=color.aqua, linewidth=2)

Click Add to chart. Done — your average appears over the candles. The overlay=true is what makes the indicator draw over price (instead of in a separate panel below).

03The concepts you need to understand

The time series

In Pine, variables like close, open, high, low aren't a single number — they're series. The script runs once for every candle on the chart, and close always refers to the close of the current candle on that pass. To access earlier candles, use brackets: close[1] is the previous candle's close, close[2] the close from two candles back.

Functions from the ta library

The ta (technical analysis) library has everything built in: ta.sma() (simple moving average), ta.ema() (exponential), ta.rsi(), ta.macd(), ta.crossover() (cross above), ta.crossunder() (cross below). You rarely need to calculate an indicator by hand.

04From indicator to strategy

The crucial difference: indicator() only draws; strategy() simulates trades and generates a backtest report. Let's turn the moving average into a crossover system that actually trades:

//@version=5
strategy("Cruzamento de Médias", overlay=true,
         initial_capital=10000, default_qty_type=strategy.percent_of_equity,
         default_qty_value=10)

// adjustable parameters
rapida = input.int(9,  "MM Rápida")
lenta  = input.int(21, "MM Lenta")

ma_rapida = ta.ema(close, rapida)
ma_lenta  = ta.ema(close, lenta)

// detects the crossovers
cruzaCima  = ta.crossover(ma_rapida, ma_lenta)
cruzaBaixo = ta.crossunder(ma_rapida, ma_lenta)

// trading rules
if cruzaCima
    strategy.entry("Compra", strategy.long)
if cruzaBaixo
    strategy.close("Compra")

// plot the moving averages
plot(ma_rapida, "Rápida", color=color.lime)
plot(ma_lenta,  "Lenta",  color=color.orange)

When you add it to the chart, TradingView automatically opens the Strategy Tester below — with net profit, number of trades, win rate, maximum drawdown and the equity curve. You just ran a backtest without writing a single line of testing code.

Want ready-made strategies to adapt?

See our collection of classic strategies with the logic explained — ready to be turned into code.

See strategies →

05Adding stop loss and take profit

A strategy without risk management is incomplete. In Pine, you define the stop and the target at the moment of entry:

// inside the entry block
if cruzaCima
    strategy.entry("Compra", strategy.long)
    // stop 2% below, target 4% above (risk:reward 1:2)
    strategy.exit("Saida", "Compra",
                   stop  = close * 0.98,
                   limit = close * 1.04)

Tip: the Strategy Tester recalculates everything when you change those values. Use it to see how different stop/target levels affect the result — but watch out for overfitting (over-optimizing to the past).

06Alerts: the bridge to automation

Pine Script runs on TradingView and does not place orders at your broker on its own. The bridge to automation is alerts. You add an alert in the code, and when the condition fires, TradingView can send a webhook (an HTTP request) to a server that executes the order at the broker.

// fires an alert on the crossover
if cruzaCima
    alert("COMPRA BTCUSDT", alert.freq_once_per_bar_close)
if cruzaBaixo
    alert("VENDA BTCUSDT", alert.freq_once_per_bar_close)

Two ways to turn the alert into a real order: (1) native integration — brokers that support TradingView (such as Pepperstone) execute straight from the chart; (2) webhook + server — the alert calls your server (e.g. a Python script that receives the webhook and sends the order via API, as we show in the Binance tutorial).

Heads up: webhook automation adds points of failure (the server goes down, the request is lost, latency). For time-sensitive strategies, the broker's native integration is more reliable. Test exhaustively on a demo account before automating with real money.

07Next steps to master it

  • Study the whole ta library — RSI, MACD, Bollinger, ATR. Each one opens up new strategies.
  • Learn arrays and var to keep state between candles (e.g. tracking a support level).
  • Detect SMC patterns — order blocks and fair value gaps can be coded in Pine (see our Smart Money Concepts guide).
  • Read the official Pine v5 manual — it's the best reference and has examples for everything.

08Frequently asked questions

What is Pine Script?

It's TradingView's programming language, for building custom indicators and strategies with backtesting right inside the platform. It runs in the cloud — nothing to install.

Is Pine Script hard?

No. It's simple and purpose-built for chart analysis. Anyone who has coded before picks it up in hours; beginners get the basics in a few days. The visual write→plot→test cycle speeds up learning a lot.

Can you actually trade with Pine Script?

Pine generates signals and alerts. To place real orders automatically, you connect the alerts to a webhook (which sends the order to the broker via API) or use the native integration of brokers that support TradingView.

Pine Script or Python for automation?

Pine is better for prototyping and fast visual backtesting. Python gives full control and runs independently of TradingView, ideal for robust execution. Many people use Pine to design the strategy and Python to run it.

Do I have to pay for TradingView to use Pine?

The free plan lets you create and test scripts with limits (number of simultaneous indicators, alerts). For serious automation with several alerts, the paid plans unlock more resources.

Read next

🎁 Get the free trading bot (with Quotex, Deriv and IQ Option APIs)

Open source bot + ready-made API code. You edit it by chatting with ChatGPT/Claude — no programming. Free, no spam.

👉 Want the ready-made bot? Go to botbinaryoptions.com →