I would like to find option contract inside OnData method and buy option contract I filter.

I know I can use self.AddOption, but I don't want to use it because in my original algo I have big universe and I need options data only on very few bars when I want to buy options contract.

I saw I can use self.OptionChainProvder method to get options data, but it seems the data is not loaded, because when I want to buy it (with MarketOrder), I get an error:

Runtime Error: This asset symbol (AAPL XL7X5HFSCR5Y|AAPL R735QTJ8XC9X) was not found in your security list. Please add this security or check it exists before using it with 'Securities.ContainsKey("AAPL XL7X5HFSCR5Y|AAPL R735QTJ8XC9X")' in SecurityManager.cs:line 254 (Open Stack Trace)

 

Here is the code :

# region imports
from AlgorithmImports import *
# endregion

class WellDressedSkyBlueScorpion(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2020, 12, 29)  # Set Start Date
        self.SetCash(100000)  # Set Strategy Cash
        self.symbol = self.AddEquity("AAPL", Resolution.Minute).Symbol


    def OnData(self, data: Slice):
        
        if not self.Portfolio.Invested:

            # get options data
            contracts = self.OptionChainProvider.GetOptionContractList(self.symbol, self.Time)
            
            # selects the type of option to be Call contract, then selects all contracts that meet our expiration criteria
            uppertargetStrike = (data[self.symbol].Close * (1 + 0.02))
            minContractExpiry = 10
            maxContractExpiry = 90
            call = [x for x in contracts if x.ID.OptionRight == OptionRight.Call and \
                                            x.ID.StrikePrice > uppertargetStrike and \
                                            minContractExpiry < (x.ID.Date - self.Time).days <= maxContractExpiry] # expiration not longer than 30 days
            if not call: return

            # sorts contracts by closet expiring date and closest strike price (sorts in ascending order)
            call = sorted(sorted(call, key = lambda x: x.ID.Date), key = lambda x: x.ID.StrikePrice)
            if len(call) == 0: return

            # order
            self.MarketOrder(call[0], 10)