From bffff6c2961853800cc4277b1cc1991abccde0fe Mon Sep 17 00:00:00 2001 From: Sean Date: Tue, 24 Feb 2026 12:23:38 -0500 Subject: [PATCH] Refactor GlobalPriceCache and LocalPriceCache to pattern snapshot, fetch, update. Parellelize. --- MarketDataLib/Cache/GBPriceCache.cs | 427 ++++++++++++++---------- MarketDataLib/Cache/LocalPriceCache.cs | 439 ++++++++++++++++--------- 2 files changed, 521 insertions(+), 345 deletions(-) diff --git a/MarketDataLib/Cache/GBPriceCache.cs b/MarketDataLib/Cache/GBPriceCache.cs index 7c9876f..1e8a641 100644 --- a/MarketDataLib/Cache/GBPriceCache.cs +++ b/MarketDataLib/Cache/GBPriceCache.cs @@ -1,260 +1,323 @@ using System; using System.Collections.Generic; -using System.Text; -using MarketData.MarketDataModel; -using MarketData.DataAccess; -using MarketData.Utils; using System.Linq; +using System.Threading; +using MarketData.MarketDataModel; +using MarketData.Utils; using MarketData.Helper; using MarketData.Numerical; -using System.Threading; +using MarketData.DataAccess; - -// This cache is mainly used by the models. It is a short lived cache that gets cleared out every 2 minutes. -// This cache will attempt to load a price from the database if it is found in the cache. namespace MarketData.Cache { - public class GBPriceCache + public interface IPricingDataAccess { - private Thread cacheMonitorThread=null; - private volatile bool threadRun=true; - private Object thisLock=new Object(); - private Dictionary priceCache=new Dictionary(); // the main cache - private Dictionary realTimePriceCache=new Dictionary(); // short lived cache of realtime prices gets cleared out every cacheRefreshAfter(ms) - private Dictionary nullCache=new Dictionary(); - private DateGenerator dateGenerator=new DateGenerator(); - private static GBPriceCache priceCacheInstance=null; - private int cacheRefreshAfter=120000; // the cache will be cleaned up after 2 minutes + Price GetPrice(string symbol, DateTime date); + Prices GetPrices(string symbol, DateTime maxDate, DateTime minDate); + DateTime GetLatestDateOnOrBefore(string symbol, DateTime date); + } + + internal class RealPricingDA : IPricingDataAccess + { + public Price GetPrice(string symbol, DateTime date) => PricingDA.GetPrice(symbol, date); + public Prices GetPrices(string symbol, DateTime maxDate, DateTime minDate) => PricingDA.GetPrices(symbol, maxDate, minDate); + public DateTime GetLatestDateOnOrBefore(string symbol, DateTime date) => PricingDA.GetLatestDateOnOrBefore(symbol, date); + } + + internal class CacheSnapshot + { + public Dictionary PriceCache { get; } + public Dictionary RealTimePriceCache { get; } + public Dictionary NullCache { get; } + + public CacheSnapshot( + Dictionary priceCache, + Dictionary realTimePriceCache, + Dictionary nullCache) + { + PriceCache = priceCache; + RealTimePriceCache = realTimePriceCache; + NullCache = nullCache; + } + } + + public class GBPriceCache : IDisposable + { + private Thread cacheMonitorThread = null; + private volatile bool threadRun = true; + private Object thisLock = new Object(); + + private CacheSnapshot snapshot; + private DateGenerator dateGenerator = new DateGenerator(); + private static GBPriceCache priceCacheInstance = null; + private int cacheRefreshAfter = 120000; // 2 minutes + private SemaphoreSlim fetchSemaphore = new SemaphoreSlim(8); // max 8 concurrent DB fetches + public IPricingDataAccess PricingDataAccess { get; set; } = new RealPricingDA(); protected GBPriceCache() { - cacheMonitorThread=new Thread(new ThreadStart(ThreadProc)); + snapshot = new CacheSnapshot(new Dictionary(), new Dictionary(), new Dictionary()); + cacheMonitorThread = new Thread(new ThreadStart(ThreadProc)); cacheMonitorThread.Start(); } + public static GBPriceCache GetInstance() { - lock(typeof(GBPriceCache)) + lock (typeof(GBPriceCache)) { - if(null==priceCacheInstance) + if (null == priceCacheInstance) { - priceCacheInstance=new GBPriceCache(); + priceCacheInstance = new GBPriceCache(); } return priceCacheInstance; } } + public void Clear() { - lock(thisLock) + lock (thisLock) { - priceCache=new Dictionary(); - realTimePriceCache=new Dictionary(); - nullCache=new Dictionary(); - } - } - public void Dispose() - { - lock(thisLock) - { - if(null==priceCacheInstance || false==threadRun)return; - threadRun=false; - if(null!=cacheMonitorThread) - { - MDTrace.WriteLine(LogLevel.DEBUG,String.Format("[GBPriceCache:Dispose]Thread state is '{0}'. Joining main thread...",Utility.ThreadStateToString(cacheMonitorThread))); - cacheMonitorThread.Join(5000); - this.cacheMonitorThread=null; - } - MDTrace.WriteLine(LogLevel.DEBUG,"[GBPriceCache:Dispose] End."); - priceCacheInstance=null; - } - } - public void ClearCacheOnOrBefore(DateTime onOrBeforeDate,bool collect=false) - { - lock(thisLock) - { - MDTrace.WriteLine(LogLevel.DEBUG,"Clearing GBPriceCache cache."); - List symbols=new List(priceCache.Keys); - foreach(String symbol in symbols) - { - PricesByDate pricesByDate=priceCache[symbol]; - List symbolDates=new List(pricesByDate.Keys); - foreach(DateTime symbolDate in symbolDates) - { - if(symbolDate(), new Dictionary(), new Dictionary()); } } - public Price GetPriceOrLatestAvailable(String symbol,DateTime date) + public void Dispose() { - lock(thisLock) + lock (thisLock) { - Price price=GetPrice(symbol,date); - if(null!=price) return price; - DateTime latestPricingDate=PricingDA.GetLatestDateOnOrBefore(symbol,date); - price=GetPrice(symbol,latestPricingDate); - if(null!=price) return price; - price=PricingDA.GetPrice(symbol,latestPricingDate); - if(null!=price) AddPrice(price); - return price; + if (null == priceCacheInstance || !threadRun) return; + threadRun = false; + if (null != cacheMonitorThread) + { + MDTrace.WriteLine(LogLevel.DEBUG, "[GBPriceCache:Dispose] Joining monitor thread..."); + cacheMonitorThread.Join(5000); + cacheMonitorThread = null; + } + priceCacheInstance = null; } } + + public void ClearCacheOnOrBefore(DateTime onOrBeforeDate, bool collect = false) + { + lock (thisLock) + { + Dictionary newPriceCache = new Dictionary(); + foreach (KeyValuePair entry in snapshot.PriceCache) + { + String symbol = entry.Key; + PricesByDate filteredPrices = new PricesByDate(); + PricesByDate existingPrices = entry.Value; + foreach (KeyValuePair kvp in existingPrices) + { + if (kvp.Key >= onOrBeforeDate) + { + filteredPrices.Add(kvp.Key, kvp.Value); + } + } + if (filteredPrices.Count > 0) + { + newPriceCache.Add(symbol, filteredPrices); + } + } + UpdateSnapshot(newPriceCache, snapshot.RealTimePriceCache, snapshot.NullCache); + if (collect) GC.Collect(); + } + } + + public Price GetPriceOrLatestAvailable(String symbol, DateTime date) + { + Price price = GetPrice(symbol, date); + if (null != price) return price; + DateTime latestPricingDate = PricingDataAccess.GetLatestDateOnOrBefore(symbol, date); + price = GetPrice(symbol, latestPricingDate); + if (null != price) return price; + fetchSemaphore.Wait(); + try + { + price = PricingDataAccess.GetPrice(symbol, latestPricingDate); + } + finally + { + fetchSemaphore.Release(); + } + if (null !=price) AddPrice(price); + return price; + } + public Price GetRealtimePrice(String symbol) { - if(realTimePriceCache.ContainsKey(symbol)) return realTimePriceCache[symbol]; - Price price=MarketDataHelper.GetLatestPrice(symbol); - if(null!=price) + if (snapshot.RealTimePriceCache.ContainsKey(symbol)) { - realTimePriceCache.Add(symbol,price); + return snapshot.RealTimePriceCache[symbol]; + } + + Price price = MarketDataHelper.GetLatestPrice(symbol); + if (null != price) + { + Dictionary newRealtime = new Dictionary(snapshot.RealTimePriceCache); + newRealtime.Add(symbol, price); + UpdateSnapshot(snapshot.PriceCache, newRealtime, snapshot.NullCache); } return price; } - public Price GetPrice(String symbol,DateTime date) + + public Price GetPrice(String symbol, DateTime date) { - lock(thisLock) + date = date.Date; + if (!ContainsPrice(symbol, date)) { - date=date.Date; - if(!ContainsPrice(symbol,date)) + String key = symbol + Utility.DateTimeToStringMMHDDHYYYY(date); + if (snapshot.NullCache.ContainsKey(key)) { - String key=symbol+Utility.DateTimeToStringMMHDDHYYYY(date); - if(nullCache.ContainsKey(key)) return null; - Price price=PricingDA.GetPrice(symbol,date); - if(null==price) - { - nullCache.Add(key,true); - return price; - } - AddPrice(price); + return null; } - if(!priceCache.ContainsKey(symbol)) return null; - PricesByDate pricesByDate=priceCache[symbol]; - if(!pricesByDate.ContainsKey(date.Date)) return null; - return pricesByDate[date]; + fetchSemaphore.Wait(); + Price price; + try + { + price = PricingDataAccess.GetPrice(symbol, date); + } + finally + { + fetchSemaphore.Release(); + } + if (null ==price) + { + Dictionary newNullCache = new Dictionary(snapshot.NullCache); + newNullCache.Add(key, true); + UpdateSnapshot(snapshot.PriceCache, snapshot.RealTimePriceCache, newNullCache); + return null; + } + + AddPrice(price); } + if (!snapshot.PriceCache.ContainsKey(symbol)) return null; + PricesByDate pricesByDate = snapshot.PriceCache[symbol]; + if (!pricesByDate.ContainsKey(date)) return null; + return pricesByDate[date]; } public Prices GetPrices(String symbol, DateTime earlierDate, DateTime laterDate) { - DateGenerator dateGenerator = new DateGenerator(); - - if(laterDate datesList = dateGenerator.GenerateHistoricalDates(earlierDate, laterDate); + List datesList = localDateGenerator.GenerateHistoricalDates(earlierDate, laterDate); datesList = datesList.Where(x => x >= earlierDate).ToList(); return GetPrices(symbol, laterDate, datesList.Count); } -// The most recent price is returned at the lowest index - public Prices GetPrices(String symbol,DateTime startDate,int dayCount) + public Prices GetPrices(String symbol, DateTime startDate, int dayCount) { - lock(thisLock) + List historicalDates = dateGenerator.GenerateHistoricalDates(startDate, dayCount + 60); + List missingDates = new List(); + foreach (DateTime historicalDate in historicalDates) { - List historicalDates=dateGenerator.GenerateHistoricalDates(startDate,dayCount+60); - Prices prices=null; - List missingDates=null; - foreach(DateTime historicalDate in historicalDates) + if (!ContainsPrice(symbol, historicalDate)) { - if(!ContainsPrice(symbol,historicalDate)) + String key = symbol + Utility.DateTimeToStringMMHDDHYYYY(historicalDate); + if (!snapshot.NullCache.ContainsKey(key)) { - String key=symbol+Utility.DateTimeToStringMMHDDHYYYY(historicalDate); - if(nullCache.ContainsKey(key)) continue; - if(null==missingDates)missingDates=new List(); missingDates.Add(historicalDate); } } - if(null!=missingDates) - { - DateTime minDate=(from DateTime date in missingDates select date).Min(); - DateTime maxDate=(from DateTime date in missingDates select date).Max(); - prices=PricingDA.GetPrices(symbol,maxDate,minDate); - foreach(Price price in prices) AddPrice(price); - prices=new Prices(); - foreach(DateTime historicalDate in historicalDates) - { - if(!ContainsPrice(symbol,historicalDate)) - { - String key=symbol+Utility.DateTimeToStringMMHDDHYYYY(historicalDate); - if(!nullCache.ContainsKey(key)) nullCache.Add(key,true); - } - else - { - if(!priceCache.ContainsKey(symbol)) continue; - PricesByDate pricesByDate=priceCache[symbol]; - if(!pricesByDate.ContainsKey(historicalDate.Date)) continue; - prices.Add(pricesByDate[historicalDate]); - } - } - } - else - { - prices=new Prices(); - foreach(DateTime historicalDate in historicalDates) - { - if(!priceCache.ContainsKey(symbol)) continue; - if(!priceCache[symbol].ContainsKey(historicalDate.Date)) - { - continue; - } - prices.Add((priceCache[symbol])[historicalDate]); - } - } - return new Prices(prices.OrderByDescending(x => x.Date).ToList().Take(dayCount).ToList()); } + if (missingDates.Count > 0) + { + DateTime minDate = missingDates.Min(); + DateTime maxDate = missingDates.Max(); + + fetchSemaphore.Wait(); + Prices loadedPrices; + try + { + loadedPrices = PricingDataAccess.GetPrices(symbol, maxDate, minDate); + } + finally + { + fetchSemaphore.Release(); + } + + foreach (Price price in loadedPrices) + { + AddPrice(price); + } + } + + Prices prices = new Prices(); + foreach (DateTime historicalDate in historicalDates) + { + if (!snapshot.PriceCache.ContainsKey(symbol)) continue; + PricesByDate pricesByDate = snapshot.PriceCache[symbol]; + if (!pricesByDate.ContainsKey(historicalDate)) continue; + prices.Add(pricesByDate[historicalDate]); + } + + List ordered = prices.OrderByDescending(x => x.Date).ToList(); + return new Prices(ordered.Take(dayCount).ToList()); } + private void AddPrice(Price price) { - lock(thisLock) + if (null == price) return; + + lock (thisLock) { - if(null==price) return; - PricesByDate pricesByDate=null; - if(!priceCache.ContainsKey(price.Symbol)) + PricesByDate pricesByDate; + if (!snapshot.PriceCache.ContainsKey(price.Symbol)) { - pricesByDate=new PricesByDate(); - pricesByDate.Add(price.Date,price); - priceCache.Add(price.Symbol,pricesByDate); + pricesByDate = new PricesByDate(); + pricesByDate.Add(price.Date, price); + Dictionary newCache = new Dictionary(snapshot.PriceCache); + newCache.Add(price.Symbol, pricesByDate); + UpdateSnapshot(newCache, snapshot.RealTimePriceCache, snapshot.NullCache); } else { - pricesByDate=priceCache[price.Symbol]; - if(pricesByDate.ContainsKey(price.Date.Date)) return; - pricesByDate.Add(price.Date.Date,price); - } - } - } - public bool ContainsPrice(String symbol,DateTime date) - { - if(!priceCache.ContainsKey(symbol)) return false; - PricesByDate pricesByDate=priceCache[symbol]; - if(!pricesByDate.ContainsKey(date.Date)) return false; - return true; - } - private void ThreadProc() - { - int quantums=0; - int quantumInterval=1000; - while(threadRun) - { - Thread.Sleep(quantumInterval); - if(!threadRun) break; - quantums+=quantumInterval; - if(quantums>cacheRefreshAfter) - { - quantums=0; - lock(thisLock) + pricesByDate = snapshot.PriceCache[price.Symbol]; + if (!pricesByDate.ContainsKey(price.Date)) { - realTimePriceCache.Clear(); - MDTrace.WriteLine(LogLevel.DEBUG,"Clearing GBPriceCache price cache."); + pricesByDate.Add(price.Date, price); } } } - MDTrace.WriteLine(LogLevel.DEBUG,"[GBPriceCache:ThreadProc]Thread ended."); + } + + public bool ContainsPrice(String symbol, DateTime date) + { + if (!snapshot.PriceCache.ContainsKey(symbol)) return false; + PricesByDate pricesByDate = snapshot.PriceCache[symbol]; + return pricesByDate.ContainsKey(date); + } + + private void ThreadProc() + { + int quantums = 0; + int quantumInterval = 1000; + + while (threadRun) + { + Thread.Sleep(quantumInterval); + if(!threadRun)break; + quantums += quantumInterval; + if (quantums > cacheRefreshAfter) + { + quantums = 0; + lock (thisLock) + { + UpdateSnapshot(snapshot.PriceCache, new Dictionary(), snapshot.NullCache); + } + } + } + } + + private void UpdateSnapshot(Dictionary newPriceCache,Dictionary newRealtimePriceCache, Dictionary newNullCache) + { + snapshot = new CacheSnapshot(newPriceCache, newRealtimePriceCache, newNullCache); } } } - diff --git a/MarketDataLib/Cache/LocalPriceCache.cs b/MarketDataLib/Cache/LocalPriceCache.cs index 5cd654d..cf4eefd 100644 --- a/MarketDataLib/Cache/LocalPriceCache.cs +++ b/MarketDataLib/Cache/LocalPriceCache.cs @@ -1,65 +1,70 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using MarketData.MarketDataModel; +using MarketData.MarketDataModel; using MarketData.Utils; using MarketData.DataAccess; +using System.Collections.Concurrent; using System.Threading; +using System.Collections.Generic; +using System; +using System.Threading.Tasks; +using System.Linq; -// This cache is mainly used by gainloss generator. This cache is intended to be front loaded and then used. -// This cache will not attempt to load an item that is not found. It does have a Refresh() that will reload only the most recent pricing data from the database in order to -// maintain the most updated pricing. namespace MarketData.Cache { - public class LocalPriceCache - { - private Dictionary priceCache=new Dictionary(); - private static LocalPriceCache instance=null; + public class LocalPriceCache + { + private Dictionary priceCache = new Dictionary(); + private static LocalPriceCache instance = null; private DateTime latestDate = Utility.Epoch; - private Thread cacheMonitorThread=null; - private volatile bool threadRun=true; - private int cacheCycle=300000; - private Object thisLock=new Object(); + private Thread cacheMonitorThread = null; + private volatile bool threadRun = true; + private int cacheCycle = 300000; + private object thisLock = new object(); + private object fetchLock = new object(); - private LocalPriceCache() - { - cacheMonitorThread=new Thread(new ThreadStart(ThreadProc)); + private LocalPriceCache() + { + cacheMonitorThread = new Thread(new ThreadStart(ThreadProc)); cacheMonitorThread.Start(); - } + } public void Clear() { - lock(thisLock) + lock (thisLock) { - priceCache=new Dictionary(); + priceCache = new Dictionary(); RefreshLatestDate(); } } public void Dispose() { - lock(thisLock) + Thread threadToJoin = null; + + lock (thisLock) { - if(null==instance || false==threadRun)return; - threadRun=false; - if(null!=cacheMonitorThread) - { - MDTrace.WriteLine(LogLevel.DEBUG,String.Format("[LocalPriceCache:Dispose]Thread state is '{0}'. Joining main thread...",Utility.ThreadStateToString(cacheMonitorThread))); - cacheMonitorThread.Join(5000); - this.cacheMonitorThread=null; - } - MDTrace.WriteLine(LogLevel.DEBUG,"[LocalPriceCache:Dispose] End"); - instance=null; + if (instance == null || !threadRun) return; + threadRun = false; + threadToJoin = cacheMonitorThread; + cacheMonitorThread = null; + instance = null; } + + if (threadToJoin != null) + { + MDTrace.WriteLine(LogLevel.DEBUG, $"[LocalPriceCache:Dispose] Thread state is '{Utility.ThreadStateToString(threadToJoin)}'. Joining..."); + threadToJoin.Join(5000); + } + + MDTrace.WriteLine(LogLevel.DEBUG, "[LocalPriceCache:Dispose] End"); } public static LocalPriceCache GetInstance() { - lock(typeof(LocalPriceCache)) + lock (typeof(LocalPriceCache)) { - if(null==instance) + if (instance == null) { - instance=new LocalPriceCache(); + instance = new LocalPriceCache(); } return instance; } @@ -67,17 +72,17 @@ namespace MarketData.Cache public void RefreshLatestDate() { - lock(typeof(LocalPriceCache)) + lock (thisLock) { - latestDate=PricingDA.GetLatestDate(); + latestDate = PricingDA.GetLatestDate(); } } public DateTime GetLatestDate() { - lock(typeof(LocalPriceCache)) + lock (thisLock) { - if(Utility.IsEpoch(latestDate)) + if (Utility.IsEpoch(latestDate)) { RefreshLatestDate(); } @@ -87,65 +92,118 @@ namespace MarketData.Cache public void Refresh() { - lock(typeof(LocalPriceCache)) + List symbols; + Dictionary currentMaxDates; + + lock (thisLock) { - List symbols=new List(priceCache.Keys); - Dictionary maxDbDates = PricingDA.GetLatestDates(symbols); - RefreshLatestDate(); - foreach(String symbol in symbols) + symbols = priceCache.Keys.ToList(); + currentMaxDates = priceCache.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.MaxDate); + } + + if (symbols.Count == 0) return; + + ConcurrentDictionary fullReloads = new ConcurrentDictionary(); + ConcurrentDictionary singleUpdates = new ConcurrentDictionary(); + DateTime latestDateFromDb; + + lock (fetchLock) + { + Dictionary maxDbDates = PricingDA.GetLatestDates(symbols); + latestDateFromDb = PricingDA.GetLatestDate(); + + Parallel.ForEach(symbols, new ParallelOptions { MaxDegreeOfParallelism = 8 }, symbol => { - PricesByDate symbolPrices=priceCache[symbol]; - DateTime maxDate=symbolPrices.MaxDate; // get the latest date in the cache - if(maxDbDates.ContainsKey(symbol) && !maxDbDates[symbol].Date.Equals(maxDate.Date)) // if the cache date and the database date are not equal then reload the cache + if (!currentMaxDates.TryGetValue(symbol, out var cachedMax)) return; + + if (maxDbDates.TryGetValue(symbol, out var dbMax) && dbMax.Date != cachedMax.Date) { - MDTrace.WriteLine(LogLevel.DEBUG,$"Cache date and Database date for {symbol} are not equal, reloading cache. Cache Date:{maxDate.ToShortDateString()} Database Date:{maxDbDates[symbol].Date.ToShortDateString()}"); - Prices prices=PricingDA.GetPrices(symbol,symbolPrices.MinDate); // reload the prices for this symbol using the current minDate in the cache as a lower boundary - if(null==prices)continue; // if we can't load any prices for symbol then just continue - priceCache.Remove(symbol); // remove the pricing entries in the price cache for the symbol - priceCache.Add(symbol,prices.GetPricesByDate()); // reload the cache + Prices prices = PricingDA.GetPrices(symbol, cachedMax); + if (prices != null) fullReloads[symbol] = prices.GetPricesByDate(); } else - { - MDTrace.WriteLine(LogLevel.DEBUG,$"[LocalPriceCache] Fetching latest price from database for {symbol} on {maxDate.ToShortDateString()}"); - Price price=PricingDA.GetPrice(symbol,maxDate); // the max date from the cache equals the max date from the database so just reload the latest price from the database - if(null==price)continue; // if no latest price then just continue - symbolPrices.Remove(maxDate); // remove the current price associated with the max date - symbolPrices.Add(maxDate,price); // reload the latest price for maxDate(symbol) into the cache + { + Price price = PricingDA.GetPrice(symbol, cachedMax); + if (price != null) singleUpdates[symbol] = price; + } + }); + } + + lock (thisLock) + { + latestDate = latestDateFromDb; + + foreach (var kvp in fullReloads) + { + if (priceCache.TryGetValue(kvp.Key, out PricesByDate existing) && existing.MaxDate == currentMaxDates[kvp.Key]) + { + priceCache[kvp.Key] = kvp.Value; + } + } + + foreach (var kvp in singleUpdates) + { + if (priceCache.TryGetValue(kvp.Key, out PricesByDate pricesByDate) && pricesByDate.MaxDate == currentMaxDates[kvp.Key]) + { + // Remove the old price (if any) and add the new price properly + if (pricesByDate.ContainsKey(kvp.Value.Date)) + pricesByDate.Remove(kvp.Value.Date); + pricesByDate.Add(kvp.Value.Date, kvp.Value); } } } + + MDTrace.WriteLine(LogLevel.DEBUG, $"Full reloads: {fullReloads.Count}, Single updates: {singleUpdates.Count}"); } -// This version of Add(PortfolioTrades) will account for adding multiple lots at different times. So instead of just checking for the existance of the symbol in the cache -// we look to see if the symbol is in the cache and what dates are available. If the date range specified in the trade are not available then we load those date ranges. -// This is a brute force approach always maintaining the gap between successive TradeDates in th.e portfolio trades and the maximum date for the symbol in the database. -// So while it is inefficient in terms of memory usage it alleviates the need for figuring out contiguous price sections public void Add(PortfolioTrades portfolioTrades) { - lock(typeof(LocalPriceCache)) + List symbols = portfolioTrades.Symbols; + Dictionary minTradeDates = symbols.ToDictionary(sym => sym, sym => portfolioTrades.GetMinTradeDate(sym)); + + Dictionary minCacheDates; + lock (thisLock) { - Profiler profiler=new Profiler(); - profiler.Start(); - List symbols=portfolioTrades.Symbols; - foreach(String symbol in symbols) + minCacheDates = symbols.ToDictionary(sym => sym, sym => priceCache.ContainsKey(sym) ? priceCache[sym].MinDate : DateTime.MaxValue); + } + + ConcurrentDictionary fetchedPrices = new ConcurrentDictionary(); + + Parallel.ForEach(symbols, new ParallelOptions { MaxDegreeOfParallelism = 8 }, symbol => + { + DateTime minTradeDate = minTradeDates[symbol]; + DateTime minCacheDate = minCacheDates[symbol]; + Prices prices = null; + + try { - DateTime minPortfolioTradeDate=portfolioTrades.GetMinTradeDate(symbol); - if(!ContainsSymbol(symbol)) + if (minCacheDate == DateTime.MaxValue) { - Prices prices=PricingDA.GetPrices(symbol,minPortfolioTradeDate); - if(null==prices)continue; - foreach(Price price in prices)Add(price); + prices = PricingDA.GetPrices(symbol, minTradeDate); } - else + else if (minTradeDate < minCacheDate) { - DateTime minCacheDate=GetMinCacheDate(symbol); - if(minPortfolioTradeDate 0) + { + fetchedPrices[symbol] = prices; + } + } + catch (Exception ex) + { + MDTrace.WriteLine(LogLevel.DEBUG, $"Error fetching prices for {symbol}: {ex.Message}"); + } + }); + + lock (thisLock) + { + foreach (var kvp in fetchedPrices) + { + foreach (var price in kvp.Value) + { + Add(price); } } } @@ -153,131 +211,186 @@ namespace MarketData.Cache public void Add(Prices prices) { - foreach(Price price in prices) - { - Add(price); - } + foreach (Price price in prices) + { + Add(price); + } } - public void Add(List symbols,DateTime pricingDate) + public void Add(List symbols, DateTime pricingDate) { - foreach(String symbol in symbols) + if (symbols == null || symbols.Count == 0) return; + + ConcurrentDictionary fetchedPrices = new ConcurrentDictionary(); + + Parallel.ForEach(symbols, new ParallelOptions { MaxDegreeOfParallelism = 8 }, symbol => { - if(ContainsPrice(symbol,pricingDate))continue; - Price price=PricingDA.GetPrice(symbol,pricingDate); - if(null==price)continue; - Add(price); + lock (thisLock) + { + if (ContainsPrice(symbol, pricingDate)) return; + } + + try + { + Price price = PricingDA.GetPrice(symbol, pricingDate); + if (price != null) fetchedPrices[symbol] = price; + } + catch (Exception ex) + { + MDTrace.WriteLine(LogLevel.DEBUG, $"Error fetching price for {symbol} on {pricingDate:yyyy-MM-dd}: {ex.Message}"); + } + }); + + lock (thisLock) + { + foreach (var kvp in fetchedPrices) + { + Add(kvp.Value); + } } } public void Add(Price price) { - lock(typeof(LocalPriceCache)) + if (price == null) return; + + lock (thisLock) { - if(null==price)return; - if(ContainsPrice(price.Symbol,price.Date))return; - PricesByDate pricesByDate=null; - if(!priceCache.ContainsKey(price.Symbol)) + if (!priceCache.TryGetValue(price.Symbol, out var pricesByDate)) { - pricesByDate=new PricesByDate(); - pricesByDate.Add(price.Date,price); - priceCache.Add(price.Symbol,pricesByDate); - return; + pricesByDate = new PricesByDate(); + priceCache[price.Symbol] = pricesByDate; + } + if (!pricesByDate.ContainsKey(price.Date)) + { + pricesByDate.Add(price.Date, price); // must use Add() to update MinDate/MaxDate } - pricesByDate=priceCache[price.Symbol]; - if(pricesByDate.ContainsKey(price.Date))return; - pricesByDate.Add(price.Date,price); } } - public DateTime GetMinCacheDate(String symbol) + + public DateTime GetMinCacheDate(string symbol) { - if(!ContainsSymbol(symbol))return Utility.Epoch; - PricesByDate symbolPrices=priceCache[symbol]; - return symbolPrices.MinDate; + lock (thisLock) + { + if (!priceCache.TryGetValue(symbol, out var symbolPrices) || symbolPrices.Count == 0) + { + return Utility.Epoch; + } + return symbolPrices.MinDate; + } } public void RemoveDate(DateTime date) { - lock(typeof(LocalPriceCache)) + lock (thisLock) { - List symbols=new List(priceCache.Keys); - foreach(String key in symbols) + foreach (var kvp in priceCache) { - PricesByDate pricesByDate=priceCache[key]; - if(pricesByDate.ContainsKey(date))pricesByDate.Remove(date); + kvp.Value.Remove(date); } } } - public Price GetPrice(String symbol,DateTime date) - { - lock(typeof(LocalPriceCache)) - { - if(!priceCache.ContainsKey(symbol))return null; - PricesByDate pricesByDate=priceCache[symbol]; - if(!pricesByDate.ContainsKey(date))return null; - return pricesByDate[date]; - } - } - public bool ContainsPrice(String symbol,DateTime date) - { - lock(typeof(LocalPriceCache)) - { - if(!priceCache.ContainsKey(symbol))return false; - PricesByDate pricesByDate=priceCache[symbol]; - if(!pricesByDate.ContainsKey(date))return false; - return true; - } - } - public bool ContainsPrice(List symbols,DateTime date) - { - lock(typeof(LocalPriceCache)) - { - foreach(String symbol in symbols)if(!ContainsPrice(symbol,date))return false; - return true; - } - } - public bool ContainsSymbol(String symbol) + public Prices GetPrices(string symbol, DateTime endDate, int dayCount) { - lock(typeof(LocalPriceCache)) + lock (thisLock) { - if(priceCache.ContainsKey(symbol))return true; - return false; + if (!priceCache.TryGetValue(symbol, out var pricesByDate)) return new Prices(); + + DateGenerator dateGenerator = new DateGenerator(); + List historicalDates = dateGenerator.GenerateHistoricalDates(endDate, dayCount); + + Prices result = new Prices(); + foreach (DateTime date in historicalDates) + { + if (pricesByDate.ContainsKey(date)) + { + result.Add(pricesByDate[date]); + } + } + + return result; } } - public long Count() + public Price GetPrice(string symbol, DateTime date) { - long count=0; - List symbols=priceCache.Keys.ToList(); - foreach(String symbol in symbols) + lock (thisLock) { - PricesByDate pricesByDate=priceCache[symbol]; - count+=pricesByDate.Count; + if (!priceCache.TryGetValue(symbol, out var pricesByDate)) return null; + return pricesByDate.TryGetValue(date, out var price) ? price : null; + } + } + + public bool ContainsPrice(string symbol, DateTime date) + { + lock (thisLock) + { + if (!priceCache.TryGetValue(symbol, out var pricesByDate)) return false; + return pricesByDate.ContainsKey(date); + } + } + + public bool ContainsPrice(List symbols, DateTime date) + { + if (symbols == null || symbols.Count == 0) return false; + + lock (thisLock) + { + foreach (string symbol in symbols) + { + if (!priceCache.TryGetValue(symbol, out var pricesByDate) || !pricesByDate.ContainsKey(date)) + { + return false; + } + } + return true; + } + } + + public bool ContainsSymbol(string symbol) + { + lock (thisLock) + { + return priceCache.ContainsKey(symbol); + } + } + + private long Count() + { + lock (thisLock) + { + long count = 0; + foreach (var pricesByDate in priceCache.Values) + { + count += pricesByDate.Count; + } + return count; } - return count; } private void ThreadProc() { - int quantums=0; - int quantumInterval=1000; - long lastCount=0; - while(threadRun) + int quantums = 0; + int quantumInterval = 1000; + long lastCount = 0; + + while (threadRun) { Thread.Sleep(quantumInterval); - quantums+=quantumInterval; - if(quantums>cacheCycle) + quantums += quantumInterval; + if (quantums > cacheCycle) { - quantums=0; - lock(thisLock) + quantums = 0; + lock (thisLock) { - lastCount=Count(); - MDTrace.WriteLine(LogLevel.DEBUG,String.Format("[LocalPriceCache:ThreadProc] Symbols: {0}. Items in cache: {1}.",priceCache.Keys.Count,Utility.FormatNumber(lastCount,0,true))); + lastCount = Count(); + MDTrace.WriteLine(LogLevel.DEBUG, $"[LocalPriceCache:ThreadProc] Symbols: {priceCache.Keys.Count}. Items in cache: {Utility.FormatNumber(lastCount,0,true)}."); } } } - MDTrace.WriteLine(LogLevel.DEBUG,String.Format("[LocalPriceCache:ThreadProc] Thread ended. Items in cache:{0}",Utility.FormatNumber(lastCount,0,true))); + + MDTrace.WriteLine(LogLevel.DEBUG, $"[LocalPriceCache:ThreadProc] Thread ended. Items in cache:{Utility.FormatNumber(lastCount,0,true)}"); } - } + } }