Backtest a strategy
Entries, stop and target brackets, end-of-day exits, and how to read the report honestly.
Start with strategy("Name") instead of indicator() and the script becomes a backtest. entry(id, long) buys at the next bar’s open; exit(id, from_entry, stop = …, limit = …) adds a stop and a target; close_all() flattens. Fills happen on the chart’s past candles. Nothing is sent to a broker.
strategy("EMA trend", qty = 100, commission = 1)
fast = ema(close, 9)
slow = ema(close, 21)
risk = 1.5 * atr(14)
if crossover(fast, slow) and position_size == 0
entry("Long", long)
exit("Bracket", "Long", stop = close - risk, limit = close + 2 * risk)
if rth and minutes_since_open >= 380
close_all("End of day")
plot(fast, "Fast", color = amber)
plot(slow, "Slow", color = violet)- Fills: market orders fill at the next open; stops and targets fill when a bar trades through them, nearer extreme first.
- Costs: set commission and slippage. A strategy that only works without them doesn’t work.
- Sample size: a handful of trades on one symbol proves very little. Test many symbols, timeframes and months.
Key takeaways
- strategy() + entry/exit/close_all = a backtest.
- Market orders fill at the next open.
- Include costs and test widely before trusting a result.