Strategy Basics#

A Strategy is the Pine Script script type used for backtesting trading logic. Unlike indicators, strategies can issue buy and sell orders, and TradingView automatically calculates P&L, win rate, maximum drawdown, and other performance metrics.

Declaring a Strategy#

Replace the first line with strategy():

//@version=6
strategy("Strategy Name", overlay=true, initial_capital=100000, currency=currency.USD)

Common parameters:

ParameterDescriptionDefault
overlayWhether to overlay on the main chartfalse
initial_capitalStarting capital100000
currencyCurrency unitcurrency.USD
default_qty_typeOrder quantity typestrategy.fixed
default_qty_valueDefault order quantity1

Entry and Exit Orders#

strategy.entry — Open a Position#

strategy.entry(id, direction, qty, comment)
ParameterDescription
idOrder ID (custom string, used for subsequent management)
directionstrategy.long (long) or strategy.short (short)
qtyOrder quantity (omit to use the default)
commentComment text displayed on the chart

strategy.exit — Close with Conditions#

strategy.exit(id, from_entry, stop, limit, trail_points, trail_offset, comment)
ParameterDescription
idExit order ID
from_entryCorresponding entry order ID
stopStop-loss price
limitTake-profit price

strategy.close — Close at Market Price#

strategy.close(id, comment)

Immediately closes the position with the specified ID at market price.

strategy.close_all — Close All Positions#

strategy.close_all(comment)

First Strategy: MA Crossover#

//@version=6
strategy("MA Crossover Strategy", overlay=true, initial_capital=100000)

fastLen = input.int(5,  "Fast MA")
slowLen = input.int(20, "Slow MA")

fastMA = ta.sma(close, fastLen)
slowMA = ta.sma(close, slowLen)

plot(fastMA, "Fast MA", color=color.blue)
plot(slowMA, "Slow MA", color=color.orange)

// Golden cross: enter long
if ta.crossover(fastMA, slowMA)
    strategy.entry("Long", strategy.long, comment="Golden Cross")

// Death cross: close long
if ta.crossunder(fastMA, slowMA)
    strategy.close("Long", comment="Death Cross")

Adding Stop-Loss and Take-Profit#

//@version=6
strategy("MA + Stop Loss/Take Profit", overlay=true, initial_capital=100000)

fastLen   = input.int(5,   "Fast MA")
slowLen   = input.int(20,  "Slow MA")
stopPct   = input.float(2.0, "Stop Loss (%)", step=0.5) / 100
targetPct = input.float(4.0, "Take Profit (%)", step=0.5) / 100

fastMA = ta.sma(close, fastLen)
slowMA = ta.sma(close, slowLen)

// Enter on golden cross
if ta.crossover(fastMA, slowMA)
    strategy.entry("Long", strategy.long)

// Calculate stop-loss and take-profit from entry price
if strategy.position_size > 0
    entryPrice = strategy.position_avg_price
    stopPrice  = entryPrice * (1 - stopPct)
    limitPrice = entryPrice * (1 + targetPct)
    strategy.exit("Exit Long", from_entry="Long",
                  stop=stopPrice, limit=limitPrice)

strategy.position_size — Checking the Position#

strategy.position_size returns the current position size:

  • Positive: long position held
  • Negative: short position held
  • 0: no position
// Only enter when there is no existing position (avoid duplicate entries)
if ta.crossover(fastMA, slowMA) and strategy.position_size == 0
    strategy.entry("Long", strategy.long)

Two-Way Trading (Both Long and Short)#

//@version=6
strategy("Two-Way MA Strategy", overlay=true, initial_capital=100000)

fastLen = input.int(5,  "Fast MA")
slowLen = input.int(20, "Slow MA")

fastMA = ta.sma(close, fastLen)
slowMA = ta.sma(close, slowLen)

// Golden cross: enter long (also closes any short)
if ta.crossover(fastMA, slowMA)
    strategy.entry("Long",  strategy.long,  comment="Golden Cross Long")

// Death cross: enter short (also closes any long)
if ta.crossunder(fastMA, slowMA)
    strategy.entry("Short", strategy.short, comment="Death Cross Short")

When a new strategy.entry direction is opposite to the current position, TradingView automatically closes the existing position before opening a new one.

Backtest Report#

After applying a strategy, click the Strategy Tester panel at the bottom of the chart to see:

MetricDescription
Net ProfitTotal profit/loss amount
Total TradesTotal number of complete trades (entries + exits)
Win RatePercentage of profitable trades
Profit FactorTotal gains / total losses
Max DrawdownMaximum loss from peak to trough
Sharpe RatioRisk-adjusted return rate

Comparison with MultiCharts#

Readers with a MultiCharts background can refer to the following comparison:

Pine ScriptPowerLanguage
Entrystrategy.entry("id", strategy.long)Buy("id") next bar at market
Exitstrategy.close("id")Sell("id") next bar at market
Stop-lossstrategy.exit(..., stop=price)SetStopLoss(amount)
Position querystrategy.position_sizeMarketPosition
Backtest reportStrategy Tester panelPerformance Report

Reference#