/// <summary> /// Асинхронная загрузка исторических данных по фин. инструменту /// </summary> /// <param name="insStore">Поток данных</param> /// <param name="date1">Начальная дата</param> /// <param name="date2">Конечная дата</param> /// <param name="isLastDirty">Последняя дата содердит неполные данные</param> /// <param name="isForward">Загрузка блоками от начальной даты к конечной (иначе от конечной к начальной)</param> /// <param name="progress">Объект управления фоновой задачей</param> /// <param name="cancel">Объект отмены длительной операции</param> /// <returns>Асинхронная задача загрузки</returns> public async Task DownloadAsync(CommonData.InsStore insStore, DateTime date1, DateTime date2, bool isLastDirty, bool isForward, BgTaskProgress progress, CancellationToken cancel) { try { var parts = GetDownloadParts(insStore.Tf, date1, date2, isForward); int idx = 1; int count = parts.Count(); if (progress != null) { progress.OnStart(count > 1); } foreach (var part in parts) { if (cancel.IsCancellationRequested) { if (progress != null) { progress.OnAbort(); } break; } await SyncDataBlock(insStore, part.Date1, part.Date2, isLastDirty, cancel); if (progress != null) { progress.OnProgress((double)idx++ / count * 100); } } if (progress != null) { if (cancel.IsCancellationRequested) { progress.OnAbort(); } else { progress.OnComplete(); } } } catch (Exception ex) { if (progress != null) { progress.OnFault(ex); } } }
/// <summary> /// Загрузка одного потока /// </summary> /// <param name="args">Date1, Date2, [Dirty], Tf, Ticker, Ticker, ...</param> public async void HistoryDownloadAsync(List <string> args) { DateTime date1 = DateTime.Today; DateTime date2 = DateTime.Today; bool isLastDirty = false; Timeframes tf = Timeframes.Min; if (args.Count == 1) { if (args[0].Trim().ToLower() == "progress") { if (_progress != null) { ShowProgress(_progress); } else { _console.WriteLine("Нет операции"); } return; } else if (args[0].Trim().ToLower() == "cancel") { if (_cancel != null) { _cancel.Cancel(); _console.WriteLine("Операция прервана"); } else { _console.WriteLine("Нет операции"); } return; } } if (args.Count < 2) { _console.WriteError("Не указаны даты"); return; } DateTime d; if (DateTime.TryParse(args[0].Trim(), out d)) { date1 = d; } else { _console.WriteError("Неверно указана дата начала"); return; } if (DateTime.TryParse(args[1].Trim(), out d)) { date2 = d; } else { _console.WriteError("Неверно указана дата окончания"); return; } args.RemoveRange(0, 2); if (args.Count < 1) { _console.WriteError("Неверное число аргументов"); return; } if (args[0].Trim().ToLower() == "dirty") { isLastDirty = true; args.RemoveAt(0); } if (args.Count < 1) { _console.WriteError("Неверное число аргументов"); return; } Timeframes tf_; if (!Timeframes.TryParse <Timeframes>(args[0].Trim(), out tf_)) { _console.WriteError("Неверный агрумент: Timeframe"); return; } tf = tf_; args.RemoveAt(0); if (args.Count < 1) { _console.WriteError("Неверное число аргументов"); return; } List <CommonData.InsStore> insStores = new List <CommonData.InsStore>(); foreach (string ticker in args) { CommonData.InsStore insStore = _insStoreBL.GetInsStore(ticker, tf); if (insStore == null) { _console.WriteError("Не найден тикер: " + ticker); continue; } insStores.Add(insStore); } if (insStores.Count == 0) { _console.WriteError("Пустой список тикеров"); return; } if (_progress != null && _progress.IsWorking) { ShowProgress(_progress); return; } _console.WriteLine("Загрузка данных ... "); _progress = new BgTaskProgress(_syncContext, "Загрузка данных ..."); _cancel = new CancellationTokenSource(); _progress.OnStart(); int idx = 0; foreach (var insStore in insStores) { var instrum = _instrumBL.GetInstrumByID(insStore.InsID); if (instrum == null) { continue; } var p = _progress.AddChildProgress(instrum.ShortName); await _historyDownloader.DownloadAsync(insStore, date1, date2, isLastDirty, true, p, _cancel.Token); idx++; _progress.OnProgress((double)idx * 100 / insStores.Count); } _progress.OnComplete(); }
/// <summary> /// Асинхронная загрузка исторических данных /// </summary> /// <param name="toDate">Загрузка по эту дату включительно</param> /// <param name="isLastDirty">Данные за последний день неполные</param> /// <param name="progress">Объект управления фоновой задачей</param> /// <param name="cancel">Отмена длительной операции</param> /// <returns>Асинхронная задача загрузки</returns> public Task DownloadAllAsync(DateTime toDate, bool isLastDirty, BgTaskProgress progress, CancellationToken cancel) { return(Task.Run(() => { try { _logger.LogInformation("DownloadAll to {date}", toDate.ToString("yyyy-MM-dd")); var insStores = _insStoreBL.GetActiveInsStores(); int count = insStores.Count(); int idx = 1; if (progress != null) { progress.OnStart(count > 1); } Dictionary <CommonData.InsStore, BgTaskProgress> progresses = new Dictionary <CommonData.InsStore, BgTaskProgress>(); if (progress != null) { foreach (var ss in insStores) { string name = ""; var instrum = _instrumBL.GetInstrumByID(ss.InsID); if (instrum != null) { name = instrum.ShortName; } var child = progress.AddChildProgress(name); progresses.Add(ss, child); } } foreach (var insStore in insStores) { if (cancel.IsCancellationRequested) { if (progress != null) { progress.OnAbort(); } break; } var ssCal = _insStoreBL.GetInsStoreCalendar(insStore.InsStoreID); if (ssCal == null || ssCal.Periods == null) { continue; } DateTime fromDate; if (ssCal.Periods.Count() > 0) { var lastPeriod = ssCal.Periods.Last(); fromDate = lastPeriod.IsLastDirty ? lastPeriod.EndDate : lastPeriod.EndDate.AddDays(1); } else { fromDate = _insStoreBL.GetDefaultStartHistoryDate(toDate, insStore.Tf); } var p = progresses.ContainsKey(insStore) ? progresses[insStore] : null; DownloadAsync(insStore, fromDate, toDate, isLastDirty, true, p, cancel).Wait(); if (progress != null) { progress.OnProgress((double)idx++ / count * 100); } } if (progress != null) { if (cancel.IsCancellationRequested) { progress.OnAbort(); } else { progress.OnComplete(); } } _logger.LogInformation("DownloadAll complete."); } catch (Exception ex) { _logger.LogError(ex, "DownloadAll error."); if (progress != null) { progress.OnFault(ex); } } })); }