Backtesting in TradingView Example


Backtesting is a fundamental trading process that helps traders evaluate the effectiveness of their trading strategies by analyzing past market data. It allows traders to determine whether a strategy has been historically profitable and whether it has the potential to be successful in the future.

Why Backtest a Strategy?

Backtesting is essential because it helps traders avoid wasting time and money on strategies that do not work. By simulating trades on historical data, traders can identify whether a strategy is profitable across different market conditions before risking real capital.

There are two primary methods of backtesting:

  • Systematic Backtesting: This uses software that runs a trading algorithm through historical data.
  • Manual Backtesting: This involves manually reviewing price charts and recording hypothetical trades.

While systematic backtesting is efficient, manual backtesting allows traders to better understand price action and trading setups.

See my video:

 

What to Backtest?

You don’t need a complete trading strategy to start backtesting. You can test small components of a strategy before putting them together. For example, traders often test:

  • Candlestick patterns
  • Support and resistance levels
  • Trendline breakouts
  • Moving average crossovers
  • Volume-based strategies

Once a complete strategy is developed, it should be tested under different market conditions (ranging, trending, high volatility, low volatility, etc.) to ensure robustness.

Systematic Backtesting

backtesting in treadingview strategy ea

Backtesting a trading strategy is crucial to evaluating its effectiveness before applying it to live trading. TradingView provides two primary ways to backtest strategies:

  1. Using the Strategy Tester for automated backtesting (for strategies coded in Pine Script).
  2. Performing manual backtesting with the Replay Trading feature.

1. Backtesting Using the Strategy Tester

If you have a trading strategy coded in Pine Script, you can use TradingView’s built-in Strategy Tester to analyze its historical performance.

Step 1: Selecting a Strategy

  1. Open TradingView and go to the asset (stock, forex pair, crypto, or commodity) you want to test.
  2. Choose the strategy script you want to test from the Indicators & Strategies section.
  3. Apply the strategy to the chart.

Step 2: Configuring the Backtest

  1. Choose a relevant timeframe (e.g., 1-hour, 4-hour, daily, etc.).
  2. Select a historical period (e.g., the last 12 years for stocks, the last 2 years for forex pairs, etc.).
  3. Click on Strategy Tester at the bottom of the screen and select Generate Report.

Step 3: Analyzing the Strategy Performance

  • It may be robust if the strategy produces positive results in different timeframes (e.g., 15 minutes, 1 hour, 4 hours).
  • If performance varies significantly across assets (e.g., works well on stocks but poorly on indices), it suggests the strategy is asset-dependent.
  • Test the strategy on stocks, forex pairs, commodities, and indices to identify the best-performing assets.
  • If a strategy performs well in a bull market but poorly in a bear market, it may be trend-sensitive.

Step 4: Evaluating Market Conditions

  • Test during different market phases:
    • Bullish trend: Does the strategy perform well?
    • Bearish trend: Does it lose money?
    • Sideways market: Does it still perform?
  • Adjust the parameters (e.g., moving average length, stop-loss, take-profit) to optimize performance.

Step 5: Adding Additional Filters

  • Use indicators like Average True Range (ATR) to assess volatility.
  • Test during high-volatility vs. low-volatility periods.
  • Use the Relative Strength Index (RSI) or MACD as confirmation indicators.

2. Manual Backtesting Using Replay Trading

TradingView’s Replay Trading feature allows manual backtesting for traders who prefer discretionary analysis.

Step 1: Selecting a Historical Period

  1. Click on the Replay button in the TradingView toolbar.
  2. Choose a specific historical date (e.g., January 2025).
  3. The chart will rewind to that point, hiding future price action.

Step 2: Testing Trade Entries and Exits

  1. Identify trade opportunities based on your strategy rules.
  2. Manually place buy/sell trades as per the strategy’s conditions.
  3. Use the Step Forward button to progress the price action candle by candle.
  4. Record each trade, including:
    • Entry and exit price.
    • Stop-loss and take-profit levels.
    • Win/loss outcome.

Step 3: Evaluating Performance

  • Compare strategy effectiveness in bullish, bearish, and ranging markets.
  • Adjust strategy rules if necessary.
  • Repeat the process on multiple assets and timeframes.

3. Optimizing the Strategy for Better Results

After backtesting, optimize the strategy by:

  • Tweaking parameters (e.g., changing a 50-period moving average to a 100-period moving average).
  • Applying different entry/exit conditions.
  • Filtering trades based on volatility.
  • Adjusting risk management settings (stop-loss, position size, leverage, etc.).

How to Manually Backtest in TradingView

TradingView provides an excellent environment for manual backtesting with its Bar Replay tool. This tool allows traders to go back in time and analyze the market without knowing future price movements.

 

Steps for Backtesting

  1. Gather Historical Data
    • Use at least a few weeks of data for short-term strategies (scalping, intraday).
    • Use multiple years of data for higher timeframes (swing or position trading).
  2. Define the Strategy Parameters
    • State entry and exit conditions. For example:
      • Enter a long position if the price closes above the 50-period moving average.
    • Include risk management rules, such as:
      • Risk 1% of the account per trade.
      • Use a fixed 2:1 reward-to-risk ratio.
  3. Use TradingView’s Bar Replay Tool
    • Open a price chart on TradingView.
    • Click on the “Replay” button.
    • Select a date in the past and start playing the price action forward.
  4. Analyze Entry and Exit Signals
    • Mark or write down each trade.
    • Log trade details such as:
      • Entry price
      • Stop-loss and take-profit levels
      • Trade outcome (win/loss)
  5. Evaluate Performance
    • After collecting enough trades, calculate key performance metrics:
      • Win rate (%)
      • Risk-to-reward ratio
      • Maximum drawdown
      • Profitability over time

Common Mistakes in Backtesting

Traders often make errors in backtesting that lead to misleading results. Some common pitfalls include:

  • Using too little data: A small sample size may not capture all market conditions.
  • Not defining clear rules: Vague strategies lead to inconsistent results in live trading.
  • Overfitting: A strategy that performs well in backtesting but fails in live trading may be too optimized for past data.
  • Ignoring drawdowns: Failing to test for prolonged losing streaks can result in unexpected losses in actual trading.

Conclusion

Backtesting in TradingView is a powerful way to validate trading strategies before applying them to live markets. By following a structured approach and avoiding common mistakes, traders can gain confidence in their strategies and improve their overall trading performance. Whether done manually or systematically, backtesting should be an ongoing process to refine and adapt strategies to changing market conditions.

 

Fxigor

Fxigor

Igor has been a trader since 2007. Currently, Igor works for several prop trading companies. He is an expert in financial niche, long-term trading, and weekly technical levels. The primary field of Igor's research is the application of machine learning in algorithmic trading. Education: Computer Engineering and Ph.D. in machine learning. Igor regularly publishes trading-related videos on the Fxigor Youtube channel. To contact Igor write on: igor@forex.in.rs

Trade gold and silver. Visit the broker's page and start trading high liquidity spot metals - the most traded instruments in the world.

Trade Gold & Silver

GET FREE MEAN REVERSION STRATEGY

Recent Posts