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:
| Parameter | Description | Default |
|---|---|---|
overlay | Whether to overlay on the main chart | false |
initial_capital | Starting capital | 100000 |
currency | Currency unit | currency.USD |
default_qty_type | Order quantity type | strategy.fixed |
default_qty_value | Default order quantity | 1 |
Entry and Exit Orders#
strategy.entry — Open a Position#
strategy.entry(id, direction, qty, comment)| Parameter | Description |
|---|---|
id | Order ID (custom string, used for subsequent management) |
direction | strategy.long (long) or strategy.short (short) |
qty | Order quantity (omit to use the default) |
comment | Comment text displayed on the chart |
strategy.exit — Close with Conditions#
strategy.exit(id, from_entry, stop, limit, trail_points, trail_offset, comment)| Parameter | Description |
|---|---|
id | Exit order ID |
from_entry | Corresponding entry order ID |
stop | Stop-loss price |
limit | Take-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.entrydirection 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:
| Metric | Description |
|---|---|
| Net Profit | Total profit/loss amount |
| Total Trades | Total number of complete trades (entries + exits) |
| Win Rate | Percentage of profitable trades |
| Profit Factor | Total gains / total losses |
| Max Drawdown | Maximum loss from peak to trough |
| Sharpe Ratio | Risk-adjusted return rate |
Comparison with MultiCharts#
Readers with a MultiCharts background can refer to the following comparison:
| Pine Script | PowerLanguage | |
|---|---|---|
| Entry | strategy.entry("id", strategy.long) | Buy("id") next bar at market |
| Exit | strategy.close("id") | Sell("id") next bar at market |
| Stop-loss | strategy.exit(..., stop=price) | SetStopLoss(amount) |
| Position query | strategy.position_size | MarketPosition |
| Backtest report | Strategy Tester panel | Performance Report |