For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:

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
    def stop(self):
    i = list(range(0, len(self.datas)))
    for (d,j) in zip(self.datas,i):
    close = self.close(d,exectype=bt.Order.Market)
    print("Backtesting completed")

    self.close function does return the following:
    Ref: 92
    OrdType: 0
    OrdType: Buy
    Status: 1
    Status: Submitted
    Size: 10
    Price: None
    Price Limit: None
    TrailAmount: None
    TrailPercent: None
    ExecType: 0
    ExecType: Market
    CommInfo: None
    End of Session: 736088.9999999999
    Info: AutoOrderedDict()
    Broker: None
    Alive: True

    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

  • administrators

    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 stop method 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)

    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.

  • administrators


    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):

  • administrators

    You issued the order one bar in advance. That works with preloaded data feeds (because buflen returns the length of what has been preloaded), but not all data feeds have to be preload-able

Log in to reply