Get the number of closed trades from a Pine Script strategy
Get the number of closed trades from a Pine Script strategy
Section titled “Get the number of closed trades from a Pine Script strategy”TL;DR
Trackstrategy.closedtradesso you know exactly how many trades have completed and can react when new ones close.
At a Glance
Section titled “At a Glance”| Difficulty | Beginner |
| Time to implement | 5-10 min |
| Category | Strategy Basics |
Quick Actions
Section titled “Quick Actions”Quick Start
Section titled “Quick Start”//@version=5strategy("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.")Why It Matters
Section titled “Why It Matters”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.
What You’ll Learn
Section titled “What You’ll Learn”- 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
Quick Reference
Section titled “Quick Reference”| Call | Purpose |
|---|---|
strategy.closedtrades | Returns the cumulative number of completed trades. |
strategy.closedtrades[1] | Previous bar’s total—use to detect newly closed trades. |
strategy.wintrades / strategy.losstrades | Split 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. |
Implementation Blueprint
Section titled “Implementation Blueprint”-
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 >= maxTradesstrategy.close_all("Trade limit hit") -
Detect a new closed trade
Compare current and previous values to trigger logic on closure.newTradeClosed = strategy.closedtrades > strategy.closedtrades[1]if newTradeClosedalert("New trade closed! Total trades: " + str.tostring(strategy.closedtrades)) -
Compute win rate using trade counts
Combinestrategy.closedtradeswith winning trade counts.winRate = strategy.closedtrades > 0? strategy.wintrades / strategy.closedtrades: naplot(winRate, "Win rate", color=color.green)
Example Playbook
Section titled “Example Playbook”//@version=5strategy("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 tradesnewClosed = 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))- 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.
Pro Tips & Pitfalls
Section titled “Pro Tips & Pitfalls”strategy.closedtradesresets 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.
Troubleshooting & FAQ
Section titled “Troubleshooting & FAQ”The count seems to skip values—why?
Section titled “The count seems to skip values—why?”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.
Key Takeaways
Section titled “Key Takeaways”strategy.closedtradesprovides 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.
Keep Going
Section titled “Keep Going”- Open AI Editor to apply the pattern with guided assistance
- Browse PineScript Examples for ready-to-run templates
- Connect to Live Trading when you are ready to automate
Adapted from tradingcode.net, optimised for Algo Trade Analytics users.