Howwise RSS
Trading Software7 min read

Backtrader Close Position at End of Backtest: Working Fixes

Short answer

To make Backtrader close position at the end of a backtest, send self.close() on the second-to-last bar (len(data) == data.buflen() - 1) or enable cheat-on-close. stop() runs too late, because no more bars are processed.

Key takeaways
  • Backtrader never liquidates at the end of data: the final position stays open and broker.getvalue() marks it at the last close as unrealised P&L.
  • TradeAnalyzer reports a still-open trade only under total.open, so it is missing from total.closed, won/lost, streaks and averages.
  • self.close() inside stop() creates an order that is never processed, so it cannot fix the trade log.
  • Closing when len(data) == data.buflen() - 1 fills at the last bar's open, and this is the fix that does not change any other fills.
  • Cheat-on-close (broker.set_coc(True)) lets a last-bar close() fill, but it changes fills for every market order in the run.

Why does Backtrader leave the last position open?

Backtrader is an event loop over bars. When the feed is exhausted, cerebro.run() stops iterating and nothing liquidates the book. Whatever you hold on the last bar is simply still held, so any Backtrader close position logic has to run before the data ends.

The broker's final value, broker.getvalue(), is cash plus open positions marked at the last close. That profit or loss is unrealised. It sits in equity, but it is not a closed trade, so nothing that is built from closed trades will see it.

The usual symptoms all come from this one mismatch between an equity view and a closed-trade view.

SymptomCauseFix
Final trade missing from the trade lognotify_trade never fires with isclosed for itClose before the data ends
total.closed is lower than the number of entriesThe last trade is counted under total.openClose on buflen() - 1, or add the open P&L manually
Final equity differs from start cash plus summed closed PnLOpen position is marked to marketClose it, then compare again
close() on the last bar does nothingMarket orders fill at the next bar's open, which does not existSend it one bar earlier, or use cheat-on-close

How do TradeAnalyzer and notify_trade treat an open trade?

TradeAnalyzer builds its won/lost, streak, length and PnL statistics only when a trade closes. An open trade is counted in total.total and total.open, and nowhere else. If nothing is open at the end, the open key is typically absent, so read it defensively.

notify_trade works the same way. It is called when a trade opens (trade.isopen) and when it closes (trade.isclosed). With an open position at the end of data, the closing call never comes, so a log that prints only closed trades omits it.

import backtrader as bt

class S(bt.Strategy):
    def notify_trade(self, trade):
        if trade.isclosed:
            print('CLOSED', trade.pnl, trade.pnlcomm)  # gross, net of commission
        elif trade.isopen:
            print('OPEN  ', trade.price, trade.size)

# after cerebro.run():
# strat = results[0]
# ta = strat.analyzers.ta.get_analysis()
# closed = ta.total.get('closed', 0)
# opened = ta.total.get('open', 0)
# print(ta.total.total, closed, opened)
# won = ta.get('won', {}).get('total', 0)   # 'won' is absent if no trade closed
Tip: Register the analyzer with cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='ta'). The result is a nested dict-like object, so test for keys before indexing.

Why can't stop() close the position?

stop() is called once, after the last bar has been processed. self.close() there only creates an order object and hands it to the broker. The broker executes orders while processing a bar, and no further bars come, so the order stays pending and nothing is recorded.

The trade log, TradeAnalyzer and equity are therefore unchanged. stop() is still the right place for read-only end-of-run work: logging broker.getvalue(), computing the open-position P&L, and warning about a leftover position.

def stop(self):
    pos = self.position
    if pos.size:
        # pos.price is the average entry price
        unreal = (self.data.close[0] - pos.price) * pos.size
        print(f'WARNING: open position {pos.size} @ {pos.price:.4f}, '
              f'unrealised PnL {unreal:.2f}')
    print('Final value', self.broker.getvalue())
Warning: Do not put self.close() in stop() and assume the trade log is fixed. It looks correct in the code and silently does nothing to the results.

Which fix makes Backtrader close position on the last bar?

By default a market order sent in next() on bar N fills at the open of bar N+1. On the last bar there is no N+1, so the order never fills. The reliable approach is to send the close one bar earlier, when len(self.data) == self.data.buflen() - 1. It then fills at the last bar's open.

Last-bar detection with buflen() works with preloaded data (the default preload=True). It does not work with live feeds or preload=False, because the total length is not known in advance. In those cases compare self.datas[0].datetime.date(0) with a known end date instead.

Cheat-on-close makes market orders fill at the current bar's close. Call cerebro.broker.set_coc(True) before cerebro.run(). It is not cheat_on_open, which is a separate feature that lets next_open() act on the open before the bar completes.

OptionTrade logTradeAnalyzerFill priceSide effects
close() in stop()UnchangedStill total.openNone, never fillsNone
close() on the last bar, default brokerUnchangedStill total.openNone, never fillsNone
close() on buflen() - 1Closed trade recordedCounted in total.closedLast bar's openEquity differs slightly from the last-close mark
set_coc(True) and close() on the last barClosed trade recordedCounted in total.closedLast bar's closeChanges fills of every market order; optimistic, since you act on a price you could not know
def next(self):
    if len(self.data) == self.data.buflen() - 1 and self.position:
        self.close()   # fills at the open of the final bar
        return
    # ... normal logic ...
Warning: With cheat-on-close the close of the current bar is used for signals and fills at once. Every entry and exit in the run becomes more optimistic, so do not enable it just to fix the final trade.

What does a copy-paste CloseAtEnd mixin look like?

The mixin below closes every data feed on its own second-to-last bar. It checks each feed's own length, so a feed with shorter history is closed when that feed is about to end, not when the longest one ends. It also exposes a flag so your entry logic can stop opening new trades.

The test builds synthetic bars, enters every 10 bars and exits 5 bars later. The last entry on bar 100 would remain open to bar 103. Without the mixin the analyzer shows 9 closed and 1 open. With it, closed trades equal entries sent.

import numpy as np, pandas as pd, backtrader as bt

class CloseAtEnd:
    """List before bt.Strategy. Call self.close_at_end() first in next()."""
    def close_at_end(self):
        if not hasattr(self, '_ce_sent'):
            self._ce_sent = set()
        ending = False
        for d in self.datas:
            if len(d) >= d.buflen() - 1:      # this feed's own end
                ending = True
                if self.getposition(d).size and d not in self._ce_sent:
                    self.close(data=d)
                    self._ce_sent.add(d)
        return ending                          # True: do not open new trades

class S(CloseAtEnd, bt.Strategy):
    params = dict(use_close=True)
    def __init__(self):
        self.entries = 0
    def next(self):
        if self.p.use_close and self.close_at_end():
            return
        n = len(self.data)
        if not self.position and n % 10 == 0:
            self.buy(); self.entries += 1
        elif self.position and n % 10 == 5:
            self.sell()
    def stop(self):
        if self.p.use_close:
            assert self.position.size == 0

def run(use_close):
    n = 103
    idx = pd.date_range('2020-01-01', periods=n, freq='D')
    px = 100 + np.cumsum(np.random.default_rng(1).normal(0, 1, n))
    df = pd.DataFrame({'open': px, 'high': px + 1, 'low': px - 1,
                       'close': px, 'volume': 1000}, index=idx)
    c = bt.Cerebro()
    c.adddata(bt.feeds.PandasData(dataname=df))
    c.addstrategy(S, use_close=use_close)
    c.addanalyzer(bt.analyzers.TradeAnalyzer, _name='ta')
    c.broker.setcash(10000); c.broker.setcommission(commission=0.001)
    s = c.run()[0]
    ta = s.analyzers.ta.get_analysis()
    return s.entries, ta.total.get('closed', 0), ta.total.get('open', 0)

print('before', run(False))   # entries, closed, open -> 10, 9, 1
print('after ', run(True))    # -> 10, 10, 0
assert run(True)[0] == run(True)[1]
Tip: The mixin must come before bt.Strategy in the class bases. It adds a plain helper method rather than overriding next(), which avoids surprises with Backtrader's metaclass.

How do I verify the trade log, analyzers and equity agree?

Once everything is closed, equity is cash only, so it should equal starting cash plus the sum of closed net PnL. Net means after commission, which is trade.pnlcomm and ta.pnl.net.total. Gross PnL will not reconcile when a commission is set, and that includes the commission on the closing order.

Closing at buflen() - 1 books the exit at the last bar's open, so final equity differs from the old last-close mark by that open-to-close move plus the closing commission. Only with cheat-on-close does the exit price match the old mark, apart from commission. A difference is not a bug, but an unexplained one is.

  1. Assert self.position.size == 0 in stop() for every data feed.
  2. Read ta.total.get('open', 0) and assert it is 0 or absent.
  3. Assert ta.total.closed equals the number of entries you sent.
  4. Compare broker.getvalue() with startcash + ta.pnl.net.total using a tolerance such as abs(a - b) < 1e-6.
  5. If you keep an open position on purpose, report closed-trade stats and equity separately, and add the open P&L manually.
ta = strat.analyzers.ta.get_analysis()
net = ta.pnl.net.total if 'pnl' in ta else 0.0
assert ta.total.get('open', 0) == 0
assert abs(cerebro.broker.getvalue() - (10000 + net)) < 1e-6

What are the common mistakes with closing at the end?

Using exitbars or a timer for the final exit assumes a fixed holding period, so it misses whenever the entry is late. Only the data length tells you where the end is.

Expecting runonce to change the trade log is another one. runonce affects how indicators are computed, not how orders and trades are processed. The tradehistory option is likewise only extra per-trade history, and it does not close anything.

With resampled data, the last bar can be partial, for example an incomplete week or hour. Closing on its open then uses a price that does not represent a full period, so check that the final bar is complete.

Finally, ignoring the commission on the closing order makes equity checks fail by a small amount. Also remember that with several feeds the shortest one ends early, so its position must be closed on its own buflen() - 1, not the master clock's.

Common questions

Why is the last bar not executed in Backtrader?

Orders sent in next() fill at the next bar's open, so an order created on the last bar has nothing to fill against. The strategy runs on the last bar, but its orders never execute. Send them one bar earlier or use cheat-on-close.

Can I see open trades in the trade log or observers?

Yes, but not as closed trades. The Trades observer plots only closed trade PnL, and notify_trade reports the open state only when the trade opens. To see the open P&L, compute it from self.position and the last close, or compare equity with the closed-trade sum.

Does Cerebro's broker value include the open position?

Yes. broker.getvalue() returns cash plus the market value of open positions marked at the latest close. That is why equity can look right while closed-trade statistics look wrong.

Does set_coc(True) work if I call it after cerebro.run()?

No. It has to be set before run(), either through cerebro.broker.set_coc(True) or the coc parameter of the broker. It then applies to all market orders in that run, not just the final one.

How do I close all positions on the last bar with several data feeds?

Loop over self.datas and test each feed's own len(d) against d.buflen() - 1. Call self.close(data=d) for each feed that still has a position. Feeds with shorter history reach their end earlier, so they close earlier.

Related topics:backtraderbacktestingtradeanalyzerpythontrade-log