Overall Statistics
Total Trades
28
Average Win
1.05%
Average Loss
0%
Compounding Annual Return
-4.326%
Drawdown
2.600%
Expectancy
0
Net Profit
-1.468%
Sharpe Ratio
-1.446
Probabilistic Sharpe Ratio
7.534%
Loss Rate
0%
Win Rate
100%
Profit-Loss Ratio
0
Alpha
0.009
Beta
-0.131
Annual Standard Deviation
0.028
Annual Variance
0.001
Information Ratio
-2.037
Tracking Error
0.205
Treynor Ratio
0.31
Total Fees
$16.00
Estimated Strategy Capacity
$24000000.00
Lowest Capacity Asset
SPY XJOS49F1C606|SPY R735QTJ8XC9X
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities.Option;

namespace QuantConnect.Algorithm.CSharp
{
    public class SellOTMOptionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
    {
        private Symbol _optionSymbol;
        private Option _option;
        
        private readonly LocalOrderCollection1 _dailyOrders = new LocalOrderCollection1();


        public override void Initialize()
        {
            SetStartDate(2020, 08, 1);
            SetEndDate(2020, 11, 30);
            SetCash(1000000);

            //SetWarmUp(TimeSpan.FromSeconds(5));

            _option = AddOption("SPY", Resolution.Minute);
            _optionSymbol = _option.Symbol;

            //Set option contracts filter with the expiration date.
            //_option.SetFilter(-2,2,0 ,1);
            _option.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(2));

            // set the warm-up period for the pricing model
            SetWarmup(TimeSpan.FromDays(1));
            // set the benchmark to be the initial cash     
            //SetBenchmark(d => 1000000);

        }

        public override void OnData(Slice slice)
        {
            //For each day the trading should start from 09:01AM NY TIME. Default timezone is TimeZones.NewYork.
            if (Time.Hour < 9 && Time.Minute < 31) return;

            
            bool hasCallOptionOrderPlacedForTheDay = false;
            bool hasPutOptionOrderPlacedForTheDay = false;

            hasCallOptionOrderPlacedForTheDay = _dailyOrders.DoesOrderPlacedForTheDay(slice.Time, ContractType.Call);
            hasPutOptionOrderPlacedForTheDay = _dailyOrders.DoesOrderPlacedForTheDay(slice.Time, ContractType.Put);

            //If order placed for the today then leave.
            if (hasPutOptionOrderPlacedForTheDay && hasCallOptionOrderPlacedForTheDay) return;

            foreach (var sliceOptionChain in slice.OptionChains)
            {
                if (sliceOptionChain.Key != _optionSymbol) continue;

                OptionChain optionChain = sliceOptionChain.Value;

                #region For Call Contracts

                if (hasCallOptionOrderPlacedForTheDay == false)
                {
                    // find a nearest OTM call contract
                    var callContracts = optionChain
                        .Where(x => x.Right == OptionRight.Call &&
                            optionChain.Underlying.Price - x.Strike > 0.0m)
                        .OrderBy(x => x.Expiry).ToList();

                    if (!callContracts.Any()) continue;

                    Log($"Total call contract founds : {callContracts.Count}");
                    var callContract = callContracts.FirstOrDefault();

                    if (callContract != null)
                    {
                        HandleCallContract(callContract, slice, ContractType.Call);
                    }
                }
               

                #endregion

                #region For Put Contracts

                if (hasPutOptionOrderPlacedForTheDay == false)
                {
                    // find a nearest OTM put contract
                    var putContracts = optionChain
                        .Where(x => x.Right == OptionRight.Put &&
                            optionChain.Underlying.Price - x.Strike > 0.0m)
                        .OrderBy(x => x.Expiry).ToList();

                    if (!putContracts.Any()) continue;

                    Log($"Total put contract founds : {putContracts.Count}");
                    var putContract = putContracts.FirstOrDefault();

                    if (putContract != null)
                    {
                        HandleCallContract(putContract, slice, ContractType.Put);
                    }
                }
              
                #endregion
            }

        }

        private void HandleCallContract(OptionContract contract, Slice slice, ContractType type)
        {
            decimal callPrice = contract.Strike;
            decimal takeProfit = callPrice + 100; //callPrice * (1 + StopLossPercent); 
            decimal stopLoss = callPrice - 100; //callPrice * (1 - StopLossPercent);
            // Calculate quantity based on available cash
            var quantity = 1; //(int) (Portfolio.Cash / callPrice);

            var takeProfitOrderTicket = LimitOrder(contract.Symbol, quantity * -1, takeProfit);
            var stopLossOrderTicket = StopMarketOrder(contract.Symbol, quantity * -1, stopLoss);

            _dailyOrders.Add(new LocalOrder1(slice.Time, contract.Symbol, takeProfitOrderTicket, stopLossOrderTicket, type));


            Log($"{contract.Symbol.Value}," +
                $"Bid={contract.BidPrice.ToStringInvariant()} " +
                $"Ask={contract.AskPrice.ToStringInvariant()} " +
                $"Last={contract.LastPrice.ToStringInvariant()} " +
                $"Strike={contract.Strike.ToStringInvariant()} " +
                $"Volume={contract.Volume}" +
                $"Underlying Price = {contract.UnderlyingLastPrice.ToStringInvariant()} " +
                $"Contract Expiry={contract.Expiry}"
            );
        }
        
        public override void OnOrderEvent(OrderEvent orderEvent)
        {
            // Ignore OrderEvents that are not closed
            if (orderEvent != null && !orderEvent.Status.IsClosed())
            {
                return;
            }

            var filledOrderId = orderEvent.OrderId;

            var localOrder = _dailyOrders.GetLocalOrderByOrderId(filledOrderId);

            // If the ProfitTarget order was filled, close the StopLoss order
            if (localOrder != null && localOrder.TakeProfitOrderTicket.OrderId == filledOrderId)
            {
                localOrder.StopLossOrderTicket.Cancel();
            }

            // If the StopLoss order was filled, close the ProfitTarget
            if (localOrder != null && localOrder.StopLossOrderTicket.OrderId == filledOrderId)
            {
                localOrder.TakeProfitOrderTicket.Cancel();
            }
        }


        #region Implementation of IRegressionAlgorithmDefinition

        /// <summary>
        /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
        /// </summary>
        public bool CanRunLocally { get; } = true;

        /// <summary>
        /// This is used by the regression test system to indicate which languages this algorithm is written in.
        /// </summary>
        public Language[] Languages { get; } = { Language.CSharp };

        /// <summary>
        /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
        /// </summary>
        public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
        {
            {"Total Trades", "2"},
            {"Average Win", "0%"},
            {"Average Loss", "0%"},
            {"Compounding Annual Return", "0%"},
            {"Drawdown", "0%"},
            {"Expectancy", "0"},
            {"Net Profit", "0%"},
            {"Sharpe 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", "$2.00"},
            {"Estimated Strategy Capacity", "$6300000.00"},
            {"Lowest Capacity Asset", "GOOCV W723A0UB7HTY|GOOCV VP83T1ZUHROL"},
            {"Fitness Score", "0"},
            {"Kelly Criterion Estimate", "0"},
            {"Kelly Criterion Probability Value", "0"},
            {"Sortino Ratio", "0"},
            {"Return Over Maximum Drawdown", "0"},
            {"Portfolio Turnover", "0"},
            {"Total Insights Generated", "0"},
            {"Total Insights Closed", "0"},
            {"Total Insights Analysis Completed", "0"},
            {"Long Insight Count", "0"},
            {"Short Insight Count", "0"},
            {"Long/Short Ratio", "100%"},
            {"Estimated Monthly Alpha Value", "$0"},
            {"Total Accumulated Estimated Alpha Value", "$0"},
            {"Mean Population Estimated Insight Value", "$0"},
            {"Mean Population Direction", "0%"},
            {"Mean Population Magnitude", "0%"},
            {"Rolling Averaged Population Direction", "0%"},
            {"Rolling Averaged Population Magnitude", "0%"},
            {"OrderListHash", "38553a7723601f345ea373858ad7be0d"}
        };

        #endregion

    }


    public class LocalOrderCollection1 : List<LocalOrder1>
    {
        public bool DoesOrderPlacedForTheDay(DateTime dateTime, ContractType type)
        {
            var existingTrade = this.FirstOrDefault(t => t.TradeDateTime.Date.Equals(dateTime.Date) && t.ContractType == type);
            return existingTrade != null;
        }

        public LocalOrder1 GetLocalOrderByOrderId(int orderId)
        {
            return this.FirstOrDefault(o =>
                o.StopLossOrderTicket.OrderId == orderId || o.TakeProfitOrderTicket.OrderId == orderId);
        }
    }

    public enum ContractType
    {
        Put, Call
    }
    public class LocalOrder1
    {
        public LocalOrder1(DateTime tradeDateTime, Symbol optionContract, OrderTicket takeProfitOrderTicket, OrderTicket stopLossOrderTicket, ContractType contractType)
        {
            TradeDateTime = tradeDateTime;
            OptionContract = optionContract;
            TakeProfitOrderTicket = takeProfitOrderTicket;
            StopLossOrderTicket = stopLossOrderTicket;
            ContractType = contractType;
        }

        public DateTime TradeDateTime { get; }
        public Symbol OptionContract { get; }
        public OrderTicket TakeProfitOrderTicket { get; }
        public OrderTicket StopLossOrderTicket { get; }
        public ContractType ContractType { get; }
    }

}