Trying to close all open position after last call made to next function
I am trying to close all open positions after last iteration call is made to next function -
Below in the stop function i am calling self.close function to close all open positions
i = list(range(0, len(self.datas)))
for (d,j) in zip(self.datas,i):
close = self.close(d,exectype=bt.Order.Market)
self.close function does return the following:
Price Limit: None
End of Session: 736088.9999999999
But the last close transaction is not captured by the bt.analyzers.Transactions. When i print the Transactions capture by the analyzer it doesn't show the last transaction which was closed by self.close().
Please advise. Thanks
The first advice (following the please advise) is to use (as seen at the top) the
3-backtick marks to format your code block and output. Else all formatting is gone and it is unreadable.
In any case when your strategy
stopmethod is called it is called to let you know that the system is stopping. There is no more data and nothing can be done with regards to closing positions.
I have added the self.close(d,exectype=bt.Order.Market) in the next function as below.
def next(self): i = list(range(0, len(self.datas))) for (d,j) in zip(self.datas,i): if len(d) == d.buflen(): close = self.close(d,exectype=bt.Order.Market) print(close)
Also i am check if the last bar was executed by comparing len() and buflen(). print(close) shows that orders were submitted but trade did not happen.
Because there is no further iteration as explained above. There is no more data to consume and no further operations take place.
Thanks @backtrader , i was able to close all open positions.
Changed condition to
if len(d) == (d.buflen()-1):
You issued the order one bar in advance. That works with preloaded data feeds (because
buflenreturns the length of what has been preloaded), but not all data feeds have to be