Backtest Template [Backtest Terminal] — Strategy by BacktestTerminal
By BacktestTerminal
Performance Metrics
- Author: BacktestTerminal
- Symbol: EIGHTCAP:XAUUSD
- Timeframe: 1 minute
- Net P&L: +324.83 USD (+3.25%)
- Win Rate: 51.9%
- Profit Factor: 1.334
- Max Drawdown: 56.37 USD (0.55%)
- Total Trades: 397
Description
Overview — What Is This Script?Backtest Template (BTT) is an open-source strategy framework designed to let traders test their own indicator logic without building the backtest infrastructure from scratch. Instead of writing stop loss management, session filters, alert systems, and trailing stops yourself, BTT handles all of that automatically. You bring your signal idea — BTT handles the rest.The template is designed for all markets: stocks, Forex, gold (XAUUSD), crypto spot, and crypto futures. It ships with a pre-built Moving Average Cross trigger and Moving Average Trend filter as working examples that you replace with your own logic.What Makes It OriginalMost backtest templates on TradingView are fixed strategies that test one specific indicator. BTT introduces a User Zone architecture: a single clearly marked section near the top of the script where the user replaces one pre-built trigger and one pre-built filter with their own Pine Script code. The engine below reads four fixed variable names and runs automatically — the user never needs to touch strategy orders, stop management, session logic, or the alert system.This design means a complete beginner can run their first backtest by changing fewer than ten lines of code, while an advanced user can plug in arrays, multi-timeframe calculations, or complex signal logic and the engine handles it identically.What The Engine Handles AutomaticallyOnce your signal is connected through the User Zone, the following run without any additional code: Stop Loss and Take Profit — three unit modes: percentage of price, fixed points (Forex / CFD), or fixed dollar amount (crypto / stocks) Stop Mode — Fixed (original level), Trailing (follows price), or Breakeven (moves to entry price) Trailing Stop — configurable distance and activation offset, each with matching %, point, and dollar unit inputs consistent with your Stop/Target Mode selection Breakeven Stop — configurable activation offset in the same unit system Disable Take Profit — when using Trailing mode, an optional toggle removes the fixed TP so the trailing stop becomes the sole exit Trade Direction — Long only, Short only, or Both Backtest Date Range — start and end date inputs Trading Day Filter — enable or disable any day of the week Trade Session Hours — exchange server time filter (HHMM-HHMM format) Trade Windows — four configurable local-time windows each independently set to Off, Blackout, or Trade Only mode with full timezone support Entry Signal Markers — green and red triangles that only appear when all conditions pass, so chart visuals exactly match what the strategy trades App Alerts — pre-formatted alert messages with ticker, direction, stop and target prices Custom JSON Alerts — four separate input fields for webhook bot integration, one per order eventHow To Use It — Quick Start Open the script in Pine Editor Find the User Zone near the top — it is clearly marked with a visual border and is the only section you need to edit Replace the pre-built Moving Average Cross trigger block with your own indicator signal, assigning your long condition to userLong and your short condition to userShort — always add and confirmed to both Replace the pre-built Moving Average Trend filter block with your own market condition, assigning to userFilterLong and userFilterShort Add to chart and open Strategy TesterUser Zone ContractThe engine connects to your signal through exactly four variables. Do not rename them: userLong → true on the bar you want to enter Long userShort → true on the bar you want to enter Short userFilterLong → true when Long entries are allowed userFilterShort → true when Short entries are allowed Always add and confirmed (barstate.isconfirmed) to userLong and userShort. This ensures the signal locks in only when the bar closes, preventing signals from changing value mid-bar. Setting userFilterLong = true disables the Long filter entirely. Setting it to a condition like close > ta.ema(close, 200) means Long entries are only allowed when price is above that EMA. Long and Short filters are independent — you can filter one direction while leaving the other open.Stop Loss and Take Profit — Three Unit ModesThe Stop/Target Mode setting controls how SL and TP distances are measured: % (Percentage) — distance as a percentage of price. Suitable for stocks and crypto. Stop source can be the close price or the candle High/Low. Take profit is derived from stop distance × Risk:Reward ratio. Point - Forex / CFD — distance in instrument ticks (syminfo.mintick). Suitable for XAUUSD, EURUSD, and other Forex/CFD instruments. Example: 100 points on EURUSD (mintick = 0.00001) = 1 pip. Dollar - Crypto / Stock — fixed dollar distance from entry. Suitable for BTCUSD and US stocks.All trailing and breakeven offset inputs follow the same three-unit system. Use the [%], [P], or [$] input that matches your selected Stop/Target Mode. Using the wrong unit input will result in a mismatch between your intended stop distance and the actual calculation.Stop Mode — Fixed, Trailing, Breakeven Fixed — stop loss stays at the original level from entry until hit or TP is reached Trailing — stop follows price at a configurable distance, locking in profit as price moves. The trailing activation offset controls how far price must move before trailing begins (shown as a yellow line on chart). Enable "Disable Take Profit" to let the trailing stop manage the entire exit without a fixed TP ceiling Breakeven — stop moves to the exact entry price once price moves a configurable distance in your favour (shown as a white line on chart)Trade Windows — Off, Blackout, Trade OnlyEach of the four time windows (Tokyo, London, New York, Custom) has an independent mode selector: Off — this window has no effect on entries (default for all four) Blackout — block all new entries while the current time is inside this window. Useful for avoiding high-volatility opens or news events Trade Only — only allow new entries while the current time is inside this window. Useful for targeting specific sessions or news event windows such as NFP or Fed announcementsAll times are entered in your local timezone selected from the My Timezone dropdown. The engine converts to UTC internally.Logic rules: Multiple Blackout windows use AND NOT logic — entries are blocked if the current time is inside any Blackout window Multiple Trade Only windows use OR logic — entries are allowed when the current time is inside any one Trade Only window If no windows are set to Trade Only, there is no time restriction on entries (same as all Off) Blackout and Trade Only can be combined: for example, set London to Trade Only and New York to Blackout to only trade the London session while avoiding NY volatilityTrading Day and Session Trading Days — enable or disable any individual day of the week. Disabling a day prevents new entries — open positions are still managed on disabled days. Trade Session — set allowed hours in exchange server time (HHMM-HHMM format). Default 0000-0000 means 24 hours with no restriction. This uses exchange server time, not your local time.Alert System — App Alert and Custom JSONHow to activate alerts: Set the alert mode to App Alert or Custom in the settings panel Create a TradingView alert on the chart (right-click → Add Alert) In the alert message box, paste exactly: {{strategy.order.alert_message}} This placeholder delivers the correct message for each order event automaticallyApp Alert mode sends a pre-formatted text message for each event:[ TICKER : EXCHANGE ]ENTRY LONG : {price}STOP LOSS : {stop level}TARGET PRICE : {target level}Exit alerts include a PNL percentage. No additional setup is required.Custom mode — JSON webhook for bot integration:Four separate input fields accept a single-line JSON string — one per order event: Long Entry — fires when a Long position opens Long Exit — fires when a Long position closes (TP, SL, or trailing stop) Short Entry — fires when a Short position opens Short Entry — fires when a Short position opensShort Exit — fires when a Short position closes (TP, SL, or trailing stop)Paste your JSON as a single line into each field. TradingView's input.string stores the content as a single line regardless of how it was formatted, making it safe for all webhook receivers.Settings Guide — Commission, Slippage, MarginDefault values are conservative starting points. Edit the strategy() declaration at the top of the script to match your broker and market. Detailed inline comments in the script explain every parameter.Commission defaults (0.1% per side, 2 ticks slippage): Stocks zero-commission broker → 0.0% Stocks SET Thailand → 0.16% Crypto spot (Binance) → 0.1% Crypto futures (Binance taker) → 0.04% XAUUSD $7 per standard lot → change commission_type to strategy.commission.cash_per_contract and commission_value to 0.07 ($7 ÷ 100 oz)Position sizing (default 2% of equity):For lot-based markets (Forex, XAUUSD) change default_qty_type to strategy.fixed and default_qty_value to the number of units. On XAUUSD: 1 unit = 1 oz, so 0.01 lot = value of 1, 0.10 lot = value of 10, 1.00 lot = value of 100.Margin/leverage simulation:Both margin_long and margin_short are 0 by default (no margin simulation). Formula: margin value = 100 / leverage ratio. Example: 1:500 leverage → margin_long = 0.2. These values cannot be set from the input panel — edit them directly in the strategy() call.Repainting WarningBefore connecting any indicator to the User Zone, verify it does not repaint. A repainting indicator places signal arrows on past bars using data from future bars that did not exist at the time — backtest results will look excellent while live trading produces nothing like it.How to check using Bar Replay: Open the indicator on your chart and find a signal arrow in the past Open Bar Replay and rewind to before that signal appeared Step forward one bar at a time using Shift + → Do not use the Play button (Shift + ↓) — bars move too fast to catch a disappearing arrowIf the arrow appears and stays permanently → safe to use. If the arrow appears then disappears or moves as you advance → repainting confirmed, do not use in a strategy.How to check using Alert Log:Enable the indicator's built-in alert, wait for it to fire on a live bar, then compare the alert log entry to the signal arrow on the chart. If they do not match in timing or direction → repainting.DisclaimerThis script is published for educational purposes only. It is a framework and template — not a complete trading system and not financial advice. Backtest results shown in Strategy Tester reflect historical data only and do not guarantee future performance. Past performance is not indicative of future results.All trading involves significant risk of loss. Do not trade with money you cannot afford to lose. The results produced by this template depend entirely on the signal logic the user provides — the author accepts no responsibility for any trading decisions made using this script or any modifications of it.Before using any strategy in live trading, you should fully understand how it works, verify its logic independently, and test it thoroughly on a demo account. Always consult a qualified financial advisor before making investment decisions.The pre-built Moving Average Cross trigger and Moving Average Trend filter included in the User Zone are provided as examples only — they are not recommendations to trade any specific method.