Skip to main content

Strategy Fundamentals

The strategy() function, all strategy order functions, the Strategy Tester, and understanding every parameter that controls backtest behavior.

The strategy() Declaration

Every PineScript strategy begins with the strategy() declaration instead of indicator(). This single change unlocks the entire Strategy Tester engine: the backtesting simulator, the trade list, the equity curve, and the performance metrics panel. The strategy() function accepts over a dozen parameters that control how the simulator executes your orders, calculates commissions, handles slippage, and manages margin. Getting these parameters right is the difference between a realistic backtest and a fantasy.

pine-strategy() with all key parameters
1//@version=5
2strategy("BTC Momentum System",
3 overlay = true,
4 initial_capital = 10000,
5 default_qty_type = strategy.percent_of_equity,
6 default_qty_value = 100,
7 commission_type = strategy.commission.percent,
8 commission_value = 0.075,
9 slippage = 2,
10 pyramiding = 0,
11 calc_on_every_tick = false,
12 margin_long = 100,
13 margin_short = 100,
14 currency = currency.USD,
15 process_orders_on_close = false)
16
17// Your strategy logic goes here
overlaytrue places the strategy on the price chart (for entries/exits). false places it in a separate pane.
initial_capitalStarting account balance in the specified currency. Set this to match your real trading capital for realistic results. Default is 1,000,000 which inflates results.
default_qty_typestrategy.percent_of_equity (% of current equity), strategy.fixed (fixed units), or strategy.cash (fixed dollar amount). Percent of equity is most realistic for compounding.
default_qty_valueThe value associated with qty_type. With percent_of_equity, 100 means use all available equity. With fixed, it is the number of contracts/coins.
commission_typestrategy.commission.percent (percentage per trade) or strategy.commission.cash_per_contract / cash_per_order. For crypto, use percent.
commission_valueThe commission rate. Binance maker/taker is 0.1%. With BNB discount it is 0.075%. Always include commissions: they destroy marginal strategies.
slippageNumber of ticks of slippage per order. On BTC with tight spreads, 1–2 ticks is realistic. On altcoins like low-cap SOL pairs, use 5–10.
pyramidingMaximum number of entries in the same direction. 0 means one position at a time. Setting this to 3 allows adding to winners up to 3 times.
calc_on_every_tickfalse (default) calculates only on bar close: more realistic. true calculates on every price update: useful for scalping but can cause unrealistic fills in backtests.
margin_long / margin_shortMargin requirement as percentage. 100 means no leverage. 50 means 2x leverage. 10 means 10x. Set to match your actual exchange leverage.
currencyThe base currency for calculations. Use currency.USD, currency.BTC, or currency.NONE. Affects how profit is calculated on cross-currency pairs.
process_orders_on_closeIf true, orders fill at the current bar's close instead of the next bar's open. Keep false for realistic backtesting. You cannot trade at a price you see after the bar closes.

Strategy Order Functions

PineScript provides six core functions for managing orders within a strategy. Understanding when to use each one is critical. The most common mistake beginners make is using strategy.entry() for exits or confusing strategy.close() with strategy.exit().

strategy.entry()Opens a new position or adds to an existing one (if pyramiding > 0). Takes an id string, direction (strategy.long or strategy.short), qty, limit, stop, and comment. If you call entry() with a different direction than your current position, it reverses.
strategy.exit()Places a take-profit and/or stop-loss order attached to a specific entry id. Uses limit (TP), stop (SL), trail_price, trail_offset, and profit/loss in ticks. Does NOT close immediately. It places pending orders.
strategy.close()Immediately closes a position by entry id at market price on the next bar's open. Use this for signal-based exits (e.g., close when RSI crosses above 70).
strategy.close_all()Closes all open positions at market price. Useful for end-of-day flattening or emergency exits.
strategy.cancel()Cancels a pending entry order by its id. If you placed a limit entry that hasn't filled yet, cancel() removes it.
strategy.cancel_all()Cancels all pending orders. Use at the start of new logic blocks to ensure stale orders don't linger.
pine-Order functions in action
1//@version=5
2strategy("Order Functions Demo", overlay=true,
3 initial_capital=10000, default_qty_type=strategy.percent_of_equity,
4 default_qty_value=100, commission_value=0.075)
5
6ema21 = ta.ema(close, 21)
7rsi = ta.rsi(close, 14)
8
9// Entry: go long when price crosses above EMA and RSI confirms
10longCondition = ta.crossover(close, ema21) and rsi > 50
11if longCondition
12 strategy.entry("Long", strategy.long)
13
14// Exit with take-profit and stop-loss
15strategy.exit("TP/SL", "Long",
16 profit = close * 0.03 / syminfo.mintick, // 3% TP in ticks
17 loss = close * 0.015 / syminfo.mintick) // 1.5% SL in ticks
18
19// Signal-based exit: close if RSI becomes overbought
20if rsi > 80
21 strategy.close("Long", comment="RSI exit")
22
23// Short entry: go short when price crosses below EMA
24shortCondition = ta.crossunder(close, ema21) and rsi < 50
25if shortCondition
26 strategy.entry("Short", strategy.short)
27
28strategy.exit("TP/SL Short", "Short",
29 profit = close * 0.03 / syminfo.mintick,
30 loss = close * 0.015 / syminfo.mintick)

Order Types and Direction

Every entry and exit order has a direction and can optionally specify a price for limit or stop execution. By default, orders are market orders. They fill at the open of the next bar. Adding a limit parameter creates a limit order (fills at the specified price or better). Adding a stop parameter creates a stop order (triggers when price reaches the level, then fills at market).

pine-Limit, stop, and stop-limit entries
1//@version=5
2strategy("Order Types", overlay=true, initial_capital=10000)
3
4ema50 = ta.ema(close, 50)
5atr = ta.atr(14)
6
7// MARKET ORDER: fills at next bar open
8if ta.crossover(close, ema50)
9 strategy.entry("Mkt Long", strategy.long)
10
11// LIMIT ORDER: buy at EMA (dip-buy)
12if close > ema50 and close > open
13 strategy.entry("Limit Long", strategy.long,
14 limit = ema50)
15
16// STOP ORDER: buy on breakout above yesterday's high
17if close > ema50
18 strategy.entry("Stop Long", strategy.long,
19 stop = ta.highest(high, 20))
20
21// STOP-LIMIT: trigger at breakout, fill at limit
22if close > ema50
23 strategy.entry("SL Long", strategy.long,
24 stop = ta.highest(high, 20),
25 limit = ta.highest(high, 20) + atr * 0.5)

The Strategy Tester Tab

When you add a strategy to a chart, the "Strategy Tester" tab appears in the bottom panel. This is the backtesting dashboard. It has three main views: the Performance Summary, the List of Trades, and the Equity Curve.

Performance Summary

Shows net profit, gross profit/loss, max drawdown, profit factor, total trades, percent profitable, Sharpe ratio, Sortino ratio, and more. This is your one-stop overview.

List of Trades

Every individual trade with entry/exit dates, prices, profit/loss, cumulative P&L, and the trade duration. Lets you audit specific trades.

Equity Curve

A visual line chart of your account equity over time. Smooth upward curves are good. Jagged cliff-drops reveal dangerous drawdowns.

Buy & Hold Comparison

The equity curve overlays a buy-and-hold benchmark so you can see if your strategy actually outperforms simply holding BTC.

Drawdown Plot

Visualizes drawdown periods: how deep they go and how long recovery takes. Essential for psychological preparedness.

Deep Backtesting

Premium feature that runs the strategy on more historical data than the chart displays, giving more trades and a more reliable sample size.

Backtesting is not live trading

A profitable backtest does not guarantee live profitability. Backtests suffer from look-ahead bias (your strategy may use data it wouldn't have in real time), unrealistic fills (the simulator assumes your limit orders always fill, but in reality they may not), survivorship bias (you're testing on assets that survived. You never see the coins that went to zero), and curve fitting (optimizing parameters to fit past data perfectly, which fails on new data). Always validate with out-of-sample data, paper trading, and small live positions before committing real capital.

Put this lesson to work

Free on Thrive, no account needed.