Hi All,

I am trying to get ATM option contracts which are closest to expiration. Where am I going wrong? Also how can I  change the nearest to 2 days before expiry?

Thanks


    def Initialize(self):
        self.SetStartDate(2022, 6, 1)  # Set Start Date
        self.SetEndDate(2022,6, 29) #Set End Date
        self.SetCash(500000)  # Set Strategy Cash
        self.Settings.FreePortfolioValuePercentage = 0.3 #Free portfolio percentage to avoid margin calls %
        option = self.AddOption("QQQ");
        option.SetFilter(-2, 2, timedelta(0), timedelta(182))
        
        self.oi_contract = None
        self.macd = None
        
        self.takeProfit = None
        self.stopLoss = None
      
    def OnData(self, slice):
        for chain in slice.OptionChains.Values:
            contracts = [contract for contract in chain.Value]
            if len(contracts) == 0:
                self.qqq_contract = None
                break
            
            contracts = sorted(sorted(chain, \
                           key = lambda x: abs(chain.Underlying.Price - x.Strike)), \
                           key = lambda x: x.Expiry, reverse=False)
            
            if self.qqq_contract is not None and contract.Symbol == self.qqq_contract.Symbol:
                break