From 4a3fb9750f9ae83ba51bed5021d719e8d8bfb76f Mon Sep 17 00:00:00 2001 From: Sean Date: Fri, 4 Apr 2025 16:35:16 -0400 Subject: [PATCH] Optimize the LocalPriceCache by adding a method to PricingDA --- .../MarketDataLib/Cache/LocalPriceCache.cs | 88 ++++--------------- .../MarketDataLib/DataAccess/PricingDA.cs | 44 ++++++++++ 2 files changed, 62 insertions(+), 70 deletions(-) diff --git a/MarketData/MarketDataLib/Cache/LocalPriceCache.cs b/MarketData/MarketDataLib/Cache/LocalPriceCache.cs index 4ef3294..eb3dac1 100755 --- a/MarketData/MarketDataLib/Cache/LocalPriceCache.cs +++ b/MarketData/MarketDataLib/Cache/LocalPriceCache.cs @@ -1,11 +1,6 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using MarketData; -using MarketData.MarketDataModel; +using MarketData.MarketDataModel; using MarketData.Utils; using MarketData.DataAccess; -using System.Threading; // 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 @@ -19,7 +14,6 @@ namespace MarketData.Cache private Thread cacheMonitorThread=null; private volatile bool threadRun=true; private int cacheCycle=300000; -// private int cacheRefreshAfter=60000; private Object thisLock=new Object(); private LocalPriceCache() @@ -27,6 +21,7 @@ namespace MarketData.Cache cacheMonitorThread=new Thread(new ThreadStart(ThreadProc)); cacheMonitorThread.Start(); } + public void Clear() { lock(thisLock) @@ -34,6 +29,7 @@ namespace MarketData.Cache priceCache=new Dictionary(); } } + public void Dispose() { lock(thisLock) @@ -50,6 +46,7 @@ namespace MarketData.Cache instance=null; } } + public static LocalPriceCache GetInstance() { lock(typeof(LocalPriceCache)) @@ -64,13 +61,15 @@ namespace MarketData.Cache lock(typeof(LocalPriceCache)) { List symbols=new List(priceCache.Keys); + Dictionary maxDbDates = PricingDA.GetLatestDates(symbols); + foreach(String symbol in symbols) { PricesByDate symbolPrices=priceCache[symbol]; - DateTime maxDateDb=PricingDA.GetLatestDate(symbol); // get the latest date in the database DateTime maxDate=symbolPrices.MaxDate; // get the latest date in the cache - if(!maxDateDb.Date.Equals(maxDate.Date)) // if the cache date and the database date are not equal then reload 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 { + MDTrace.WriteLine(LogLevel.DEBUG,$"[LocalPriceCache] 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 @@ -78,6 +77,7 @@ namespace MarketData.Cache } 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 @@ -86,23 +86,7 @@ namespace MarketData.Cache } } } - //public void Add(PortfolioTrades portfolioTrades) - //{ - // lock(typeof(LocalPriceCache)) - // { - // Profiler profiler=new Profiler(); - // profiler.Start(); - // List symbols=portfolioTrades.Symbols; - // foreach(String symbol in symbols) - // { - // if(ContainsSymbol(symbol))continue; - // DateTime minDate=portfolioTrades.GetMinTradeDate(symbol); - // Prices prices=PricingDA.GetPrices(symbol,minDate); - // if(null==prices)continue; - // if(!priceCache.ContainsKey(symbol))priceCache.Add(symbol,prices.GetPricesByDate()); - // } - // } - //} + // 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. @@ -137,48 +121,6 @@ namespace MarketData.Cache } } } -// This version tries to be more efficient by examing what prices are required for the particular lot and just loading those. -// The version above is very brute force and always maintains min-present for all symbols even if they are no longer held. -// So if this more streamlined version gives problems then revert back to the more brute force method. - //public void Add(PortfolioTrades portfolioTrades) - //{ - // lock(typeof(LocalPriceCache)) - // { - // Profiler profiler=new Profiler(); - // profiler.Start(); - // List symbols=portfolioTrades.Symbols; - // foreach(String symbol in symbols) - // { - // DateTime minPortfolioTradeDate=portfolioTrades.GetMinTradeDate(symbol); - // DateTime maxPortfolioTradeDate=portfolioTrades.GetMaxTradeDate(symbol); - // if(!ContainsSymbol(symbol)) - // { - // Prices prices=null; - // if(Utility.IsEpoch(maxPortfolioTradeDate))prices=PricingDA.GetPrices(symbol,minPortfolioTradeDate); - // else prices=PricingDA.GetPrices(symbol,maxPortfolioTradeDate,minPortfolioTradeDate); - // if(null==prices)continue; - // foreach(Price price in prices)Add(price); - // } - // else - // { - // DateTime minCacheDate=GetMinCacheDate(symbol); - // if(minPortfolioTradeDate symbols,DateTime pricingDate) { foreach(String symbol in symbols) @@ -197,6 +140,7 @@ namespace MarketData.Cache Add(price); } } + public void Add(Price price) { lock(typeof(LocalPriceCache)) @@ -222,6 +166,7 @@ namespace MarketData.Cache PricesByDate symbolPrices=priceCache[symbol]; return symbolPrices.MinDate; } + public void RemoveDate(DateTime date) { lock(typeof(LocalPriceCache)) @@ -262,6 +207,7 @@ namespace MarketData.Cache return true; } } + public bool ContainsSymbol(String symbol) { lock(typeof(LocalPriceCache)) @@ -270,6 +216,7 @@ namespace MarketData.Cache return false; } } + public long Count() { long count=0; @@ -281,6 +228,7 @@ namespace MarketData.Cache } return count; } + private void ThreadProc() { int quantums=0; @@ -296,11 +244,11 @@ namespace MarketData.Cache lock(thisLock) { lastCount=Count(); - MDTrace.WriteLine(LogLevel.DEBUG,String.Format("LocalPriceCache Symbols: {0}. Items in cache: {1}.",priceCache.Keys.Count,Utility.FormatNumber(lastCount,0,true))); + MDTrace.WriteLine(LogLevel.DEBUG,String.Format("[LocalPriceCache:ThreadProc] Symbols: {0}. Items in cache: {1}.",priceCache.Keys.Count,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,String.Format("[LocalPriceCache:ThreadProc] Thread ended. Items in cache:{0}",Utility.FormatNumber(lastCount,0,true))); } } } diff --git a/MarketData/MarketDataLib/DataAccess/PricingDA.cs b/MarketData/MarketDataLib/DataAccess/PricingDA.cs index a870a6c..15e4797 100755 --- a/MarketData/MarketDataLib/DataAccess/PricingDA.cs +++ b/MarketData/MarketDataLib/DataAccess/PricingDA.cs @@ -285,6 +285,50 @@ namespace MarketData.DataAccess if(null!=sqlConnection) sqlConnection.Close(); } } + + public static Dictionary GetLatestDates(List symbols) + { + MySqlConnection sqlConnection = null; + MySqlDataReader sqlDataReader = null; + MySqlCommand sqlCommand = null; + String strQuery = null; + Dictionary latestDates = new Dictionary(); + + try + { + StringBuilder sb = new StringBuilder(); + sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data")); + sb.Append(" select symbol, max(date) as date "); + sb.Append(" from prices where symbol in").Append(SqlUtils.CreateInClause(symbols)); + sb.Append(" group by symbol order by symbol"); + strQuery = sb.ToString(); + sqlCommand = new MySqlCommand(strQuery, sqlConnection); + sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT; + sqlDataReader = sqlCommand.ExecuteReader(); + while (sqlDataReader.Read()) + { + if(sqlDataReader.IsDBNull(0) || sqlDataReader.IsDBNull(1))continue; + String symbol = sqlDataReader.GetString(0); + DateTime latestDate = sqlDataReader.GetDateTime(1); + if(latestDates.ContainsKey(symbol))continue; + latestDates.Add(symbol, latestDate); + } + return latestDates; + } + catch (Exception exception) + { + MDTrace.WriteLine(LogLevel.DEBUG,exception); + MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Query was {0}",strQuery)); + return latestDates; + } + finally + { + if (null != sqlCommand) sqlCommand.Dispose(); + if (null != sqlDataReader) sqlDataReader.Close(); + if (null != sqlConnection) sqlConnection.Close(); + } + } + public static DateTime GetLatestDate(List symbols) { MySqlConnection sqlConnection = null;