public static IDictionary <string, IList <Candle> > BuildCandles(IDictionary <string, IDictionary <DateTime, decimal> > pHistoryData, int intervalMinutes) { Dictionary <string, IList <Candle> > _candles = new Dictionary <string, IList <Candle> >(); foreach (string rateName in pHistoryData.Keys) { IDictionary <DateTime, decimal> historyData = pHistoryData[rateName]; List <Candle> candles = new List <Candle>(); _candles.Add(rateName, candles); if (historyData.Count() == 0) { continue; } DateTime minDate = historyData.Keys.Min(); DateTime lastDate = historyData.Keys.Max(); int firstIntervalStartMinute = ((minDate.Minute / 5) + 1) * 5; int minutesDiff = firstIntervalStartMinute - minDate.Minute; minDate = minDate.AddMinutes(minutesDiff); DateTime firstIntervalStartDate = new DateTime(minDate.Year, minDate.Month, minDate.Day, minDate.Hour, minDate.Minute, 0); DateTime currentTime = firstIntervalStartDate; while (currentTime < lastDate) { DateTime nextTime = currentTime.AddMinutes(intervalMinutes); Candle candle = new Candle(); candle.OpenTime = currentTime; DateTime?openTime = null; if (historyData.Keys.Where(item => item >= currentTime && item < nextTime).Count() > 0) { openTime = historyData.Keys.Where(item => item >= currentTime && item < nextTime).Min(); } if (!openTime.HasValue) { currentTime = currentTime.AddMinutes(intervalMinutes); continue; } DateTime?closeTime = null; if (historyData.Keys.Where(item => item >= currentTime && item < nextTime).Count() > 0) { closeTime = historyData.Keys.Where(item => item >= currentTime && item < nextTime).Max(); } if (!closeTime.HasValue) { currentTime = currentTime.AddMinutes(intervalMinutes); continue; } candle.RateName = rateName; candle.OpenPrice = historyData[openTime.Value]; candle.ClosePrice = historyData[closeTime.Value]; candle.HighPrice = historyData.Where(item => item.Key >= currentTime && item.Key < nextTime).Max(item => item.Value); candle.LowPrice = historyData.Where(item => item.Key >= currentTime && item.Key < nextTime).Min(item => item.Value); candles.Add(candle); currentTime = currentTime.AddMinutes(intervalMinutes); } Candle lastCandle = candles.OrderBy(item => item.OpenTime).LastOrDefault(); if (lastCandle != null) { foreach (KeyValuePair <DateTime, decimal> pair in historyData.Where(item => item.Key >= lastCandle.OpenTime && item.Key < lastCandle.OpenTime.AddMinutes(intervalMinutes))) { lastCandle.AddNewData(pair.Key, pair.Value); } } } return(_candles); }