FileDataAccess.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. using MuchInfo.Chart.Data.EnumTypes;
  2. using MuchInfo.Chart.Data.Interfaces;
  3. using MuchInfo.Chart.Data.Models;
  4. using Newtonsoft.Json;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. namespace MuchInfo.Chart.DataAccess
  10. {
  11. /// <summary>
  12. /// 文件JSON存储
  13. /// </summary>
  14. public class FileDataAccess : IDataAccess
  15. {
  16. #region Methods
  17. #region Public Methods
  18. /// <summary>
  19. /// 获取数据
  20. /// </summary>
  21. /// <param name="symbol">商品代码</param>
  22. /// <param name="cycleType">周期类型</param>
  23. /// <param name="startTime">起始时间</param>
  24. /// <param name="endTime">结束时间</param>
  25. /// <param name="totalCount">记录条数</param>
  26. public IEnumerable<IBarDataPoint> GetDataPoints(string symbol, CycleType cycleType, DateTime startTime, DateTime endTime, int totalCount)
  27. {
  28. if (string.IsNullOrWhiteSpace(symbol)) return null;
  29. //周期为Nono,默认为Day
  30. var filePath = CombineFilePath(symbol, (cycleType == CycleType.None ? CycleType.Day : cycleType));
  31. if (!File.Exists(filePath)) return null;
  32. return GetDataPoints(filePath, startTime, endTime, totalCount);
  33. }
  34. /// <summary>
  35. /// 获取数据
  36. /// </summary>
  37. /// <param name="filePath">The file path.</param>
  38. /// <param name="startTime">起始时间</param>
  39. /// <param name="endTime">结束时间</param>
  40. /// <param name="totalCount">记录条数</param>
  41. /// <returns>IEnumerable{IBarDataPoint}.</returns>
  42. private IEnumerable<IBarDataPoint> GetDataPoints(string filePath, DateTime startTime, DateTime endTime, int totalCount)
  43. {
  44. try
  45. {
  46. IList<BarDataPoint> dataSoure;
  47. //获取数据
  48. using (StreamReader file = File.OpenText(filePath))
  49. {
  50. var serializer = new JsonSerializer();
  51. try
  52. {
  53. dataSoure = (IList<BarDataPoint>)serializer.Deserialize(file, typeof(IList<BarDataPoint>));
  54. }
  55. catch
  56. {
  57. return null;
  58. }
  59. }
  60. if (dataSoure == null || !dataSoure.Any()) return null;
  61. //记录条数小于零,默认取100条
  62. //返回数据按日间顺排序
  63. var count = totalCount <= 0 ? 100 : totalCount;
  64. if (startTime > endTime)
  65. {
  66. return dataSoure.Where(z => z.Date <= endTime)
  67. .OrderByDescending(z => z.Date)
  68. .Take(count).OrderBy(z => z.Date);
  69. }
  70. else
  71. {
  72. return dataSoure.Where(z => z.Date >= startTime && z.Date <= endTime)
  73. .OrderByDescending(z => z.Date)
  74. .Take(count).OrderBy(z => z.Date);
  75. }
  76. }
  77. catch (Exception ex)
  78. {
  79. throw ex;
  80. }
  81. }
  82. /// <summary>
  83. /// 保存数据
  84. /// </summary>
  85. /// <param name="symbol">商品代码</param>
  86. /// <param name="cycleType">周期类型</param>
  87. /// <param name="dataPoints">保存的数据</param>
  88. /// <exception cref="System.NotImplementedException"></exception>
  89. public void SaveDataPoints(string symbol, CycleType cycleType, IList<IBarDataPoint> dataPoints)
  90. {
  91. if (string.IsNullOrWhiteSpace(symbol) ||
  92. cycleType == CycleType.None ||
  93. dataPoints == null) return;
  94. var filePath = CombineFilePath(symbol, cycleType);
  95. SaveDataPoints(filePath, dataPoints);
  96. }
  97. /// <summary>
  98. /// Saves the data points.
  99. /// </summary>
  100. /// <param name="filePath">The file path.</param>
  101. /// <param name="dataPoints">The data points.</param>
  102. private void SaveDataPoints(string filePath, IList<IBarDataPoint> dataPoints)
  103. {
  104. try
  105. {
  106. IList<IBarDataPoint> totalDataPoints;
  107. if (File.Exists(filePath))
  108. {
  109. //获取源数据
  110. IList<BarDataPoint> source;
  111. try
  112. {
  113. using (StreamReader file = File.OpenText(filePath))
  114. {
  115. var serializer = new JsonSerializer();
  116. source = (IList<BarDataPoint>)serializer.Deserialize(file, typeof(IList<BarDataPoint>));
  117. }
  118. }
  119. catch
  120. {
  121. //反序列化出错,删除源文件,重新写入目标数据
  122. source = new List<BarDataPoint>();
  123. File.Delete(filePath);
  124. }
  125. //合并数据
  126. totalDataPoints = CombineDataPoints(source == null ? null : source.ToList<IBarDataPoint>(), dataPoints).ToList();
  127. }
  128. else
  129. {
  130. totalDataPoints = dataPoints;
  131. var fileInfo = new FileInfo(filePath);
  132. //创建目录
  133. if (fileInfo.Directory != null && !Directory.Exists(fileInfo.Directory.FullName))
  134. {
  135. Directory.CreateDirectory(fileInfo.Directory.FullName);
  136. }
  137. }
  138. //写JSON数据
  139. using (var file = File.CreateText(filePath))
  140. {
  141. var serializer = new JsonSerializer();
  142. serializer.Serialize(file, totalDataPoints);
  143. }
  144. }
  145. catch (Exception ex)
  146. {
  147. throw ex;
  148. }
  149. }
  150. #endregion Public Methods
  151. #region Private Methods
  152. /// <summary>
  153. /// 合并数据
  154. /// </summary>
  155. /// <param name="source">源数据</param>
  156. /// <param name="destination">目标数据</param>
  157. private IEnumerable<IBarDataPoint> CombineDataPoints(IList<IBarDataPoint> source, IList<IBarDataPoint> destination)
  158. {
  159. if (source == null && destination == null) return new List<IBarDataPoint>();
  160. if (source == null || !source.Any()) return destination;
  161. if (destination == null || !destination.Any()) return source;
  162. //找出源中存的数据
  163. var interesct = destination.Intersect(source, new DataPointComparer<IBarDataPoint>()).ToList();
  164. //找出源数据中不存在的数据
  165. var except = destination.Except(source, new DataPointComparer<IBarDataPoint>()).ToList();
  166. //从源中移除要更新的数据
  167. //合并不存在的数据
  168. //合并更新的数据
  169. var result = source.Except(interesct, new DataPointComparer<IBarDataPoint>())
  170. .Union(except)
  171. .Union(interesct);
  172. return result;
  173. }
  174. /// <summary>
  175. /// 生成数据文件路径
  176. /// </summary>
  177. /// <param name="symbol">商品代码</param>
  178. /// <param name="cycleType">Type of the cycle.</param>
  179. /// <returns>System.String.</returns>
  180. private string CombineFilePath(string symbol, CycleType cycleType)
  181. {
  182. return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", symbol + "_" + cycleType.ToString() + ".txt");
  183. }
  184. private string CombineFilePath(string symbol, TimeSpan timeSpan)
  185. {
  186. var timeSpanString = timeSpan.ToString().Replace(".", "_").Replace(":", "_");
  187. return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", symbol + "_" + timeSpanString + ".txt");
  188. }
  189. /// <summary>
  190. /// 依据周期和记录条生成EndTime
  191. /// </summary>
  192. /// <param name="time">时间</param>
  193. /// <param name="type">周期</param>
  194. /// <param name="count">记录条数</param>
  195. private DateTime CreateDateTime(DateTime time, CycleType type, int count)
  196. {
  197. switch (type)
  198. {
  199. case CycleType.Minute:
  200. return time.AddMinutes(count);
  201. case CycleType.Minute5:
  202. return time.AddMinutes(count * 5);
  203. case CycleType.Minute30:
  204. return time.AddMinutes(count * 30);
  205. case CycleType.Minute240:
  206. return time.AddMinutes(count * 240);
  207. case CycleType.Week:
  208. return time.AddDays(count * 7);
  209. case CycleType.Month:
  210. return time.AddMonths(count);
  211. case CycleType.Quarter:
  212. return time.AddMonths(count * 4);
  213. case CycleType.Year:
  214. return time.AddYears(count);
  215. default:
  216. return time.AddDays(count);
  217. }
  218. }
  219. #endregion Private Methods
  220. #endregion Methods
  221. public IEnumerable<IBarDataPoint> GetDataPoints(string symbol, TimeSpan timeSpan, DateTime startTime, DateTime endTime, int totalCount)
  222. {
  223. if (string.IsNullOrWhiteSpace(symbol)) return null;
  224. var filePath = CombineFilePath(symbol, timeSpan);
  225. if (!File.Exists(filePath)) return null;
  226. return GetDataPoints(filePath, startTime, endTime, totalCount);
  227. }
  228. /// <summary>
  229. /// 保存数据
  230. /// </summary>
  231. /// <param name="symbol">商品代码</param>
  232. /// <param name="timeSpan">The time span.</param>
  233. /// <param name="dataPoints">保存的数据</param>
  234. public void SaveDataPoints(string symbol, TimeSpan timeSpan, IList<IBarDataPoint> dataPoints)
  235. {
  236. if (string.IsNullOrWhiteSpace(symbol) || dataPoints == null) return;
  237. var filePath = CombineFilePath(symbol, timeSpan);
  238. SaveDataPoints(filePath, dataPoints);
  239. }
  240. }
  241. }