Lean  $LEAN_TAG$
AbsoluteRiskOptionPositionCollectionEnumerator.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 System;
17 using System.Collections.Generic;
18 
20 {
21  /// <summary>
22  /// Stub class providing an idea towards an optimal <see cref="IOptionPositionCollectionEnumerator"/> implementation
23  /// that still needs to be implemented.
24  /// </summary>
26  {
27  private readonly Func<Symbol, decimal> _marketPriceProvider;
28 
29  /// <summary>
30  /// Intializes a new instance of the <see cref="AbsoluteRiskOptionPositionCollectionEnumerator"/> class
31  /// </summary>
32  /// <param name="marketPriceProvider">Function providing the current market price for a provided symbol</param>
33  public AbsoluteRiskOptionPositionCollectionEnumerator(Func<Symbol, decimal> marketPriceProvider)
34  {
35  _marketPriceProvider = marketPriceProvider;
36  }
37 
38  /// <summary>
39  /// Enumerates the provided <paramref name="positions"/>. Positions enumerated first are more
40  /// likely to be matched than those appearing later in the enumeration.
41  /// </summary>
42  public IEnumerable<OptionPosition> Enumerate(OptionPositionCollection positions)
43  {
44  if (positions.IsEmpty)
45  {
46  yield break;
47  }
48 
49  var marketPrice = _marketPriceProvider(positions.Underlying);
50 
51  var longPositions = new List<OptionPosition>();
52  var shortPuts = new SortedDictionary<decimal, OptionPosition>();
53  var shortCalls = new SortedDictionary<decimal, OptionPosition>();
54  foreach (var position in positions)
55  {
56  if (!position.Symbol.HasUnderlying)
57  {
58  yield return position;
59  }
60 
61  if (position.Quantity > 0)
62  {
63  longPositions.Add(position);
64  }
65  else
66  {
67  switch (position.Right)
68  {
69  case OptionRight.Put:
70  shortPuts.Add(position.Strike, position);
71  break;
72 
73  case OptionRight.Call:
74  shortCalls.Add(position.Strike, position);
75  break;
76 
77  default:
78  throw new ApplicationException(
79  "The skies are falling, the oceans rising - you're having a bad time"
80  );
81  }
82  }
83  }
84 
85  throw new NotImplementedException("This implementation needs to be completed.");
86  }
87  }
88 }