Lean  $LEAN_TAG$
DefaultDataProvider.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.IO;
19 
21 {
22  /// <summary>
23  /// Default file provider functionality that retrieves data from disc to be used in an algorithm
24  /// </summary>
25  public class DefaultDataProvider : IDataProvider, IDisposable
26  {
27  private bool _oneTimeWarningLog;
28 
29  /// <summary>
30  /// Event raised each time data fetch is finished (successfully or not)
31  /// </summary>
32  public event EventHandler<DataProviderNewDataRequestEventArgs> NewDataRequest;
33 
34  /// <summary>
35  /// Retrieves data from disc to be used in an algorithm
36  /// </summary>
37  /// <param name="key">A string representing where the data is stored</param>
38  /// <returns>A <see cref="Stream"/> of the data requested</returns>
39  public virtual Stream Fetch(string key)
40  {
41  var success = true;
42  var errorMessage = string.Empty;
43  try
44  {
45  return new FileStream(FileExtension.ToNormalizedPath(key), FileMode.Open, FileAccess.Read, FileShare.Read);
46  }
47  catch (Exception exception)
48  {
49  success = false;
50  errorMessage = exception.Message;
51  if (exception is DirectoryNotFoundException)
52  {
53  if (!_oneTimeWarningLog)
54  {
55  _oneTimeWarningLog = true;
56  Logging.Log.Debug($"DefaultDataProvider.Fetch(): DirectoryNotFoundException: please review data paths, current 'Globals.DataFolder': {Globals.DataFolder}");
57  }
58  return null;
59  }
60  else if (exception is FileNotFoundException)
61  {
62  return null;
63  }
64 
65  throw;
66  }
67  finally
68  {
69  OnNewDataRequest(new DataProviderNewDataRequestEventArgs(key, success, errorMessage));
70  }
71  }
72 
73  /// <summary>
74  /// The stream created by this type is passed up the stack to the IStreamReader
75  /// The stream is closed when the StreamReader that wraps this stream is disposed</summary>
76  public void Dispose()
77  {
78  //
79  }
80 
81  /// <summary>
82  /// Event invocator for the <see cref="NewDataRequest"/> event
83  /// </summary>
85  {
86  NewDataRequest?.Invoke(this, e);
87  }
88  }
89 }