Skip to content
Algo Trade Analytics Docs
Pine library page — review pending. This page is preserved for compatibility but is not part of the reviewed search index. Check the official Pine Script v6 reference before relying on its explanation, signature, or example.

Pine Script strategy.closedtrades: Count Closed Trades

TL;DR
Track strategy.closedtrades so you know exactly how many trades have completed and can react when new ones close.

DifficultyBeginner
Time to implement5-10 min
CategoryStrategy Basics
//@version=6
strategy("Closed trades counter", overlay=false)
plot(strategy.closedtrades, "Closed trades", color=color.blue)
if strategy.closedtrades > 50
alert("Strategy has closed more than 50 trades.")
Tip. `strategy.closedtrades` is cumulative and only increments when a position is fully closed (either profit or loss).

The number of closed trades is a core metric for evaluating sample size, calculating win ratios, or enforcing rule-based limits (e.g., stop trading after N trades). Because Pine Script exposes it as a series, you can inspect previous values to detect when the latest trade and its P/L finalised.

  • Checking the current count of closed trades
  • Detecting new closures by comparing with prior bars
  • Using the count for win-rate or drawdown rules
  • Visualising trade counts over time
CallPurpose
strategy.closedtradesReturns the cumulative number of completed trades.
strategy.closedtrades[1]Previous bar’s total—use to detect newly closed trades.
strategy.wintrades / strategy.losstradesSplit counts for win-rate analysis.
strategy.closedtrades.profit(trade_num)Accesses P/L values of past trades when you need more detail.
strategy.close_all()Useful when you want to halt trading after a maximum number of trades.
  1. Read the current trade count
    Use simple comparisons to guard against running too many backtest trades.

    maxTrades = input.int(100, "Max trades", minval=1)
    if strategy.closedtrades >= maxTrades
    strategy.close_all("Trade limit hit")
  2. Detect a new closed trade
    Compare current and previous values to trigger logic on closure.

    newTradeClosed = strategy.closedtrades > strategy.closedtrades[1]
    if newTradeClosed
    alert("New trade closed! Total trades: " + str.tostring(strategy.closedtrades))
  3. Compute win rate using trade counts
    Combine strategy.closedtrades with winning trade counts.

    winRate = strategy.closedtrades > 0
    ? strategy.wintrades / strategy.closedtrades
    : na
    plot(winRate, "Win rate", color=color.green)
//@version=6
strategy("Breakout with trade counter", overlay=true, pyramiding=1)
length = input.int(20, "Breakout length")
highBreak = ta.highest(high, length)
lowBreak = ta.lowest(low, length)
plot(highBreak, "High breakout", color=color.orange)
plot(lowBreak, "Low breakout", color=color.blue)
if high > highBreak
strategy.entry("Breakout Long", strategy.long)
if low < lowBreak
strategy.entry("Breakout Short", strategy.short)
// Detect new closed trades
newClosed = strategy.closedtrades > strategy.closedtrades[1]
if newClosed
lastProfit = strategy.closedtrades.profit(strategy.closedtrades - 1)
label.new(bar_index, high, "Trade #" + str.tostring(strategy.closedtrades) +
"\nP/L: " + str.tostring(lastProfit, format.mintick),
style=label.style_label_down, textcolor=color.white, bgcolor=color.new(color.blue, 65))
plot(strategy.closedtrades, "Closed trades", color=color.new(color.purple, 0))
Why this works.
  • The counter increments immediately when a trade exits, enabling timely annotations.
  • We store the latest P/L to provide context for each label.
  • Plotting the cumulative count reveals how frequently the strategy trades over time.
  • strategy.closedtrades resets only when the strategy restarts (backtest or live). Track deltas if you need session-based metrics.
  • Combine with strategy.closedtrades.exit_bar_index(trade_num) to see when the trade closed.
  • For performance, avoid looping over every closed trade on every bar; store information as it becomes available.
  • Use alerts or conditional logic to pause trading if too many losing trades occur within a fixed window.

strategy.closedtrades increments by one per closed position, including partial exits treated as separate trades. Verify how you structure entries/exits and pyramiding rules.

Can I differentiate long vs short closed trades?

Section titled “Can I differentiate long vs short closed trades?”

Yes—check strategy.closedtrades.entry_direction(trade_num) or the profit value sign to infer direction.

  • strategy.closedtrades provides a bar-by-bar snapshot of completed trades.
  • Comparing current and previous values detects when a new trade finishes.
  • Combine trade counts with win/loss breakdowns and alerts to supervise strategy behaviour.
  • Plotting the count helps visualise strategy cadence and identify periods of inactivity or churn.