Overall Statistics
class BasicTemplateOptionsAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2015, 12, 24)
        self.SetEndDate(2016, 1, 27)
        self.SetCash(100000)

        option = self.AddOption("GOOG")
        self.option_symbol = option.Symbol
        self.price_of_security_when_optioned_was_filled = 0

        # set our strike/expiry filter for this option chain
        option.SetFilter(-2, +2, timedelta(0), timedelta(180))

        # use the underlying equity as the benchmark
        self.AddEquity('GOOG', Resolution.Minute)
        self.equity_symbol = "GOOG"

    def OnData(self,slice):
        if self.Portfolio.Invested: return

        chain = slice.OptionChains.GetValue(self.option_symbol)
        if chain is None:
            return

        # we sort the contracts to find at the money (ATM) contract with farthest expiration
        contracts = sorted(sorted(sorted(chain, \
            key = lambda x: abs(chain.Underlying.Price - x.Strike)), \
            key = lambda x: x.Expiry, reverse=True), \
            key = lambda x: x.Right, reverse=True)
        
        
        # if found, trade it
        if len(contracts) == 0: return
        contract = contracts[0]
        self._buyTicket = self.Buy(contract.Symbol, 10)
        self.price_of_security_when_optioned_was_filled = contract.UnderlyingLastPrice
        self.ConditionalOrderFunction(contract)


    def ConditionalOrderFunction(self, optionContract):
        self.Log(f'Last GOOG Price: {self.Securities[self.equity_symbol].Price}')
        self.Log(f'Contract Underlying Price: {optionContract.UnderlyingLastPrice}')
        if (self.Securities[self.equity_symbol].Price  < self.price_of_security_when_optioned_was_filled):
            self._sellTicket = self.Sell(optionContract.Symbol, 10)
            self.Log(f'Close ticket opened for {optionContract.Symbol}')

    def OnOrderEvent(self, orderEvent):
        self.Log(str(orderEvent))