Sidechair

strategy.closedtrades.first_index

Browse the reference

The index of the oldest closed trade still held in the trade list; the first valid trade_num for the closed-trade functions.

Try it in the editor

strategy.closedtrades.first_index is a series int. Standard Pine remembers at most 9000 closed trades. When a new trade closes beyond that limit, the oldest one is dropped, and first_index moves up by one.

Loop from first_index to strategy.closedtrades - 1 to visit every trade you can still read. Until the limit is reached, first_index is 0 and the loop starts at the first trade.

Type

series int

Remarks

  • Index 0 stays the first trade the strategy ever closed even after it drops out; reading it then returns na. That is why a plain loop from 0 breaks on long histories.
  • Only strategies with a very large trade count ever see first_index above 0.

Example

Pine ScriptSum profit over the readable tradesOpen in editor
//@version=6
strategy("Readable trade profit", overlay = false)
fast = ta.sma(close, 10)
slow = ta.sma(close, 30)
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long)
if ta.crossunder(fast, slow)
    strategy.close("Long")
total = 0.0
for i = strategy.closedtrades.first_index to strategy.closedtrades - 1
    total += strategy.closedtrades.profit(i)
plot(total, "Profit of kept trades", color.green)

See also

Runs on Sidechair