Sidechair

strategy.closedtrades.entry_bar_index()

Browse the reference

The bar_index of the bar on which a closed trade's entry order filled.

Try it in the editor

strategy.closedtrades.entry_bar_index(trade_num) is the bar where the entry filled, which is normally the bar after the one whose close sent the order. With process_orders_on_close = true it is the same bar.

Subtract it from strategy.closedtrades.exit_bar_index to get the number of bars the trade was held.

Syntax

Pine Script
strategy.closedtrades.entry_bar_index(trade_num: series int) -> series int

Arguments

NameTypeDefaultDescription
trade_numseries intrequiredZero-based index of the closed trade. 0 is the first trade the strategy closed and strategy.closedtrades - 1 is the most recent.

Returns

series int: The bar_index of the bar the entry order filled on. na when the trade does not exist.

Remarks

  • Returns na when trade_num is negative, is not below strategy.closedtrades, or points at a trade that has dropped out of the history (see strategy.closedtrades.first_index).
  • The bar_index can be passed straight to drawing functions such as label.new and line.new as an x position.

Example

Pine ScriptAverage bars heldOpen in editor
//@version=6
strategy("Bars held", 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")
held = 0
for i = strategy.closedtrades.first_index to strategy.closedtrades - 1
    held += strategy.closedtrades.exit_bar_index(i) - strategy.closedtrades.entry_bar_index(i)
avg = strategy.closedtrades > 0 ? held / strategy.closedtrades : na
plot(avg, "Average bars held", color.orange)

See also

Runs on Sidechair