Number of bars for open trades in backtest

Hi!

I am experiencing that for open positions at the end of backtest, column "# bars" in backtest output (and also trade.BarsInTrade in CBT) always gives 1 more than what I would expect. For closed trades it does not.

For closed trades, "BarsInTrade" matches "Lookup(BarIndex(), trade.ExitDateTime) - Lookup(BarIndex(), trade.EntryDateTime)", but for open positions, "BarsInTrade" gives 1 more. I would expect them to be the same.

What am I missing? Is there a setting that this calculation depends on?
See a test code below.
Thanks

SetCustomBacktestProc("");

function metrics(trade)
{
	trade.AddCustomMetric("BarsInTrade", trade.BarsInTrade + 1);
	trade.AddCustomMetric("Exit - Entry", Lookup(BarIndex(), trade.ExitDateTime) - Lookup(BarIndex(), trade.EntryDateTime) + 1);
}

if (Status("action") == actionPortfolio)
{
    bo = GetBacktesterObject();
    bo.Backtest(True);
    
    for (trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade())
    {
        metrics(trade);
    }

    for (trade = bo.GetFirstOpenPos(); trade; trade = bo.GetNextOpenPos())
    {
        metrics(trade);
    }

    bo.ListTrades();
}

Buy = Cross(MACD(), Signal());
Sell = Cross(Signal(), MACD());

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.