Check Hold Period



  • Hi,

    How can I check how long a stock has been held for?

    I tried: len(self.broker.getposition(d)) however this doesn't appear to give the hold days...

    Thanks!



  • @cwse I've done the following to accomplish this.

    In notify_trade()

    def notify_trade(self, trade):
        self.htrade = trade
    

    In next()

    self.maxdays = ((self.data0.datetime.datetime()
                     - self.htrade.open_datetime()).days) >= self.p.limitdays
    


  • I am using code snippet from examples:

    In notify_order():

    if order.status in [order.Completed, order.Margin]:
        self.bar_executed = len(self)
    

    In next():

    if self.position:
        pos_length = len(self) - self.bar_executed + 1
    

  • administrators

    Trade instances carries an attribute which can help:

    • baropen

    Which records the length of the data when opening happens from the point of view of the strategy (len(self.data))

    Checking the difference between trade.baropen and the current length of the data len(self.data) gives the holding period.



  • Thanks everyone!


Log in to reply
 

Looks like your connection to Backtrader Community was lost, please wait while we try to reconnect.