/// <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); } } }
public void ShowProgress(BgTaskProgress progress, int level = 0) { string spaces = new string('\t', level); _console.WriteLine(string.Format("{0}{1} : {2} : {3}%", spaces, progress.Name, progress.StateStr, progress.Percent.ToString("#0.00"))); if (progress.Fault != null) { _console.WriteLine(spaces + progress.Fault.ToString()); } foreach (var p in progress.Children) { ShowProgress(p, level + 1); } }
public async void TestRunAsync(List <string> args) { 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() == "stop") { if (_testRun != null) { _testRun.Stop(); _console.WriteLine("Тестовый прогон остановлен"); } else { _console.WriteLine("Нет операции"); } return; } } if (args.Count < 2) { _console.WriteError("Неверное число аргументов"); return; } int tickSourceID; int testConfigID; int?accountID = null; int r; if (int.TryParse(args[0].Trim(), out r)) { tickSourceID = r; } else { _console.WriteError("Неверно указан id источника"); return; } if (int.TryParse(args[1].Trim(), out r)) { testConfigID = r; } else { _console.WriteError("Неверно указан id тестовой конфигурации"); return; } if (args.Count >= 3) { if (int.TryParse(args[2].Trim(), out r)) { accountID = r; } else { _console.WriteError("Неверно указан id счета"); return; } } _console.WriteLine("Загрузка данных ... "); _testRun = new TestRun(_accountBL, _accountDA, _instrumBL, _insStoreBL, _tickSourceBL, _testConfigBL, _logger, _config, _posBL, _reposBL); _progress = new BgTaskProgress(_syncContext, "Тестовый прогон"); try { bool isSuccess = await _testRun.Initialize(tickSourceID, testConfigID, accountID, _progress); if (isSuccess) { var stat = _testRun.GetTickSourceStatistics(); _console.WriteLine(string.Format("Всего загружено дней: {0}, тиков: {1}", stat.TotalDaysCount.ToString(), stat.TotalTicksCount.ToString())); _console.WriteLine(string.Format("Из них синтезировано дней: {0} ({1}%), тиков: {2} ({3}%)", stat.SynDaysCount.ToString(), (stat.TotalDaysCount != 0 ? (decimal)stat.SynDaysCount * 100 / stat.TotalDaysCount : 0).ToString("##0.0#"), stat.SynTicksCount, (stat.TotalTicksCount != 0 ? (decimal)stat.SynTicksCount * 100 / stat.TotalTicksCount : 0).ToString("##0.0#"))); _console.WriteLine("Тестовый прогон выполняется ... "); _testRun.Start(TestRunFinished); } else { _console.WriteLine("Ошибка при инициализации."); } } catch (Exception ex) { _console.WriteError(ex.ToString()); } }
public void HistoryDownloadAll(List <string> args) { bool isLastDirty = true; DateTime toDate = DateTime.Today; bool isProgress = false; bool isCancel = false; DateTime d; foreach (var arg in args) { if (DateTime.TryParse(arg, out d)) { toDate = d; continue; } if (arg.ToLower() == "full") { isLastDirty = false; } if (arg.ToLower() == "progress") { isProgress = true; } if (arg.ToLower() == "cancel") { isCancel = true; } } if (isProgress) { if (_progress != null) { ShowProgress(_progress); } else { _console.WriteLine("Нет фоновой операции"); } return; } if (isCancel) { if (_cancel != null) { _cancel.Cancel(); _console.WriteLine("Прервано"); } return; } if (_progress == null || !_progress.IsWorking) { _console.WriteLine("Загрузка котировок: toDate = " + toDate.ToString("dd/MM/yyyy") + ", isLastDirty = " + isLastDirty.ToString()); _progress = new BgTaskProgress(_syncContext, "Загрузка данных ..."); _cancel = new CancellationTokenSource(); _historyDownloader.DownloadAllAsync(toDate, isLastDirty, _progress, _cancel.Token); } else { ShowProgress(_progress); } }
/// <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); } } })); }