Lean  $LEAN_TAG$
MapFilePrimaryExchangeProvider.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.Collections.Concurrent;
18 using System.Linq;
20 
22 {
23  /// <summary>
24  /// Implementation of IPrimaryExchangeProvider from map files.
25  /// </summary>
27  {
28  private readonly IMapFileProvider _mapFileProvider;
29  private readonly ConcurrentDictionary<SecurityIdentifier, Exchange> _primaryExchangeBySid;
30 
31  /// <summary>
32  /// Constructor for Primary Exchange Provider from MapFiles
33  /// </summary>
34  /// <param name="mapFileProvider">MapFile to use</param>
36  {
37  _mapFileProvider = mapFileProvider;
38  _primaryExchangeBySid = new ConcurrentDictionary<SecurityIdentifier, Exchange>();
39  }
40 
41  /// <summary>
42  /// Gets the primary exchange for a given security identifier
43  /// </summary>
44  /// <param name="securityIdentifier">The security identifier to get the primary exchange for</param>
45  /// <returns>Returns the primary exchange or null if not found</returns>
46  public Exchange GetPrimaryExchange(SecurityIdentifier securityIdentifier)
47  {
48  Exchange primaryExchange;
49  if (!_primaryExchangeBySid.TryGetValue(securityIdentifier, out primaryExchange))
50  {
51  var mapFile = _mapFileProvider.Get(AuxiliaryDataKey.Create(securityIdentifier))
52  .ResolveMapFile(securityIdentifier.Symbol, securityIdentifier.Date);
53  if (mapFile != null && mapFile.Any())
54  {
55  primaryExchange = mapFile.Last().PrimaryExchange;
56  }
57  _primaryExchangeBySid[securityIdentifier] = primaryExchange;
58  }
59 
60  return primaryExchange;
61  }
62  }
63 }