Sidechair

strategy.opentrades.entry_bar_index()

Browse the reference

The bar_index of the bar on which an open trade's entry order filled.

Try it in the editor

strategy.opentrades.entry_bar_index(trade_num) is the bar where the entry filled, normally the bar after the one that sent the order.

bar_index - strategy.opentrades.entry_bar_index(0) counts how many bars the oldest open trade has been held, a common input for a time stop.

Syntax

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

Arguments

NameTypeDefaultDescription
trade_numseries intrequiredZero-based index of the open trade. 0 is the oldest open entry, the one a FIFO exit closes first, and strategy.opentrades - 1 is the newest.

Returns

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

Remarks

  • Returns na when trade_num is negative or is not below strategy.opentrades, so guard every call with the open-trade count.

Example

Pine ScriptTime stop after 20 barsOpen in editor
//@version=6
strategy("Time stop", overlay = true)
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")
age = strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(0) : na
if age >= 20
    strategy.close("Long", comment = "time stop")
plot(age, "Bars held", color.gray, display = display.data_window)

See also

Runs on Sidechair