I'm trying to backtest a simple strategy that purchases ATM SPXW Calls 5 minutes prior to close and holds into expiry but I am having some difficulties navigating the API with options.

So far I have just pieced together this code with the other examples of weekly options on the forum and with the  options API example in the Learning Center Articles but it seems to not actually purchase any options.

From the learning center https://www.quantconnect.com/learning/articles/introduction-to-options/quantconnect-options-api. When I add this block of code for purchasing contracts after sorting for ATM contracts in the OnData method I get a continue not used properly in loop error.

if len(contracts) == 0: continue
# trade the contracts with the farthest expiration
symbol = contracts[0].Symbol
self.MarketOrder(symbol, 1)
self.MarketOnCloseOrder(symbol, -1)

Without the loop I would still expect that one contract would be purchased within my single backtest day however none are ever purchased.

 

The full code looks like this

def Initialize(self):
        self.SetStartDate(2023, 7, 14)  # Set Start Date
        self.SetCash(100000)  # Set Strategy Cash

        underlying = self.AddIndex("SPX", Resolution.Minute)
        options = self.AddIndexOption(underlying.Symbol, "SPXW", Resolution.Minute)
        options.SetFilter(lambda u: u.WeeklysOnly().Strikes(-1,1).Expiration(0,1))
        self.symbol = options.Symbol
        

    def OnData(self, data: Slice):
        chain = slice.OptionChains.get(self.symbol)
        if chain:
            #self.log(f"underlying price: {chain.Underlying.Price}")
            #df=pd.DataFrame([[x.Right,x.Strike,x.Expiry,x.BidPrice,x.AskPrice] for x in chain],
            #    index=[x.Symbol.Value for x in chain],
            #    columns=['type)call 0, put1)', 'strike', 'expiry', 'ask price', 'bid price'])
            #self.Log(str(df))
            call = [x for x in chain if x.Right == OptionRight.Call]
            put = [x for x in chain if x.Right == OptionRight.Put]
            #Choos ATM Call contracts
            contracts = sorted(chain, key = lambda x: abs(x.UnderlyingLastPrice - x.Strike))[0]
        
        #if len(contracts) == 0: continue
        # trade the contracts with the farthest expiration
        symbol = contracts[0].Symbol
        self.MarketOrder(symbol, 1)

    def OnOrderEvent(self, orderEvent):
        self.log()

 

I am still getting used to using Quant Connect so I'm sure it is something really obvious that I am doing wrong.  Appreciate any advice!