Lean  $LEAN_TAG$
LiveTimeProvider.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 
20 {
21  /// <summary>
22  /// Live time provide which supports an initial warmup period using the given time provider <see cref="SubscriptionFrontierTimeProvider"/>, used by the <see cref="LiveSynchronizer"/>
23  /// </summary>
25  {
26  private DateTime _previous;
27  private readonly DateTime _liveStart;
28  private readonly ITimeProvider _realTime;
29  private ITimeProvider _warmupTimeProvider;
30 
31  /// <summary>
32  /// Creates a new instance
33  /// </summary>
34  /// <param name="realTime">Real time provider</param>
36  {
37  _realTime = realTime;
38  _liveStart = _realTime.GetUtcNow();
39  }
40 
41  /// <summary>
42  /// Fully initializes this instance providing the initial warmup time provider to use
43  /// </summary>
44  /// <param name="warmupTimeProvider">The warmup provider to use</param>
45  public void Initialize(ITimeProvider warmupTimeProvider)
46  {
47  _warmupTimeProvider = warmupTimeProvider;
48  }
49 
50  /// <summary>
51  /// Gets the current time in UTC
52  /// </summary>
53  /// <returns>The current time in UTC</returns>
54  public DateTime GetUtcNow()
55  {
56  if(ReferenceEquals(_realTime, _warmupTimeProvider))
57  {
58  // warmup ended
59  return _realTime.GetUtcNow();
60  }
61 
62  if (_warmupTimeProvider == null)
63  {
64  // don't let any live data point through until we are fully initialized
65  return Time.BeginningOfTime;
66  }
67 
68  var newTime = _warmupTimeProvider.GetUtcNow();
69  if (_previous == newTime || newTime >= _liveStart)
70  {
71  // subscription time provider swap ended, start using live
72  _warmupTimeProvider = _realTime;
73  return GetUtcNow();
74  }
75  _previous = newTime;
76  return newTime;
77  }
78  }
79 }