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.
1//@version=52strategy("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)1617// Your strategy logic goes here| overlay | true places the strategy on the price chart (for entries/exits). false places it in a separate pane. |
| initial_capital | Starting 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_type | strategy.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_value | The 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_type | strategy.commission.percent (percentage per trade) or strategy.commission.cash_per_contract / cash_per_order. For crypto, use percent. |
| commission_value | The commission rate. Binance maker/taker is 0.1%. With BNB discount it is 0.075%. Always include commissions: they destroy marginal strategies. |
| slippage | Number 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. |
| pyramiding | Maximum 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_tick | false (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_short | Margin requirement as percentage. 100 means no leverage. 50 means 2x leverage. 10 means 10x. Set to match your actual exchange leverage. |
| currency | The base currency for calculations. Use currency.USD, currency.BTC, or currency.NONE. Affects how profit is calculated on cross-currency pairs. |
| process_orders_on_close | If 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. |
1//@version=52strategy("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)56ema21 = ta.ema(close, 21)7rsi = ta.rsi(close, 14)89// Entry: go long when price crosses above EMA and RSI confirms10longCondition = ta.crossover(close, ema21) and rsi > 5011if longCondition12 strategy.entry("Long", strategy.long)1314// Exit with take-profit and stop-loss15strategy.exit("TP/SL", "Long",16 profit = close * 0.03 / syminfo.mintick, // 3% TP in ticks17 loss = close * 0.015 / syminfo.mintick) // 1.5% SL in ticks1819// Signal-based exit: close if RSI becomes overbought20if rsi > 8021 strategy.close("Long", comment="RSI exit")2223// Short entry: go short when price crosses below EMA24shortCondition = ta.crossunder(close, ema21) and rsi < 5025if shortCondition26 strategy.entry("Short", strategy.short)2728strategy.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).
1//@version=52strategy("Order Types", overlay=true, initial_capital=10000)34ema50 = ta.ema(close, 50)5atr = ta.atr(14)67// MARKET ORDER: fills at next bar open8if ta.crossover(close, ema50)9 strategy.entry("Mkt Long", strategy.long)1011// LIMIT ORDER: buy at EMA (dip-buy)12if close > ema50 and close > open13 strategy.entry("Limit Long", strategy.long,14 limit = ema50)1516// STOP ORDER: buy on breakout above yesterday's high17if close > ema5018 strategy.entry("Stop Long", strategy.long,19 stop = ta.highest(high, 20))2021// STOP-LIMIT: trigger at breakout, fill at limit22if close > ema5023 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.
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.
Every individual trade with entry/exit dates, prices, profit/loss, cumulative P&L, and the trade duration. Lets you audit specific trades.
A visual line chart of your account equity over time. Smooth upward curves are good. Jagged cliff-drops reveal dangerous drawdowns.
The equity curve overlays a buy-and-hold benchmark so you can see if your strategy actually outperforms simply holding BTC.
Visualizes drawdown periods: how deep they go and how long recovery takes. Essential for psychological preparedness.
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
Put this lesson to work
Free on Thrive, no account needed.