How to close current position at the end of backtest?
When it calls next() how to know if the current data is the last bar is my question. Eventually, I want to sell what I have at the end of backtesting.
I am very very new to backtrader, but from my understanding you add a stop method (https://www.backtrader.com/docu/strategy.html?highlight=stop#backtrader.Strategy.stop) to your strategy where you close the position.
without having tried it, the below should do the trick:
def stop(self): targetsize = 0 self.order = self.order_target_size(target=targetsize)
That depends on how the data feed is loaded. If the data feed is not preloaded, the platform cannot know when it will be the last bar, it will simply happen and it will then be too late for you close your position.
If you preload your data, you can check that this equality is
len(self.data) == self.data.buflen()
If you have multiple data feeds, you would need then to check it for all of them.