Lean  $LEAN_TAG$
ExecutionModelPythonWrapper.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 Python.Runtime;
19 using QuantConnect.Python;
20 using System;
21 
23 {
24  /// <summary>
25  /// Provides an implementation of <see cref="IExecutionModel"/> that wraps a <see cref="PyObject"/> object
26  /// </summary>
28  {
29  private readonly BasePythonWrapper<ExecutionModel> _model;
30 
31  /// <summary>
32  /// Constructor for initialising the <see cref="IExecutionModel"/> class with wrapped <see cref="PyObject"/> object
33  /// </summary>
34  /// <param name="model">Model defining how to execute trades to reach a portfolio target</param>
35  public ExecutionModelPythonWrapper(PyObject model)
36  {
37  _model = new BasePythonWrapper<ExecutionModel>(model, false);
38  foreach (var attributeName in new[] { "Execute", "OnSecuritiesChanged" })
39  {
40  if (!_model.HasAttr(attributeName))
41  {
42  throw new NotImplementedException($"IExecutionModel.{attributeName} must be implemented. Please implement this missing method on {model.GetPythonType()}");
43  }
44  }
45  }
46 
47  /// <summary>
48  /// Submit orders for the specified portfolio targets.
49  /// This model is free to delay or spread out these orders as it sees fit
50  /// </summary>
51  /// <param name="algorithm">The algorithm instance</param>
52  /// <param name="targets">The portfolio targets to be ordered</param>
53  public override void Execute(QCAlgorithm algorithm, IPortfolioTarget[] targets)
54  {
55  _model.InvokeMethod(nameof(Execute), algorithm, targets).Dispose();
56  }
57 
58  /// <summary>
59  /// Event fired each time the we add/remove securities from the data feed
60  /// </summary>
61  /// <param name="algorithm">The algorithm instance that experienced the change in securities</param>
62  /// <param name="changes">The security additions and removals from the algorithm</param>
63  public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
64  {
65  _model.InvokeMethod(nameof(OnSecuritiesChanged), algorithm, changes).Dispose();
66  }
67  }
68 }