Overall Statistics
Total Trades
4
Average Win
0.55%
Average Loss
0%
Compounding Annual Return
-40.826%
Drawdown
22.000%
Expectancy
0
Net Profit
-12.267%
Sharpe Ratio
-1.582
Probabilistic Sharpe Ratio
6.429%
Loss Rate
0%
Win Rate
100%
Profit-Loss Ratio
0
Alpha
-0.316
Beta
-0.408
Annual Standard Deviation
0.238
Annual Variance
0.057
Information Ratio
-1.439
Tracking Error
0.363
Treynor Ratio
0.923
Total Fees
$2.00
Estimated Strategy Capacity
$45000000.00
Lowest Capacity Asset
TSLA UNU3P8Y3WFAD
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Securities.Option;

namespace QuantConnect.Algorithm.CSharp
{
    public class SellATMOptionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
    {
        private Symbol _optionSymbol;
        private Option _option;
        const decimal StopLossPercent = 0.05m;
        
        private readonly LocalOrderCollection _dailyOrders = new LocalOrderCollection();
         
        
        public override void Initialize()
        {
            SetStartDate(2020, 09, 1);
            SetEndDate(2020, 11, 30);
            SetCash(100000);

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

            _option = AddOption("TSLA", 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;

            //if (Portfolio.Invested)
            //{
            //    return;
            //}

            if (_dailyOrders.DoesOrderPlacedForTheDay(slice.Time)) return;

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

                OptionChain optionChain = sliceOptionChain.Value;

                // find a nearest ATM call contract
                var contracts = optionChain
                    .Where(x => x.Right == OptionRight.Call &&
                        optionChain.Underlying.Price - x.Strike == 0.0m)
                    .OrderBy(x => x.Expiry).ToList();

                if (!contracts.Any()) continue;

                Log($"Total contract founds : {contracts.Count}");
                var contract = contracts.FirstOrDefault();
                
                if (contract != null)
                {
                    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 LocalOrder(slice.Time, contract.Symbol, takeProfitOrderTicket, stopLossOrderTicket));
                     

                    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 LocalOrderCollection : List<LocalOrder>
    {
        public bool DoesOrderPlacedForTheDay(DateTime dateTime)
        {
            var existingTrade = this.FirstOrDefault(t => t.TradeDateTime.Date.Equals(dateTime.Date));
            return existingTrade != null;
        }
        
        public LocalOrder GetLocalOrderByOrderId(int orderId)
        {
            return this.FirstOrDefault(o =>
                o.StopLossOrderTicket.OrderId == orderId || o.TakeProfitOrderTicket.OrderId == orderId);
        }
    }

    public class LocalOrder
    {
        public LocalOrder(DateTime tradeDateTime, Symbol optionContract, OrderTicket takeProfitOrderTicket, OrderTicket stopLossOrderTicket)
        {
            TradeDateTime = tradeDateTime;
            OptionContract = optionContract;
            TakeProfitOrderTicket = takeProfitOrderTicket;
            StopLossOrderTicket = stopLossOrderTicket;
        }

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

}