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

Determining how long orders have been open to record



  • Evening,

    I was wondering if anybody had worked out how to count the number of bars, for example, an order is open and then be able to access that in the main body of the script. In essence, so I could run the Cerebro instance and be able to export the average length of time of each order.

    I have seen some interesting ideas of pulling that information from the broker, but for the moment I am just backtesting ideas (as such, no broker to pull from). I have tried to create a list, append self(len) type things to the list but I am struggling to append a variable for each order to a list and then calculate the values as a result of the list.



  • @elliotp I would also be interested to know what is the most backtrader-y way to do this, but if it were me, I would just write the datetime to a csv or a pickle when a trade is opened and then write another datetime when the trade is closed.



  • This is what I've used, @backtrader shared this approach in the sample codes but I can't find it now.

    ...
        def notify_order(self, order):
    
            if order.status in [order.Completed, order.Margin]:
                
                # keep order execution bar
                self.bar_executed = len(self)
    
    ...
    
        def next(self):
    
                pos_length = len(self) - self.bar_executed + 1
    
    ....

  • administrators

    As posted by @ab_trader the best way, imho, is to keep track of the length of the strategy, which indicates how many bars have been processed.



  • @backtrader Smart man, thank you