Lean  $LEAN_TAG$
OptionPortfolioModel.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using QuantConnect.Orders;
17 
19 {
20  /// <summary>
21  /// Provides an implementation of <see cref="ISecurityPortfolioModel"/> for options that supports
22  /// default fills as well as option exercising.
23  /// </summary>
25  {
26  /// <summary>
27  /// Performs application of an OrderEvent to the portfolio
28  /// </summary>
29  /// <param name="portfolio">The algorithm's portfolio</param>
30  /// <param name="security">Option security</param>
31  /// <param name="fill">The order event fill object to be applied</param>
32  public override void ProcessFill(SecurityPortfolioManager portfolio, Security security, OrderEvent fill)
33  {
34  if (fill.Ticket.OrderType == OrderType.OptionExercise)
35  {
36  base.ProcessFill(portfolio, portfolio.Securities[fill.Symbol], fill);
37  }
38  else
39  {
40  // we delegate the call to the base class (default behavior)
41  base.ProcessFill(portfolio, security, fill);
42  }
43  }
44 
45  /// <summary>
46  /// Helper method to determine the close trade profit
47  /// </summary>
48  /// <remarks>For SettlementType.Cash we apply funds and add in the result to the profit</remarks>
50  {
51  var baseResult = base.ProcessCloseTradeProfit(portfolio, security, fill);
52 
53  var ticket = fill.Ticket;
54  if (ticket.OrderType == OrderType.OptionExercise && security.Symbol.SecurityType.IsOption())
55  {
56  var option = (Option)security;
57  if (option.ExerciseSettlement == SettlementType.Cash)
58  {
59  var underlying = option.Underlying;
60  var optionQuantity = fill.Ticket.Quantity;
61  var cashQuantity = -option.GetIntrinsicValue(underlying.Close) * option.ContractUnitOfTrade * optionQuantity;
62  if (cashQuantity != decimal.Zero)
63  {
64  security.SettlementModel.ApplyFunds(new ApplyFundsSettlementModelParameters(portfolio, security, fill.UtcTime, new CashAmount(cashQuantity, option.QuoteCurrency.Symbol), fill));
65  return new ConvertibleCashAmount(cashQuantity + baseResult.Amount, option.QuoteCurrency);
66  }
67  }
68  }
69  return baseResult;
70  }
71  }
72 }