Pine ScriptApr 7, 20269 min read

Pine Script Strategy: The Complete 2025 Guide to Writing TradingView Strategies

Learn how to write a Pine Script strategy from scratch — entries, exits, stop losses, position sizing, and backtesting — with step-by-step explanations for beginners and intermediate traders.

What Is Pine Script and Why Does It Matter?

Pine Script is TradingView's built-in scripting language. It lets you define custom indicators, strategies, and alerts that run directly on TradingView charts — without any external software, brokerage account, or Python knowledge required.

As of 2025, Pine Script v6 is the current version. It brings significant improvements over v4/v5, including cleaner function namespaces, better type safety, and first-class support for multi-timeframe (MTF) analysis.

The key difference between a Pine Script indicator and a Pine Script strategy is that a strategy can simulate trades and report backtest statistics like net profit, drawdown, Sharpe ratio, and win rate — directly inside TradingView's Strategy Tester.

The strategy() Declaration — Your Starting Point

Every Pine Script strategy begins with a strategy() call. This sets up your script's metadata and tells TradingView how to calculate performance metrics.

//@version=6
strategy(
  title            = "My EMA Strategy",
  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
)
  • overlay = true — draws on the price chart (not a separate pane)
  • initial_capital — starting balance for backtesting (USD)
  • default_qty_type — how position size is calculated (percent of equity, fixed lots, etc.)
  • commission_value — realistic brokerage fee to simulate real-world performance

Defining Entry and Exit Rules

A strategy needs at minimum one entry signal and one exit signal. The most common pattern uses a crossover between two moving averages to determine trend direction.

fastEma = ta.ema(close, 9)
slowEma = ta.ema(close, 21)

longEntry  = ta.crossover(fastEma, slowEma)
shortEntry = ta.crossunder(fastEma, slowEma)

strategy.entry("Long",  strategy.long,  when = longEntry)
strategy.entry("Short", strategy.short, when = shortEntry)

Tip

Always use ta.crossover() and ta.crossunder() for crossover detection. Never compare values with > or < to detect crosses — that fires on every bar, not just the crossing bar.

Stop Losses and Take Profits

Risk management is the most important part of any strategy. Pine Script supports ATR-based stops, fixed-point stops, and percentage stops — all set via strategy.exit().

atrVal  = ta.atr(14)
stopDist = atrVal * 1.5
tpDist   = atrVal * 3.0

strategy.exit(
  id        = "Long Exit",
  from_entry = "Long",
  stop      = strategy.position_avg_price - stopDist,
  limit     = strategy.position_avg_price + tpDist
)

Tip

ATR-based stops adapt to market volatility. A 1.5× ATR stop is tight enough to protect capital but loose enough to avoid noise-triggered exits.

Backtesting Your Strategy on TradingView

Once your strategy is written, click the 'Strategy Tester' tab at the bottom of TradingView. You'll see a full performance report including net profit, max drawdown, total trades, win rate, and profit factor.

A strategy worth trading typically shows: profit factor > 1.5, win rate > 45%, max drawdown < 20%, and at least 100 trades in the backtest window.

Change the chart timeframe and symbol to stress-test across different market conditions. A strategy that only works on one specific chart is likely curve-fitted.

Tip

Run your strategy on out-of-sample data — if you optimized parameters on 2020-2023, test the result on 2023-2025 data without any further adjustments.

Use AI to Write Pine Script Strategies Faster

Writing Pine Script manually has a steep learning curve. TradePilot is an AI tool that generates complete, compilable Pine Script v6 strategies from plain English descriptions — including proper stop losses, take profits, alerts, and backtesting setup.

Instead of spending hours debugging syntax errors, you describe your strategy idea and receive working code in seconds. TradePilot's Apex Pro model asks clarifying questions about your timeframe, risk style, and entry logic before generating — so the output fits your exact requirements.

TP

TradePilot Team

Traders and engineers building the fastest way to go from idea to live Pine Script strategy, right inside TradingView.

More articles

Ready to elevate your trading?

Join thousands of traders using TradePilot.co.in to generate profitable Pine Script strategies.

No credit card required30 free credits (~6 strategies)Works inside TradingViewCancel anytime