Overall Statistics
Total Orders
2
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Start Equity
100000
End Equity
99222
Net Profit
0%
Sharpe Ratio
0
Sortino Ratio
0
Probabilistic Sharpe Ratio
0%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
0
Tracking Error
0
Treynor Ratio
0
Total Fees
$1.00
Estimated Strategy Capacity
$180000.00
Lowest Capacity Asset
SPY Y05J8KTZA1K6|SPY R735QTJ8XC9X
Portfolio Turnover
38.80%
#region imports
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Globalization;
    using System.Drawing;
    using QuantConnect;
    using QuantConnect.Algorithm.Framework;
    using QuantConnect.Algorithm.Framework.Selection;
    using QuantConnect.Algorithm.Framework.Alphas;
    using QuantConnect.Algorithm.Framework.Portfolio;
    using QuantConnect.Algorithm.Framework.Execution;
    using QuantConnect.Algorithm.Framework.Risk;
    using QuantConnect.Parameters;
    using QuantConnect.Benchmarks;
    using QuantConnect.Brokerages;
    using QuantConnect.Util;
    using QuantConnect.Interfaces;
    using QuantConnect.Algorithm;
    using QuantConnect.Indicators;
    using QuantConnect.Data;
    using QuantConnect.Data.Consolidators;
    using QuantConnect.Data.Custom;
    using QuantConnect.DataSource;
    using QuantConnect.Data.Fundamental;
    using QuantConnect.Data.Market;
    using QuantConnect.Data.UniverseSelection;
    using QuantConnect.Notifications;
    using QuantConnect.Orders;
    using QuantConnect.Orders.Fees;
    using QuantConnect.Orders.Fills;
    using QuantConnect.Orders.Slippage;
    using QuantConnect.Scheduling;
    using QuantConnect.Securities;
    using QuantConnect.Securities.Equity;
    using QuantConnect.Securities.Future;
    using QuantConnect.Securities.Option;
    using QuantConnect.Securities.Forex;
    using QuantConnect.Securities.Crypto;   
    using QuantConnect.Securities.Interfaces;
    using QuantConnect.Storage;
    using QuantConnect.Data.Custom.AlphaStreams;
    using QCAlgorithmFramework = QuantConnect.Algorithm.QCAlgorithm;
    using QCAlgorithmFrameworkBridge = QuantConnect.Algorithm.QCAlgorithm;
    using QuantConnect.Orders.OptionExercise;
    using static QuantConnect.Extensions;
#endregion
namespace QuantConnect.Algorithm.CSharp
{
    public class CustomExerciseModelAlgorithm : QCAlgorithm
    {
        private Symbol _optionSymbol;
        public override void Initialize()
        {
            SetStartDate(2022, 7, 1);
            SetEndDate(2022, 7, 10);
            SetCash(100000);
            SetSecurityInitializer(new MySecurityInitializer(this));
            var option = AddOption("SPY");
            _optionSymbol = option.Symbol;
        }

        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// Slice object keyed by symbol containing the stock data
        public override void OnData(Slice data)
        {
            if (Portfolio.Invested)
            {
                return;
            }
            if (data.OptionChains.TryGetValue(_optionSymbol, out var chain))
            {
                var contract = chain
                    .Where(x => x.Right == OptionRight.Call)
                    .OrderBy(x => x.Strike)
                    .FirstOrDefault();

                MarketOrder(contract.Symbol, 1);
                ExerciseOption(contract.Symbol, 1);
                Quit();
            }
        }
    }

    public class MySecurityInitializer : BrokerageModelSecurityInitializer
    {
        private readonly QCAlgorithm _algorithm;
        public MySecurityInitializer(QCAlgorithm algorithm)
            : base(algorithm.BrokerageModel, new FuncSecuritySeeder(algorithm.GetLastKnownPrices))
        {
            _algorithm = algorithm;
        }

        public override void Initialize(Security security)
        {
            base.Initialize(security);

            if (security.Type == SecurityType.Option)
            {
                (security as Option).SetOptionExerciseModel(new MyOptionExerciseModel(_algorithm));
            }
        }
    }

    public class MyOptionExerciseModel : IOptionExerciseModel
    {
        private readonly QCAlgorithm _algorithm;
        public MyOptionExerciseModel(QCAlgorithm algorithm) => _algorithm = algorithm;

        public IEnumerable<OrderEvent> OptionExercise(Option option, OptionExerciseOrder order)
        {
            var underlying = option.Underlying;
            var utcTime = option.LocalTime.ConvertToUtc(option.Exchange.TimeZone);

            var inTheMoney = option.IsAutoExercised(underlying.Close);
            var isAssignment = inTheMoney && option.Holdings.IsShort;

            yield return new OrderEvent(
                order.Id,
                option.Symbol,
                utcTime,
                OrderStatus.Filled,
                GetOrderDirection(order.Quantity),
                0.0m,
                order.Quantity,
                OrderFee.Zero,
                Messages.DefaultExerciseModel.ContractHoldingsAdjustmentFillTag(inTheMoney, isAssignment, option)
            )
            {
                IsAssignment = isAssignment,
                IsInTheMoney = inTheMoney
            };

            if (inTheMoney && option.ExerciseSettlement == SettlementType.PhysicalDelivery)
            {
                var exerciseQuantity = option.GetExerciseQuantity(order.Quantity);

                yield return new OrderEvent(
                    order.Id,
                    underlying.Symbol,
                    utcTime,
                    OrderStatus.Filled,
                    GetOrderDirection(exerciseQuantity),
                    option.StrikePrice,
                    exerciseQuantity,
                    OrderFee.Zero,
                    isAssignment ? Messages.DefaultExerciseModel.OptionAssignment : Messages.DefaultExerciseModel.OptionExercise
                ) { IsInTheMoney = true };
            }
        }
    }
}