Skip to main content
On this page

Pine Script Tutorial: Your First Indicator and Strategy

· 5 min read
Pineify Team
Pine Script and AI trading workflow research team

This Pine Script tutorial builds a moving-average indicator, then shows what changes when you want simulated trades. The examples teach inputs, plots, conditions, and order timing. Their parameters are learning choices, not tested trading recommendations.

Open Pine Editor​

On a TradingView Superchart, click the Pine icon on the right toolbar. Create a new indicator from the script menu, replace its contents with the first example, save, and add it to the chart. The editor can float, dock, or move to the bottom; TradingView's current editor guide describes these layouts.

The editor is a browser interface, but Pine calculations run in TradingView's execution environment. You do not install a local Pine runtime for this tutorial. Account limits and market-data access still apply.

Write a moving-average indicator​

//@version=6
indicator("First Moving Average", overlay=true)
length = input.int(14, "Length", minval=1)
average = ta.sma(close, length)
plot(close, "Close", color=color.new(color.gray, 70))
plot(average, "Simple moving average", color=color.blue, linewidth=2)

The version annotation selects Pine v6. indicator() declares the script type; overlay=true places the plots with price. input.int() creates an editable whole-number setting and prevents a nonpositive length. ta.sma() calculates the simple moving average, while plot() displays a series.

A length of 14 means chart bars. On a five-minute chart it uses five-minute bars; on a daily chart it uses daily bars. Change the input, observe the line, and compare it with TradingView's built-in moving average using the same settings. A shorter length responds to recent changes differently; it is not automatically a better signal.

The first bars may have no average until sufficient data exists. On an open bar, close is the latest available price and can change. Indicators normally recalculate on realtime updates, whereas historical bars are processed using their available final values. Read the execution model when a signal behaves differently before and after a bar closes.

Create a separate strategy​

Use a new strategy script for this second example. Do not paste it below the indicator: a script needs one declaration. This long-only example buys after a fast average crosses above a slow one and closes after the reverse crossing.

//@version=6
strategy("Learning MA Crossover", overlay=true, initial_capital=10000, default_qty_type=strategy.fixed, default_qty_value=1, pyramiding=0, commission_type=strategy.commission.percent, commission_value=0.1, slippage=1)
fastLength = input.int(9, "Fast length", minval=1)
slowLength = input.int(21, "Slow length", minval=2)
if fastLength >= slowLength
runtime.error("Fast length must be less than slow length.")
fast = ta.sma(close, fastLength)
slow = ta.sma(close, slowLength)
enterLong = ta.crossover(fast, slow)
exitLong = ta.crossunder(fast, slow)
if enterLong
strategy.entry("Long", strategy.long)
if exitLong
strategy.close("Long")
plot(fast, "Fast average", color=color.green)
plot(slow, "Slow average", color=color.red)

The declaration explicitly uses one unit per entry, no pyramiding, an illustrative 0.1% commission, and one tick of slippage. These assumptions are not a claim about your broker or instrument. The example has no independent stop-loss or take-profit order; it waits for the opposite crossing to request a close.

With the default strategy calculation and order-processing settings used here, a historical signal is evaluated at bar close and a market order normally fills on the next available tick, often the next bar's open. A crossover marker and an order fill therefore need not appear on the same candle. Strategy orders are simulated, as explained in TradingView's strategy documentation.

Read the test before judging the idea​

First inspect whether the strategy follows the rule. Find one upward crossing, one downward crossing, and a stretch where the averages do not cross. Compare those bars with the trade list. Check order size and costs in the strategy settings, since saved settings can affect a test.

Then record the symbol, date range, chart type, timeframe, and settings alongside any report. Net profit, drawdown, trade count, and win rate describe different aspects of that simulation. A single ratio or threshold is not enough to decide whether a strategy is suitable. Standard candles are a clearer starting point than synthetic chart prices for learning fill behavior.

This tutorial reports no investment results. Testing a rule on history is useful for finding implementation mistakes and examining assumptions; it cannot establish future returns.

Fix errors in a controlled order​

Read the first compiler diagnostic and its line number. Check punctuation, function names, argument types, and indentation before changing the trading rule. Save a working copy before extending it, and add one feature at a time so that a new problem has a smaller search area.

A script that compiles can still produce missing values or a runtime error. A script that plots correctly may still express the wrong condition. Keep these checks separate: syntax, chart behavior, and strategy results.

For the next exercise, add an input or change a plot color before introducing multi-timeframe data or alerts. TradingView's first indicator tutorial and language manual provide the next reference points.