How To Build A Trading Strategy With Claude & Backtest On TradingView

Use Claude to draft Pine Script, check entries and exits in TradingView, compare filters, and build a reproducible backtest before testing alerts.

Share
How To Build A Trading Strategy With Claude & Backtest On TradingView

Claude can help turn a trading idea into Pine Script that you can test in TradingView. The useful workflow is to define the rules, compile the generated code, check individual trades and evaluate a historical simulation. This guide follows a moving-average example and shows how to iterate without confusing a better-looking backtest with a proven trading edge.

How To Build A Trading Strategy With Claude & Backtest On TradingView

Key Takeaways

  • Claude can draft Pine Script from plain-English rules; you must check that the code implements those rules.
  • TradingView's strategy tester gives you a full performance breakdown including P&L, win rate, drawdown, and profit factor.
  • Send exact compiler errors back to Claude for help, then compile and review each proposed correction.
  • Adding toggle filters to your strategy lets you test each component on or off without editing code.
  • Webhooks can send alerts to a separately configured execution service; delivery and order execution both need verification.
  • A great backtest doesn't guarantee live performance — always evaluate results in context.

What You'll Need

  • Claude AI — choose an available model and plan that supports your workload. Usage limits and features change; a paid plan does not guarantee correct Pine Script.
  • TradingView — you need chart access and Pine Editor. Historical-data depth, alerts and other features depend on the current plan. Check the plan comparison and checkout terms before subscribing; the original video's prices and promotions may have changed.
  • A trading idea — even one sentence is enough to get started.

Step 1: Set Up Claude for Strategy Building

Start a chat in Claude, or use a project if it is available in your plan. State that the goal is to write a Pine Script strategy for testing in TradingView. Keep your rule specification and code versions together so later changes can be checked against the original idea.

Model availability changes over time. Record the model you used and the date alongside the generated code. Any model can produce syntax errors or logic that compiles but does not match your instructions.

Step 2: Prompt Claude to Write Your Pine Script

Start with explicit rules. A short prompt can produce a draft, but omissions leave the model to choose important details. The video begins with this simple example:

"Create a trading strategy in Pine Script that goes long when price closes above the 200 moving average and exits when price closes below the 200 moving average."

Before copying the draft, resolve the prompt's ambiguity: specify SMA or EMA, the source price, timeframe, entry and exit conditions, and whether signals use completed bars. Ask for a Pine Script strategy, not just an indicator. The reproducible prompt below makes those choices explicit for a teaching example.

Step 3: Add the Strategy to TradingView

Open Pine Editor from the Pine icon on TradingView's right toolbar. In the editor's script-name menu, choose Create new > Strategy, replace the template with your draft, save it and select Add to chart. The editor can also be docked or detached; its placement may differ from the original video.

If compilation fails, copy the exact error message and relevant code into Claude. Ask for the smallest correction and an explanation, then compile again. Once it compiles, inspect several entries and exits against your written rules. Compilation checks syntax; it does not establish correct trading logic or realistic fills.

Step 4: Read and Interpret the Backtest Results

Once the strategy loads, TradingView displays the Strategy Report at the bottom of the screen. Key metrics to focus on:

  • Total P&L — overall profit or loss over the backtest period
  • Win rate — percentage of trades that were profitable
  • Profit factor — gross profit divided by gross loss. Interpret it alongside trade count, costs, drawdown and the test period; a high value alone is not proof of a robust strategy.
  • Max drawdown — the largest peak-to-trough drop during the period
  • Sharpe Ratio — risk-adjusted return; how efficiently the strategy converts risk into reward
  • Trade distribution — the spread of wins and losses by percentage range

Set initial capital, position sizing, commission and slippage in Strategy Properties to match the scenario being tested. Zero broker commission does not remove spread or execution costs. Record the symbol, data feed, timeframe and date range, and use standard price bars. Compare the result with buy-and-hold over the same period while considering different market exposure.

Step 5: Test Changes to the Strategy

Describe the problem you want to investigate, such as repeated trades near a moving average. Ask Claude for a small, testable change rather than a promise to improve returns. The original example explored these filters:

  • SMA buffer — require price to close 1% above the average to enter and 1% below to exit. This changes the trigger and may reduce repeated trades near the average; whether it helps is a testable question.
  • 50 SMA trend filter — require the 50 SMA to be above the 200 SMA. That ongoing state is different from requiring a fresh crossover on the entry bar.
  • ADX filter — restrict entries using an ADX threshold. Specify the calculation and threshold; it cannot confirm that a trend will persist.
  • RSI 40–75 entry band — allow entries only inside that range. Treat these as experimental parameters, not a universally optimal band.
  • RSI exit — add a precisely defined RSI exit condition. It responds to an indicator threshold; it cannot reliably identify or prevent a market crash.

Before running the updated code, ask Claude to make every filter a toggle — switchable on or off inside TradingView's settings without touching the code.

Step 6: Compare Filters Without Overfitting

Save the baseline first. Change one filter at a time while keeping the symbol, dates, timeframe, costs and sizing fixed. The observations below describe the original example, not results from a new test or rules that apply to every market:

  • RSI exit — removing it reportedly changed little in that sample. Check whether it triggered at all before deciding what the comparison means.
  • RSI entry band — little reported impact in the example. Evaluate other periods before judging its usefulness.
  • ADX filter — the original article reported a profit factor of 4.2, roughly 600% return and 17% drawdown after removing it. Those are historical example figures, not independently reproduced results. Without the complete code, dates and settings, they are not a benchmark readers can reliably reproduce.
  • SMA buffer — compare its effect on trade count, costs and drawdown. Fewer trades do not automatically produce a better strategy.
  • 50-over-200 filter — the original article reported returns approaching 800% after removing it. That reflects a selected historical configuration, not evidence of future returns or an optimal rule.

The original comparison included SPY, QQQ, Tesla and Apple and described SPY's equity curve as the most consistent. Asset selection is another form of selection: reserve data that did not guide your revisions and compare the unchanged final rules there. Do not keep retuning to the test period after seeing its result.

Step 7: Test Alerts Before Considering Automation

For notifications, create a TradingView alert using the intended strategy condition and supported delivery channel. Confirm the alert timing against the chart and the strategy's order events. An alert is a notification of a condition, not proof that an order was filled.

For an external workflow, a TradingView webhook sends an HTTP request to a configured destination. An execution service, such as the Alpha Insider workflow linked below, must separately interpret the message and handle a supported broker connection. Enable two-factor authentication, check current feature access, and verify delivery in the alert log. Webhooks can fail; a chart signal does not guarantee an executed trade.

Test the complete setup in a supported simulation or paper environment first. Check signal timestamps, duplicate handling, order size, rejected orders and exits, and know how to stop the integration. Simulated fills and matching alerts do not establish future live performance.

FAQ

Do I need to know how to code?
You can start with plain-English instructions, but you still need to inspect the generated logic and resolve errors. If you cannot explain an entry or exit, simplify the script before using it.

Can I do this on a free plan?
You can explore the workflow with the features available in your accounts. Check current model usage limits, historical-data access and alert features before choosing a paid plan; plan names, prices and promotions can change.

What is Pine Script?
TradingView's language for indicators and strategies. A strategy can simulate orders through TradingView's broker emulator; that is separate from sending real orders to a broker.

What's the difference between an indicator and a strategy?
Both can calculate chart values and produce signals or alerts. A strategy also defines simulated orders so TradingView can generate a performance report. An indicator's buy/sell marker alone is not a backtest.

What is overfitting?
When a strategy is so heavily optimized to past data that it breaks down on new data. A high backtested return is a starting point, not a guarantee.

Why build my own strategy instead of copying someone else's?
Writing explicit rules helps you understand, test and maintain the strategy. Keeping rules private does not by itself create or preserve an edge; costs, changing markets and implementation still matter.

What is Alpha Insider?
It is the execution-platform example in the linked walkthrough. Verify its current supported connections, plan requirements and setup instructions before attempting to connect any strategy alerts.

Conclusion

Claude can speed up drafting and revising code. TradingView can show how the resulting rules behaved in a historical simulation. You remain responsible for defining the rules, checking the implementation and interpreting the limitations of the test.

Use this sequence: specify the rules, generate a draft, resolve compiler errors, inspect individual trades, add realistic test settings, compare one change at a time, and evaluate unchanged rules on unused data before testing alerts.

The objective is a strategy you can explain and evaluate, not the highest number you can produce by repeatedly changing settings on the same history.

The reference links below include the original Alpha Insider walkthrough and TradingView referral link. Check current offers and product requirements at the destination; a discount or execution capability is not guaranteed by this article.

A clearer starting prompt

This specifies a simple teaching example. It is not a recommendation to trade a moving-average rule, and the generated code still requires review.

Write a Pine Script v6 strategy for TradingView using standard chart bars. Use a 200-period simple moving average of closing prices. Go long when a completed bar closes above the SMA and no long position is open. Close the long when a completed bar closes below the SMA. No shorts, no pyramiding and no extra filters. Explain how the default broker emulator schedules order fills relative to the signal bar. Do not use future data or lookahead. Expose the SMA length as an input. State the initial capital, order-sizing, commission and slippage assumptions so I can review them in Strategy Properties. Explain each entry and exit condition and flag anything you cannot implement.

Keep a reproducible test record

  • Save the prompt, model/date and exact script version.
  • Record the symbol including exchange or data feed, chart type, timeframe, test dates and every input.
  • Record capital, sizing, commission, slippage and order-fill settings. Report net results alongside trade count and maximum drawdown.
  • Check at least one expected entry, one expected exit and a bar where no trade should occur. Compare signal time with simulated fill time.
  • Keep a baseline and a period you have not used to choose filters. If you revise rules after viewing that period, it is no longer an untouched test.

Continue with the TradingView backtesting walkthrough and the repainting review prompt. The prompt is a review aid, not a certification that a script cannot repaint.

Checked November 2, 2026 against TradingView's documentation for Pine Editor, creating a strategy, strategy simulation and webhook delivery. Historical figures above were not rerun for this update.

Original resources: Alpha Insider walkthrough and TradingView referral link.