TradingView Backtesting

Average Holding Period: Trade Durations and Capital Weighting

Average holding period measures how long trades remain open. For completed trades, subtract each entry fill time from its exit fill time, then divide the total duration by the number of trades. The median describes the middle observation; a capital-weighted mean gives larger positions more influence. State the trade unit, clock, weights and treatment of open positions before comparing results.

See the decision guide

Define the observation before calculating its duration

Use actual simulated fill timestamps for a TradingView backtest and broker fill timestamps for live trading. A signal timestamp or order submission timestamp can precede execution. Choose one observation unit: a matched entry/exit lot, an exit slice, or a complete position episode from flat to flat. Mixing those units changes the average even when the executions are identical.

  • For milliseconds, d = (exit timestamp - entry timestamp) / 86,400,000 gives elapsed 24-hour days. Divide by 3,600,000 for hours. This counts nights and weekends.
  • Specify the cohort: entries during a window, exits during a window, or all positions touching it. These select different trades. If the entry precedes your export, recover it or mark the duration unknown; the export start is not the entry.
  • Keep long and short observations on the same clock. Duration is nonnegative for either direction; a short position does not have a negative holding period.
InputRequired definitionReason
Trade identifierUnique matched lot or position episodeTwo CSV rows can describe one trade; do not count both as two durations.
Entry and exitFill instants with time zone or UTC offsetSubtract instants, not unrelated local clock labels.
Status and cutoffClosed, or open at a fixed observation instantAn open age is only a lower bound on eventual duration.
WeightPositive entry capital in one reporting currencyQuantity, notional, margin and P&L weights answer different questions.

Reproduce the mean, median and capital-weighted result

Assume five completed, unsplit trades with constant entry-capital weights in USD. Each day below is exactly 24 elapsed hours. These invented amounts illustrate the formulas; they are not a market sample. Put durations in spreadsheet cells B2:B6 and capital in C2:C6.

  • The mean answers how long one equally weighted trade lasted on average. The 20-day observation raises it above the median. Report the longest duration and sample size alongside both.
  • The median is the middle sorted duration; for an even sample, average the two middle values. It describes the middle trade without measuring how much capital that trade used.
  • The 13-day result describes duration per dollar of entry capital committed across these trades. Reused capital enters the denominator each time it funds another trade; this is not average account exposure.
TradeDuration: daysEntry capital: USDCapital × days
A11,0001,000
B21,0002,000
C31,0003,000
D41,0004,000
E206,000120,000
Total3010,000130,000
Spreadsheet formulas for the five completed observations abovetext
Arithmetic mean = SUM(B2:B6) / COUNT(B2:B6) = 30 / 5 = 6 days
Spreadsheet: =AVERAGE(B2:B6)

Median = middle sorted duration = 3 days
Spreadsheet: =MEDIAN(B2:B6)

Capital-weighted mean = SUM(capital * duration) / SUM(capital)
                     = 130000 / 10000 = 13 days
Spreadsheet: =SUMPRODUCT(B2:B6,C2:C6)/SUM(C2:C6)

Make capital weighting explicit

For ordinary shares, define C as absolute share quantity × entry price. For contracts, include the contract multiplier; convert each entry value into the reporting currency using a stated entry-date FX convention. Then H = sum(C × d) / sum(C). This page uses gross entry notional as its capital convention, not cash margin, risk budget, exit value or profit.

  • Equal positive weights reproduce the arithmetic mean. Multiplying every weight by the same positive number leaves the result unchanged. With positive weights, the result must lie between the shortest and longest durations.
  • Leveraged notional can exceed funded cash. If the question concerns collateral tied up, use a separately defined margin ledger instead of relabeling notional as cash invested.
  • Profit weights can be negative or sum to zero and are not capital weights. Zero total weight makes the ratio undefined; missing or invalid weights require reconciliation.
  • Do not weight by capital × duration and then average duration again. That squares duration in the numerator. Measuring changing market-value exposure requires a time series and a declared integral, rather than this entry-weighted statistic.
  • Overlapping trades can make summed durations exceed the test window. Time in market instead measures the union of occupied intervals; it is a separate statistic.

Partial exits change what counts as a trade

Suppose 100 shares enter at $50, 40 exit after 2 days, and the remaining 60 exit after 10 days. There are no additional entries. A flat-to-flat position episode lasts 10 days. Treating the two exit slices as equally weighted observations gives (2 + 10) / 2 = 6 days. Weighting each slice by its original entry capital gives a different answer.

  • Do not assign the full $5,000 to both exits. That duplicates entry capital and silently produces the equal-slice result.
  • For scale-ins at different prices and times, match exit quantities to entry lots using a stated rule such as FIFO or explicit lot IDs. Each matched slice keeps its own entry instant and entry value.
  • Check quantity conservation: matched closed quantity plus remaining open quantity must equal entered quantity, after any documented adjustments. A reversal closes one episode and opens another.
  • Splitting one exit into several identical fills should leave the allocated-capital result unchanged. An unweighted exit-slice mean can change when a broker splits fills, which makes it unsuitable for some strategy comparisons.
Entry-capital weighting allocates the original $5,000 oncetext
First exit slice:  40 * $50 = $2000, duration = 2 days
Second exit slice: 60 * $50 = $3000, duration = 10 days
Weighted duration = (2000*2 + 3000*10) / (2000+3000)
                  = 34000 / 5000 = 6.8 days

Open positions are right-censored at the cutoff

Right censoring means the ending event has not been observed by the observation limit. Applied to holding periods, a position still open after 20 days has lasted at least 20 days; its eventual duration is unknown. The statistical definition follows the NIST censoring reference. A forced close at the test end creates a different trading rule, so label it separately.

  • Publish the closed count, open count, observation cutoff and open ages. In this example, excluding the long open trade understates the eventual cohort mean. The size and direction of selection effects depend on the sampling window and strategy.
  • Never encode an open trade as a completed zero-day trade. Do not treat the cutoff as a real exit merely to fill a missing cell.
  • A survival estimate requires explicit censor indicators and appropriate censoring assumptions. Its unrestricted mean can remain unidentified beyond the observed tail. A declared restricted horizon is a different estimand; a simple closed-trade average does not perform that adjustment.
Same-entry cohort at day 20CalculationInterpretation
Four closed trades: 1, 2, 3, 4 days10 / 4 = 2.5 daysMean among completed trades only
One trade still open, age 20 days(10 + 20) / 5 = 6 daysMean observed time through the cutoff, not eventual holding period
If the final trade later closes at day 30(10 + 30) / 5 = 8 daysEventual mean for this hypothetical five-trade cohort

Normalize cross-time-zone fills before subtracting

TradingView documents UNIX timestamps as independent of time zone and recommends IANA zone identifiers when regional clock changes matter. A fixed UTC offset does not follow daylight saving changes. Preserve each original zone or offset, convert to UTC, and subtract the resulting instants. Changing the display zone should not change the duration.

  • Elapsed time is 66 hours, or 2.75 days. Subtracting the New York clock labels without the DST offset change gives 67 hours. Subtracting the unrelated New York entry and London exit labels gives 71 hours.
  • During the autumn clock change, a local time such as 01:30 can occur twice. Require an offset or an unambiguous timestamp. Reject unresolved local timestamps rather than assuming the computer time zone.
  • Retain full precision during subtraction and round only the displayed result. A valid same-instant entry and exit has zero elapsed time; a negative result indicates a timestamp or matching problem.
Hypothetical eventRecorded local timeUTC instant
Entry, America/New_York2026-03-06 15:00, UTC-05:002026-03-06 20:00Z
Exit displayed in Europe/London2026-03-09 14:00, UTC+00:002026-03-09 14:00Z
Same exit displayed in America/New_York2026-03-09 10:00, UTC-04:002026-03-09 14:00Z

Calendar time and trading bars are different clocks

Use the same Friday-to-Monday example on a hypothetical regular-session chart with 30-minute bars, trading from 09:30 to 16:00 New York time and no intervening holiday. Entry fills at Friday 15:00 and exit at Monday 10:00. The elapsed calendar duration is still 66 hours, while time inside the stated sessions is 1 hour on Friday plus 0.5 hour on Monday.

  • TradingView strategy documentation demonstrates inclusive bar counting with exit bar index minus entry bar index plus one. That convention counts both fill bars; it does not imply exposure for the entire exit bar.
  • Four touched bars × 30 minutes = 2 hours, which is neither 66 elapsed hours nor the 1.5 hours of occupied session time in this example. State the bar convention alongside the timeframe and session.
  • Changing the timeframe changes bar counts while the same fill timestamps retain their elapsed duration. Missing bars, shortened sessions and non-time-based charts further prevent a universal conversion from bars to hours.
Clock or counting conventionResultWhat it includes
Elapsed calendar time66 hoursOvernight and weekend time, with DST handled
Time within the assumed sessions1.5 hoursOnly the two occupied regular-session intervals
Exit bar index minus entry bar index3 barsThree chart-bar steps between fill bars
Inclusive fill-bar count3 + 1 = 4 barsFriday 15:00, 15:30; Monday 09:30, 10:00

Check the CSV and the existing report fields

TradingView exports Strategy Report tabs separately, so obtain the List of Trades rather than only summary metrics. In Pineify, Backtest Deep Report stores entry time, exit time, quantity, prices, status and duration for imported trades. It displays per-trade Duration and Avg Duration. The current average is the arithmetic mean of parsed durations; it does not implement the median, capital-weighted or censor-adjusted methods above.

  • Inspect the raw CSV against the chart before interpreting averages. The current importer selects the first entry and first exit for each trade ID. Reconcile multiple entries, partial exits and repeated IDs in a separate matched-lot worksheet.
  • Review the include-open-trades setting. Open rows can enter the parsed set; a missing exit currently produces zero duration. Exclude them from a completed-trade mean and keep their cutoff ages separately. Do not infer a censor-aware estimate from Avg Duration.
  • The report type includes an average-bars field, but the current calculation returns null. Use actual chart bar indices for bar counts rather than deriving them from timestamp duration.
  • The importer can interpret offset-free dates using the local environment. Verify the export time convention and a known DST-crossing trade before relying on its duration field.
  • For an empty closed sample, report the mean and median as unavailable. Keep the count and missing-record reasons; a displayed zero is not evidence that trades had zero duration.
Where Pineify fits

Backtest Deep Report

Review imported trade durations and the existing arithmetic average. Keep the matched-lot worksheet for median, capital weighting and open-position ages alongside the report.

Also useful: Pine Script AI Coding Agent. Draft custom strategy statistics with an explicit fill-time and bar-count convention, then verify generated calculations against the examples and your trade ledger.

Explore the backtest report

Frequently asked questions

Educational information, not investment advice. All trades, capital amounts and outcomes here are hypothetical arithmetic examples. Holding-period statistics describe recorded events and do not establish profitability or predict future execution.

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.