backtesting.py icon indicating copy to clipboard operation
backtesting.py copied to clipboard

How to close on session end

Open ironhak opened this issue 5 months ago • 1 comments

Hello!

Let's say I'm backtesting futures, and the session ends every day at 16:00 and it starts again at 17:00. What if I want to close a trade at session close?

I can't do like if self.data.df.index.time == "16:00": self.position.close() otherwise the closing order will be executed at next bar, that would be the first bar of the new session.

I know I could close at one bar prior to the close, but I specifically need to close the trade at closing price of 16:00 bar for reproducibility reasons with another platform.

Also I'm aware of trade_on_close, but I still need trades to be opened at next bar open.

Any idea? Thanks

ironhak avatar Jul 20 '25 08:07 ironhak

A little hacky but should do the trick

self._broker._close_trade(self.trades[-1], self.data.Close[-1],self.data.__len__()-1)

ironhak avatar Jul 20 '25 10:07 ironhak