Lean  $LEAN_TAG$
CachingFutureChainProvider.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.Collections.Concurrent;
18 using System.Collections.Generic;
19 using System.Linq;
21 
23 {
24  /// <summary>
25  /// An implementation of <see cref="IFutureChainProvider"/> that will cache by date future contracts returned by another future chain provider.
26  /// </summary>
28  {
29  private readonly ConcurrentDictionary<Symbol, FutureChainCacheEntry> _cache = new ConcurrentDictionary<Symbol, FutureChainCacheEntry>();
30  private readonly IFutureChainProvider _futureChainProvider;
31 
32  /// <summary>
33  /// Initializes a new instance of the <see cref="CachingFutureChainProvider"/> class
34  /// </summary>
35  /// <param name="futureChainProvider"></param>
37  {
38  _futureChainProvider = futureChainProvider;
39  }
40 
41  /// <summary>
42  /// Gets the list of future contracts for a given underlying symbol
43  /// </summary>
44  /// <param name="symbol">The underlying symbol</param>
45  /// <param name="date">The date for which to request the future chain (only used in backtesting)</param>
46  /// <returns>The list of future contracts</returns>
47  public IEnumerable<Symbol> GetFutureContractList(Symbol symbol, DateTime date)
48  {
49  List<Symbol> symbols;
50 
51  FutureChainCacheEntry entry;
52  if (!_cache.TryGetValue(symbol, out entry) || date.Date != entry.Date)
53  {
54  symbols = _futureChainProvider.GetFutureContractList(symbol, date.Date).ToList();
55  _cache[symbol] = new FutureChainCacheEntry(date.Date, symbols);
56  }
57  else
58  {
59  symbols = entry.Symbols;
60  }
61 
62  return symbols;
63  }
64 
65  private class FutureChainCacheEntry
66  {
67  public DateTime Date { get; }
68  public List<Symbol> Symbols { get; }
69 
70  public FutureChainCacheEntry(DateTime date, List<Symbol> symbols)
71  {
72  Date = date;
73  Symbols = symbols;
74  }
75  }
76  }
77 }