Lean  $LEAN_TAG$
ImmediateExecutionModel.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;
20 
22 {
23  /// <summary>
24  /// Provides an implementation of <see cref="IExecutionModel"/> that immediately submits
25  /// market orders to achieve the desired portfolio targets
26  /// </summary>
28  {
29  private readonly PortfolioTargetCollection _targetsCollection = new PortfolioTargetCollection();
30 
31  /// <summary>
32  /// Immediately submits orders for the specified portfolio targets.
33  /// </summary>
34  /// <param name="algorithm">The algorithm instance</param>
35  /// <param name="targets">The portfolio targets to be ordered</param>
36  public override void Execute(QCAlgorithm algorithm, IPortfolioTarget[] targets)
37  {
38  _targetsCollection.AddRange(targets);
39  // for performance we if empty, OrderByMarginImpact and ClearFulfilled are expensive to call
40  if (!_targetsCollection.IsEmpty)
41  {
42  foreach (var target in _targetsCollection.OrderByMarginImpact(algorithm))
43  {
44  var security = algorithm.Securities[target.Symbol];
45 
46  // calculate remaining quantity to be ordered
47  var quantity = OrderSizing.GetUnorderedQuantity(algorithm, target, security);
48  if (quantity != 0)
49  {
50  if (security.BuyingPowerModel.AboveMinimumOrderMarginPortfolioPercentage(security, quantity,
51  algorithm.Portfolio, algorithm.Settings.MinimumOrderMarginPortfolioPercentage))
52  {
53  algorithm.MarketOrder(security, quantity);
54  }
56  {
57  // will trigger the warning if it has not already been sent
59  }
60  }
61  }
62 
63  _targetsCollection.ClearFulfilled(algorithm);
64  }
65  }
66 
67  /// <summary>
68  /// Event fired each time the we add/remove securities from the data feed
69  /// </summary>
70  /// <param name="algorithm">The algorithm instance that experienced the change in securities</param>
71  /// <param name="changes">The security additions and removals from the algorithm</param>
72  public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
73  {
74  }
75  }
76 }