Pine Script Strategy Tutorial: Write Your First TradingView Strategy (v6)
Pine Script is the language TradingView uses for indicators and strategies. A strategy is a script that places simulated trades, so TradingView can show you its profit, drawdown and every trade in the Strategy Tester. This tutorial writes a complete strategy in Pine Script version 6, explains each line, and shows how to make the backtest realistic.
Indicator vs strategy
- An
indicator()draws on the chart and can send alerts, but it does not place trades. - A
strategy()places simulated orders withstrategy.entry,strategy.exitandstrategy.close, and produces a backtest report.
Your first strategy
Open the Pine Editor at the bottom of a TradingView chart, start a new strategy, and replace the code with this:
//@version=6
strategy("EMA cross with stop and target", overlay = true,
initial_capital = 10000,
default_qty_type = strategy.percent_of_equity, default_qty_value = 10,
commission_type = strategy.commission.percent, commission_value = 0.05,
slippage = 2)
fastLen = input.int(9, "Fast EMA")
slowLen = input.int(21, "Slow EMA")
stopPct = input.float(1.0, "Stop loss %") / 100
takePct = input.float(2.0, "Take profit %") / 100
fast = ta.ema(close, fastLen)
slow = ta.ema(close, slowLen)
plot(fast, "Fast", color.teal)
plot(slow, "Slow", color.orange)
if ta.crossover(fast, slow)
strategy.entry("Long", strategy.long)
if ta.crossunder(fast, slow)
strategy.entry("Short", strategy.short)
if strategy.position_size > 0
entry = strategy.position_avg_price
strategy.exit("Long exit", "Long", stop = entry * (1 - stopPct), limit = entry * (1 + takePct))
if strategy.position_size < 0
entry = strategy.position_avg_price
strategy.exit("Short exit", "Short", stop = entry * (1 + stopPct), limit = entry * (1 - takePct))
Click Add to chart, then open the Strategy Tester tab to see the results.
What each part does
//@version=6tells TradingView which Pine version to use. Always put it first.strategy(...)sets the name, the starting capital, the position size (10% of equity here), and commission and slippage so the results are closer to real trading.input.intandinput.floatcreate settings you can change from the chart without editing code.ta.emacalculates the moving averages, andta.crossoveris true on the bar where the fast line crosses above the slow one.strategy.entryopens a position. Entering short while long reverses the position.strategy.exitattaches a stop loss and take profit to the open position, calculated from the average entry price.
Make the backtest honest
- Always set commission and slippage. A strategy that only works without costs doesn't work.
- Use enough history. Look at hundreds of trades, not twenty.
- Avoid lookahead. When you use
request.security()for higher timeframe data, use the value of the previous closed bar, or the backtest can see the future. - Watch out for repainting. Signals that appear and then disappear on live bars make backtests look better than live trading.
- Bar magnifier. On plans that support it,
use_bar_magnifier = trueinstrategy()fills stops and targets more accurately inside each bar. - Don't over-optimise. If changing an input from 9 to 10 destroys the results, the strategy is fitted to the past.
Reading the Strategy Tester
- Net profit and max drawdown together: a big profit with an even bigger drawdown is hard to trade.
- Profit factor: gross profit divided by gross loss. Above 1 means it made money in the test.
- Number of trades: too few and the result may be luck.
- List of trades: check entries on the chart to be sure the logic does what you meant.
From strategy to live trading
A Pine Script strategy only simulates trades. To trade for real you have two options:
- Alerts and webhooks: add an alert on the strategy and send each order to a server that places it with your broker. See our TradingView webhook JSON guide.
- Convert the code: rewrite the strategy as an MT5 Expert Advisor or a Python bot so it runs without TradingView.
Frequently asked questions
Is Pine Script hard to learn?
It is one of the easier trading languages. Simple strategies take only a few lines, and the built-in ta.* functions cover most indicators.
Can Pine Script place real trades?
Not by itself. It sends alerts, and a broker integration or webhook server turns them into real orders.
What is the difference between Pine Script v5 and v6?
Version 6 tightens some type rules and changes a few behaviours, such as how boolean values work. TradingView's editor can convert most v5 scripts automatically.
Why are my live results different from the backtest?
Usually costs, slippage, repainting signals or fills inside the bar. Fix those in the backtest first.
Need a strategy coded or automated?
We write Pine Script strategies, connect them to brokers, and convert them to MT5 or Python. See Pine Script to MQL5 conversion and TradingView to IBKR automation.