Lean  $LEAN_TAG$
LeanEngineAlgorithmHandlers.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 
17 using System;
18 using System.ComponentModel.Composition;
20 using QuantConnect.Data;
29 using QuantConnect.Logging;
30 using QuantConnect.Util;
31 
33 {
34  /// <summary>
35  /// Provides a container for the algorithm specific handlers
36  /// </summary>
37  public class LeanEngineAlgorithmHandlers : IDisposable
38  {
39  private bool _dataMonitorWired;
40 
41  /// <summary>
42  /// Gets the result handler used to communicate results from the algorithm
43  /// </summary>
44  public IResultHandler Results { get; }
45 
46  /// <summary>
47  /// Gets the setup handler used to initialize the algorithm state
48  /// </summary>
49  public ISetupHandler Setup { get; }
50 
51  /// <summary>
52  /// Gets the data feed handler used to provide data to the algorithm
53  /// </summary>
54  public IDataFeed DataFeed { get; }
55 
56  /// <summary>
57  /// Gets the transaction handler used to process orders from the algorithm
58  /// </summary>
60 
61  /// <summary>
62  /// Gets the real time handler used to process real time events
63  /// </summary>
64  public IRealTimeHandler RealTime { get; }
65 
66  /// <summary>
67  /// Gets the map file provider used as a map file source for the data feed
68  /// </summary>
70 
71  /// <summary>
72  /// Gets the map file provider used as a map file source for the data feed
73  /// </summary>
75 
76  /// <summary>
77  /// Gets the data file provider used to retrieve security data if it is not on the file system
78  /// </summary>
79  public IDataProvider DataProvider { get; }
80 
81  /// <summary>
82  /// Gets the data file provider used to retrieve security data if it is not on the file system
83  /// </summary>
85 
86  /// <summary>
87  /// Gets the object store used for persistence
88  /// </summary>
89  public IObjectStore ObjectStore { get; }
90 
91  /// <summary>
92  /// Entity in charge of handling data permissions
93  /// </summary>
95 
96  /// <summary>
97  /// Monitors data requests and reports on missing data
98  /// </summary>
99  public IDataMonitor DataMonitor { get; }
100 
101  /// <summary>
102  /// Initializes a new instance of the <see cref="LeanEngineAlgorithmHandlers"/> class from the specified handlers
103  /// </summary>
104  /// <param name="results">The result handler for communicating results from the algorithm</param>
105  /// <param name="setup">The setup handler used to initialize algorithm state</param>
106  /// <param name="dataFeed">The data feed handler used to pump data to the algorithm</param>
107  /// <param name="transactions">The transaction handler used to process orders from the algorithm</param>
108  /// <param name="realTime">The real time handler used to process real time events</param>
109  /// <param name="mapFileProvider">The map file provider used to retrieve map files for the data feed</param>
110  /// <param name="factorFileProvider">Map file provider used as a map file source for the data feed</param>
111  /// <param name="dataProvider">file provider used to retrieve security data if it is not on the file system</param>
112  /// <param name="objectStore">The object store used for persistence</param>
113  /// <param name="dataPermissionsManager">The data permission manager to use</param>
114  /// <param name="liveMode">True for live mode, false otherwise</param>
115  /// <param name="researchMode">True for research mode, false otherwise. This has less priority than liveMode</param>
116  /// <param name="dataMonitor">Optionally the data monitor instance to use</param>
118  ISetupHandler setup,
119  IDataFeed dataFeed,
120  ITransactionHandler transactions,
121  IRealTimeHandler realTime,
122  IMapFileProvider mapFileProvider,
123  IFactorFileProvider factorFileProvider,
124  IDataProvider dataProvider,
125  IObjectStore objectStore,
126  IDataPermissionManager dataPermissionsManager,
127  bool liveMode,
128  bool researchMode = false,
129  IDataMonitor dataMonitor = null
130  )
131  {
132  if (results == null)
133  {
134  throw new ArgumentNullException(nameof(results));
135  }
136  if (setup == null)
137  {
138  throw new ArgumentNullException(nameof(setup));
139  }
140  if (dataFeed == null)
141  {
142  throw new ArgumentNullException(nameof(dataFeed));
143  }
144  if (transactions == null)
145  {
146  throw new ArgumentNullException(nameof(transactions));
147  }
148  if (realTime == null)
149  {
150  throw new ArgumentNullException(nameof(realTime));
151  }
152  if (mapFileProvider == null)
153  {
154  throw new ArgumentNullException(nameof(mapFileProvider));
155  }
156  if (factorFileProvider == null)
157  {
158  throw new ArgumentNullException(nameof(factorFileProvider));
159  }
160  if (dataProvider == null)
161  {
162  throw new ArgumentNullException(nameof(dataProvider));
163  }
164  if (objectStore == null)
165  {
166  throw new ArgumentNullException(nameof(objectStore));
167  }
168  if (dataPermissionsManager == null)
169  {
170  throw new ArgumentNullException(nameof(dataPermissionsManager));
171  }
172 
173  Results = results;
174  Setup = setup;
175  DataFeed = dataFeed;
176  Transactions = transactions;
177  RealTime = realTime;
178  MapFileProvider = mapFileProvider;
179  FactorFileProvider = factorFileProvider;
180  DataProvider = dataProvider;
181  ObjectStore = objectStore;
182  DataPermissionsManager = dataPermissionsManager;
183  DataCacheProvider = new ZipDataCacheProvider(DataProvider, isDataEphemeral: liveMode);
184  DataMonitor = dataMonitor ?? new DataMonitor();
185 
186  if (!liveMode && !researchMode)
187  {
188  _dataMonitorWired = true;
190  }
191  }
192 
193  /// <summary>
194  /// Creates a new instance of the <see cref="LeanEngineAlgorithmHandlers"/> class from the specified composer using type names from configuration
195  /// </summary>
196  /// <param name="composer">The composer instance to obtain implementations from</param>
197  /// <param name="researchMode">True for research mode, false otherwise</param>
198  /// <returns>A fully hydrates <see cref="LeanEngineSystemHandlers"/> instance.</returns>
199  /// <exception cref="CompositionException">Throws a CompositionException during failure to load</exception>
200  public static LeanEngineAlgorithmHandlers FromConfiguration(Composer composer, bool researchMode = false)
201  {
202  var setupHandlerTypeName = Config.Get("setup-handler", "ConsoleSetupHandler");
203  var transactionHandlerTypeName = Config.Get("transaction-handler", "BacktestingTransactionHandler");
204  var realTimeHandlerTypeName = Config.Get("real-time-handler", "BacktestingRealTimeHandler");
205  var dataFeedHandlerTypeName = Config.Get("data-feed-handler", "FileSystemDataFeed");
206  var resultHandlerTypeName = Config.Get("result-handler", "BacktestingResultHandler");
207  var mapFileProviderTypeName = Config.Get("map-file-provider", "LocalDiskMapFileProvider");
208  var factorFileProviderTypeName = Config.Get("factor-file-provider", "LocalDiskFactorFileProvider");
209  var dataProviderTypeName = Config.Get("data-provider", "DefaultDataProvider");
210  var objectStoreTypeName = Config.Get("object-store", "LocalObjectStore");
211  var dataPermissionManager = Config.Get("data-permission-manager", "DataPermissionManager");
212  var dataMonitor = Config.Get("data-monitor", "QuantConnect.Data.DataMonitor");
213 
214  var result = new LeanEngineAlgorithmHandlers(
215  composer.GetExportedValueByTypeName<IResultHandler>(resultHandlerTypeName),
216  composer.GetExportedValueByTypeName<ISetupHandler>(setupHandlerTypeName),
217  composer.GetExportedValueByTypeName<IDataFeed>(dataFeedHandlerTypeName),
218  composer.GetExportedValueByTypeName<ITransactionHandler>(transactionHandlerTypeName),
219  composer.GetExportedValueByTypeName<IRealTimeHandler>(realTimeHandlerTypeName),
220  composer.GetExportedValueByTypeName<IMapFileProvider>(mapFileProviderTypeName),
221  composer.GetExportedValueByTypeName<IFactorFileProvider>(factorFileProviderTypeName),
222  composer.GetExportedValueByTypeName<IDataProvider>(dataProviderTypeName),
223  composer.GetExportedValueByTypeName<IObjectStore>(objectStoreTypeName),
224  composer.GetExportedValueByTypeName<IDataPermissionManager>(dataPermissionManager),
226  researchMode,
227  composer.GetExportedValueByTypeName<IDataMonitor>(dataMonitor)
228  );
229 
230  result.FactorFileProvider.Initialize(result.MapFileProvider, result.DataProvider);
231  result.MapFileProvider.Initialize(result.DataProvider);
232 
233  if (result.DataProvider is ApiDataProvider
234  && (result.FactorFileProvider is not LocalZipFactorFileProvider || result.MapFileProvider is not LocalZipMapFileProvider))
235  {
236  throw new ArgumentException($"The {typeof(ApiDataProvider)} can only be used with {typeof(LocalZipFactorFileProvider)}" +
237  $" and {typeof(LocalZipMapFileProvider)}, please update 'config.json'");
238  }
239 
240  FundamentalService.Initialize(result.DataProvider, Globals.LiveMode);
241 
242  return result;
243  }
244 
245  /// <summary>
246  /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
247  /// </summary>
248  /// <filterpriority>2</filterpriority>
249  public void Dispose()
250  {
251  Log.Trace("LeanEngineAlgorithmHandlers.Dispose(): start...");
252 
253  DataCacheProvider.DisposeSafely();
254  Setup.DisposeSafely();
255  ObjectStore.DisposeSafely();
256  if (_dataMonitorWired)
257  {
259  }
260  DataMonitor.DisposeSafely();
261 
262  Log.Trace("LeanEngineAlgorithmHandlers.Dispose(): Disposed of algorithm handlers.");
263  }
264  }
265 }