TradingView Backtesting

Robust strategy optimization across adverse scenarios

Robust optimization chooses a decision against a specified set of uncertain conditions. For trading research, a maximin rule selects the eligible strategy with the highest minimum score across declared cost and historical-window scenarios. It can sacrifice typical or favorable performance to improve the tested floor. That floor applies to the modeled scenarios; it is not a bound on future losses.

See the decision guide

Specify the decision before calculating the matrix

Let θ identify one fixed candidate strategy and s identify one scenario in a finite uncertainty set U. Let J(θ, s) be net P&L in USD for that scenario. The maximin objective is to choose θ that maximizes min over s in U of J(θ, s), among eligible candidates. A median objective instead maximizes median over s in U of J(θ, s). These objectives answer different questions even when they use identical runs.

  • Define U before scoring. This example uses two equal-duration development windows crossed with three cost levels: U = {W1, W2} × {$2, $4, $8 per completed round trip}. All six combinations count; neither window is a final holdout.
  • Declare eligibility separately. Here every scenario must have at least 30 completed trades and net P&L of at least -$200, or -2% of starting capital. These illustrative cutoffs are research choices, not evidence that 30 trades suffice or that a 2% loss is acceptable.
  • Resolve exact objective ties by the other objective, then by a fixed candidate ID order. If no candidate passes every constraint, record no selection. A failed or missing run cannot disappear from the minimum.
  • Keep symbol, timeframe, data version, sizing, currency and order rules fixed across cost scenarios for each candidate. Freeze the candidate list too; a broader search creates additional selection opportunities.

Rebuild six scenarios from four gross P&L inputs

The numbers are invented for arithmetic, not measured strategy results. W1 is January through June 2023 and W2 is July through December 2023. Each window independently starts with $10,000; position size is fixed rather than compounded, and every position closes by the window end. Candidate A has gross P&L of $1,400 in W1 and $700 in W2, with 100 completed round trips in each. B has $700 and $650, with 40 round trips in each. Gross P&L here means total trading P&L before costs, including losing trades.

  • For each cell, J = G - N × c, where G is gross window P&L, N is the completed round-trip count and c is the total cost of one round trip. A in W2 at $8 costs $700 - 100 × $8 = -$100; B is $650 - 40 × $8 = $330.
  • The cost already covers entry and exit together. Do not double it or deduct it again from an export that already reports net P&L. Return in percent is 100 × J / $10,000; the two preceding cells are -1.00% and 3.30%.
  • This linear calculation assumes costs do not change trade timing, quantities or fills. It is a transparent fixed-trade stress model. Actual slippage, skipped limit orders or equity-dependent sizing can change the trade sequence and require a new backtest.
  • Six cells are six modeled conditions, not six independent market samples. The two windows have equal duration, and all cells receive equal weight in the median. The median is neither an estimated expected return nor a probability-weighted forecast.
ScenarioCost per round tripA: net P&LB: net P&L
W1, low cost$2$1,200$620
W1, middle cost$4$1,000$540
W1, high cost$8$600$380
W2, low cost$2$500$570
W2, middle cost$4$300$490
W2, high cost$8-$100$330

Select A by median, B by the worst scenario

Both candidates meet the declared trade-count and net-P&L constraints in all six cells. Sort each candidate's scores and average the third and fourth values to obtain the median. A sorts to -100, 300, 500, 600, 1,000, 1,200, so its median is (500 + 600) / 2 = $550. B sorts to 330, 380, 490, 540, 570, 620, so its median is (490 + 540) / 2 = $515.

  • The conservative choice B improves the minimum by $330 - (-$100) = $430, or 4.30 percentage points of initial capital. Its median opportunity cost is $550 - $515 = $35, or 0.35 percentage points.
  • Against the explicitly declared W1 low-cost reference, B gives up $1,200 - $620 = $580, or 5.80 percentage points. Report the reference alongside this cost; changing the reference changes the comparison.
  • This is a choice among two candidates under six conditions, not proof of a global optimum over every trading rule. A sensitivity plot could show the same values, but a selection protocol also specifies which objective wins and what happens when constraints fail.
Decision criterionABSelection
Minimum scenario P&L-$100 (-1.00%)$330 (3.30%)B
Median scenario P&L$550 (5.50%)$515 (5.15%)A
Declared reference: W1 at $2$1,200 (12.00%)$620 (6.20%)A

The uncertainty set controls the protection and its cost

A small set can omit a damaging regime. An excessively broad set can let an implausible combination dictate the decision. Choose ranges from execution evidence and a stated research question before looking for a winner. Bertsimas and Sim describe the tradeoff between protection against uncertainty and performance under nominal data; this teaching matrix uses a finite scenario maximin rule, not their uncertainty-budget formulation or its probability guarantees.

  • As a separately declared stress extension, add $12 per round trip in both windows. A then earns $200 in W1 and -$500 in W2, so it fails the -$200 floor. B earns $220 and $170 and still passes. This demonstrates how expanding U changes feasibility; it is not permission to alter U until the preferred candidate wins.
  • If the original $8 maximum were exceeded in deployment, the original tested minimum would no longer cover that condition. Even within the cost range, an unseen price path can produce losses absent from both historical windows.
  • Use plausible joint scenarios. Combining separate worst observations for spread, impact and liquidity can double-count a single event or invent an impossible state. Conversely, evaluating each stress alone can miss a joint failure.
  • The example constrains terminal net P&L, not intrawindow drawdown or margin use. Real mandates may need path-based drawdown, exposure and liquidity constraints in every scenario. Those quantities require appropriate equity and execution data; gross totals alone cannot establish them.

Keep selection windows separate from a chronological holdout

In an example protocol designed before any scores are inspected, develop the candidate definitions using data ending in 2022, select with the declared W1 and W2 scenarios in 2023, and reserve January through June 2024 for a sealed chronological holdout. Historical dates illustrate data roles only. A period already inspected during research is not unseen because it receives a new label.

  • Before opening the holdout, save candidate definitions, script hashes, the full scenario matrix, cost evidence, eligibility rules, tie policy and the chosen objective. Retain rejected candidates and failed runs.
  • Freeze the selected candidate and apply the predetermined evaluation assumptions to the holdout. Do not compare holdout outcomes to decide between median and maximin; that would make the holdout another selection window.
  • Use only information available at each decision time. Fit any model or preprocessing on earlier data. Account for labels or trades that span split boundaries, and state the warm-up and position-closing rules.
  • A disappointing holdout is a reported result. Revising the strategy, uncertainty set or constraints after seeing it consumes that test. Evaluate the revised procedure on genuinely unseen later data or a separately specified outer chronological evaluation.

Robust optimization and outlier-resistant estimation differ

Robust statistical estimation limits the influence of unusual observations on an estimate, for example using a median instead of a mean. Robust optimization here selects a decision against an uncertainty set and deliberately pays attention to its worst modeled outcome. Computing the median of six scenarios does not turn that objective into a worst-case guarantee.

  • Investigate a suspicious loss as a data-quality issue. If it is an erroneous fill or corrupt record, correct it with an audit trail. A genuine adverse event is not a data error merely because it determines the minimum.
  • A median objective can tolerate poor lower-tail scenarios. If that behavior conflicts with the research requirement, specify a floor or a different risk objective before selection. Removing losing cells afterward changes the question.
  • Neither an outlier-resistant estimator nor a maximin selection repairs lookahead, omitted costs, unrealistic fills or repeated reuse of a test period. Future conditions can fall outside the declared set.

Build the audit from TradingView exports and a separate matrix

Save each candidate-window-cost run with its settings and trade export. TradingView documents separate exports for trade details and performance metrics; its strategy documentation also describes workbook exports with properties. If your download is a workbook, save the trades sheet as CSV for Pineify and verify the headers, dates, currency and quantities. Keep the original export and experiment manifest.

  • TradingView provides commission settings and fixed-tick slippage settings. A round-trip dollar stress cost is not the same unit as either input. Translate your assumptions for the instrument and rerun when changing fills or sizing could change trades.
  • Backtest Deep Report reads List of Trades CSV fields including trade IDs, times, prices, quantity, net P&L and excursions. Its implemented summaries include net profit, trade count, profit factor and drawdown from closed-trade equity. Reconcile counts and net P&L against each source run before using them.
  • Calculate scenario minima, medians, constraint checks and the opportunity-cost comparison separately using the formulas above. This page does not claim the report includes a cross-scenario optimizer, an intrabar equity reconstruction or automated holdout governance.
  • Pine Script AI Coding Agent can help draft parameter inputs and explicit date rules. Review and validate any generated script, then check its actual trades. Code generation cannot choose a justified uncertainty set or establish future performance.
Where Pineify fits

Backtest Deep Report

Review supported metrics from each TradingView trade CSV, then record the cross-scenario selection in your own research matrix.

Also useful: Pine Script AI Coding Agent. Draft explicit parameter and date controls for review, then validate the script and reconcile the resulting trades.

Review Backtest Deep Report

Frequently asked questions

Educational research methods, not investment advice. All candidates, dates, costs and P&L figures are hypothetical. Historical scenario results do not guarantee future returns or limit future losses.

Sources and verification

Published by Pineify. Pineify is an independent product and is not affiliated with TradingView. Sources support the technical explanations; examples do not establish trading performance.