How to Backtest a Trading Strategy on TradingView

Learn how to backtest a trading strategy on TradingView, dial in the right settings, and avoid fake results from curve fitting and repainting.

Share
How to Backtest a Trading Strategy on TradingView
How to backtest on TradingView.

Want to test a trading strategy without risking a single dollar? Learning how to backtest a trading strategy on TradingView lets you fact-check your returns, spot exactly what's dragging your performance down, and make adjustments before real money is on the line.

A historical test can look attractive and still fail in live trading. This guide walks through generating strategy code, configuring the simulation, and checking its assumptions. No combination of settings guarantees that simulated and live results will match.

By the end, you'll know how to build a working backtest and how to stress-test it so you don't get fooled by results that look too good to be true.

Table of Contents

Key Takeaways

  • Backtesting simulates a strategy on historical data.
  • AI can draft Pine Script, but you still need to compile it and check the logic.
  • A strategy() script produces a Strategy Report; indicators can also generate signals and alerts.
  • Record position sizing, costs, dates, and execution assumptions.
  • Investigate unusually strong results for bias and implementation errors.
  • Forward observation is another check, not proof of future profitability.

Prerequisites: What You'll Need

Before you build your first backtest, gather these essentials:

  • A TradingView account — the free basic plan is enough to start.
  • A way to generate Pine Script code — your own coding skills, or an AI assistant like Claude or ChatGPT.
  • A trading strategy idea — even a rough concept you want to test (e.g., a crypto swing trading breakout system).
  • Time: roughly 20–30 minutes for your first run-through.
  • Skill level: beginner-friendly. No prior coding experience is required if you're using AI to generate the code.

Do You Need a Paid TradingView Plan?

Short answer: no, not to start.

You can begin backtesting on the basic (free) plan. You'll just be limited — you won't get deep backtesting, which lets you go further back in time and gives you a more detailed look at your data.

Here's TC Trading's honest advice on upgrading:

  • Upgrade for a specific need. Check the current plan comparison before paying for more history, alerts, or other features.
  • Check offers at checkout. Referral discounts and seasonal promotions can change; the price in an older recording may no longer apply.

Step-by-Step Guide to Backtesting on TradingView

Step 1: Generate Your Pine Script Strategy

You need Pine Script code to run a strategy. With AI, this is now fast and accessible.

TC Trading's approach: keep a dedicated trading strategy project inside Claude. Feed in your past strategies for context, then describe exactly what you want. For example: "I'm looking to develop a crypto swing trading strategy for the big names — ETH, Bitcoin, Sol — with the ability to toggle different settings so I can fully customize it."

Claude then spits back the full Pine Script code — often in just minutes.

Important — prompting is an art:

  • Typing "build me a profitable trading strategy and make no mistakes" will get you a useless response.
  • Give real context, specify the settings you want to toggle, and treat the output as a starting point, not a finished product.
  • Expect to experiment, customize, edit, and adapt over time.

Step 2: Paste the Code Into the Pine Editor

Once you have your code:

  1. Click the Pine icon on the right toolbar. The editor can also be moved or detached.
  2. Open the script-name menu.
  3. Choose Create new → Strategy.
  4. Paste your draft code, then resolve compiler errors and verify its rules.
  5. Save it with a descriptive name; the recorded example was called Crypto Swing Lab v1.

Why strategy matters: A strategy() script simulates orders through TradingView's broker emulator. An indicator can display signals and create alerts, but does not itself produce a Strategy Report. Neither script type automatically sends real orders to a connected brokerage account.

Step 3: Add the Strategy to Your Chart

After saving, click Add to Chart. Your strategy now appears on the left-hand side of the chart, just like an indicator would.

From there, using the three-dot icon on the right of the strategy, you can:

  • Edit the settings
  • Toggle it on/off (hide or show it)
  • View the source code
  • Delete it
  • Add alerts and other actions

Step 4: Borrow From the Community Library

Don't want to start from scratch? TradingView has a massive, constantly refreshed library of strategies.

  1. Open Indicators on Supercharts.
  2. Browse Technicals → Strategies or Community.
  3. Choose a strategy whose source is available if you intend to inspect or modify its code. Respect the author's license and publication rules.

You can read about how each strategy works, then pull up its source code. From there:

  • Apply the strategy to a chart and inspect its assumptions.
  • If its license permits modification, describe the changes you want to your coding assistant.
  • Compile and review the result. Public availability and attractive historical returns do not establish that a script is reliable.

Step 5: Read the Strategy Report

Once your strategy is running, head to the Strategy Report in the bottom corner of the screen. This is your backtest dashboard.

A key section to understand is Strategy Outperformance. It compares:

  • Your strategy's return (all the buys, sells, longs, and shorts), versus
  • Buy and hold — what you'd have made simply buying the asset at the start of the backtest and holding it.

The original article reported a Bitcoin backtest annualizing at just under 25%, beginning around 2016/2017, while still trailing buy-and-hold Bitcoin. Treat those as historical example figures, not a current performance claim: the exact source code, dates, and settings needed to reproduce them are not supplied here.

When comparing a strategy with buy-and-hold, examine the exposure and risk assumptions as well as the return:

  • A few large winning trades can dominate the result; inspect the trade distribution.
  • The original example reported 7.59% strategy drawdown and roughly 75% for Bitcoin. This is an unreproduced historical comparison, and different sizing or drawdown definitions can materially change it.

Lower simulated drawdown is useful information, but it does not guarantee downside protection in a live account.

The Properties Tab: Where Backtests Live or Die

Inside the Strategy Report settings, the Properties tab is one of the most crucial parts of backtesting. Get this wrong, and your backtest won't align with reality.

Order size is the big one. Here's how the same strategy can produce wildly different results:

Order Size Setting What It Means
100% of equity Sizes an entry from the available equity; exposure is not the same as a predetermined maximum loss.
% of equity (e.g., 10%) Sets position size relative to equity. It does not mean that exactly 10% of the account is at risk.
Quantity Uses a specified number of contracts, shares, or units.
Amount in currency Uses a specified notional amount in the strategy's base currency.

Use sizing that represents the intended account and instrument. Changing from 100% to 10% of equity changes exposure and compounding; actual loss also depends on price movement, exits, leverage, and execution.

Portfolio check: Do not simply average standalone backtests and call that an achievable portfolio. Account for simultaneous positions, shared capital, correlation, costs, and overlapping losses.

Other Properties settings worth knowing:

  • Pyramiding: Check how many same-direction entries the script permits.
  • Bar detalization: High uses finer historical simulation on eligible plans. The tick count depends on timeframe; 32 is not a universal count, and these are simulated intrabar steps rather than a complete exchange tick history. Compare Default and High where available.
  • Commission and slippage: Use assumptions appropriate to your instrument, broker, and order types; stress-test worse execution too. A fixed couple of ticks is not suitable for every market.
  • Margin, limit fills, and script execution: Inspect each setting and record it with the result. More detailed simulation remains a model.

There's also a Style tab (purely visual — how signals and alerts appear) and a Visibility tab (which time frames the strategy displays on). Neither changes how the strategy operates.

Testing Different Time Frames

Changing the chart's time frame — say from 4-hour to 1-day — automatically updates the backtest report.

Why does this matter? Your entry logic (a breakout, an EMA cross, an RSI level) gets recalculated on each new time frame. Many strategies are highly sensitive to this: it works beautifully on one time frame and falls apart on another.

TC Trading's guidance:

  • My usual starting points for swing-trading research are 1-hour, 4-hour, daily, and weekly charts. These are preferences, not universally optimal settings.
  • Shorter charts, such as 5-minute, answer different questions and can be more sensitive to costs.
  • Choose the intended holding period first, then test that design rather than selecting whichever timeframe produced the best past return.

Cycle through the time frames and find the settings that fit your strategy's intended style.

The Gut Check: Too Good To Be True

Here's the warning most people won't give you: when a backtest looks almost too good to be true, there's a very good chance one of two problems is hiding underneath:

  1. Curve fitting
  2. Repainting

A beautiful equity curve means nothing if it's built on either of these. Let's break them both down.

Curve Fitting Explained

Curve fitting is when you optimize your settings so perfectly for the past that they fail in the future.

You look at your data, tune the parameters until "this thing literally doesn't lose" — but the future is never identical to the past. It might rhyme, but a slight shift in market conditions can flip your strategy from wildly profitable to not even close.

How to test for curve fitting: Apply the strategy broadly to other assets.

  • Results on other assets can reveal fragility.
  • Related cryptocurrencies can share the same underlying exposure, so passing several crypto tests is not independent proof of robustness.
  • Keep a genuinely unused test period and avoid tuning the rules after seeing its results.

Also check your trade count. The original example reported 99 trades. Neither 99 nor 100 is a reliability threshold: dependence between trades, regime coverage, the return distribution, and how many configurations you tried all matter.

Test multiple market regimes and retain disappointing results in your record. Repeatedly tuning against all available history can overfit that larger dataset too.

Repainting Explained (And How to Catch It)

Repainting means a script's historical and realtime behavior differs. A signal changing while a candle develops is one example; future-data leakage and plotting information into the past are more serious cases. Not every change is evidence of future-data access.

A mismatch deserves investigation. It can come from script calculations, data revisions, execution assumptions, alert timing, or costs; the mismatch alone does not identify the cause.

Use several checks together:

  1. Record forward signals. An external tracker such as AlphaInsider can help keep a record where supported. Distinguish simulated tracking from actual broker fills.
  2. Compare logs. Match signal time, intended order, submitted order, and fill where available. Check delivery failures as well as price differences.
  3. Inspect code and replay behavior. Review higher-timeframe requests, confirmation rules, and historical plotting. Bar Replay is useful, but cannot reproduce every realtime update or prove that all repainting is absent.

Webhook alerts require an eligible plan and two-factor authentication. Delivery can fail, so monitor the alert log and the receiving system.

A clean comparison increases confidence in the tested conditions. It does not validate every historical trade or establish future profitability.

Frequently Asked Questions

Do I need to pay for TradingView to backtest?
No. You can backtest on the free basic plan. You'll be limited — no deep backtesting and less historical data — but it's enough to start. Only upgrade when you hit a genuine limitation.

What's the difference between a strategy and an indicator?
Indicators can display signals and issue alerts. Strategies additionally simulate orders and produce a Strategy Report; simulated orders are not real brokerage executions.

Can AI write my Pine Script strategy?
Yes. Tools like Claude and ChatGPT can generate Pine Script from a plain-language description. But prompting is an art — give real context and specific requirements, and treat the output as a customizable starting point, not a finished product.

Why do my backtest and live results differ?
Compare sizing, costs, available data, script calculations, alert timing, order handling, and fills. Start with the recorded settings and logs rather than assuming one cause.

What is curve fitting?
It is fitting rules too closely to the historical sample. Test frozen rules on unused periods and other relevant datasets, and disclose how many variations you tried.

What is repainting?
Historical and realtime calculations can differ. Review the script and its observed signals; a replay alone is not a complete audit.

How many trades make a backtest reliable?
There is no universal minimum that proves reliability. Trade dependence, regime coverage, parameter selection, and uncertainty matter alongside the count.

Which Properties settings should I review?
Record capital, sizing, costs, margin, fill assumptions, and calculation settings. When available, compare Bar detalization modes; a fixed tick count or slippage value is not appropriate for every chart.

What does forward testing establish?
It records behavior on data arriving after the rules were chosen. Paper tracking helps test the workflow; only actual account records show actual fills. Neither guarantees future returns.

Conclusion

To start backtesting, compile your Pine Script, add the strategy to a chart, inspect the report, and save the settings alongside the results. Treat each run as a test of assumptions.

Then examine sensitivity, unused data, costs, and forward observations. Keep a record of failed tests as well as successful ones.

Ready to try the workflow? Open TradingView and start with a strategy you can explain. If you consider upgrading, check the actual price and eligibility at checkout. AlphaInsider is an optional external tracking and automation tool; confirm its supported connection and test the workflow before enabling live orders.

Watch the full video here:

Documentation checked

Instructions and claim wording reviewed November 2, 2026. Historical example results have not been independently reproduced.

Pine Editor · Strategy Report · Strategy properties · Detalization and execution · Repainting · Strategy testing and overfitting · Webhook delivery · Current plan features