static void Main(string[] args) { Security sber = new Security { Id = "SBER@TQBR", Board = ExchangeBoard.Micex }; Security gazp = new Security { Id = "GAZP@TQBS", Board = ExchangeBoard.Micex }; Security gmkn = new Security { Id = "GMKN@TQBS", Board = ExchangeBoard.Micex }; // создаем хранилище инструментов Финам // добавить инструменты можно через конструктор, так //var finamSecurityStorage = new FinamSecurityStorage(sber); // или так var finamSecurityStorage = new FinamSecurityStorage(new List <Security>() { sber, gmkn }); // или при помощи метода Add finamSecurityStorage.Add(gazp); // Создаем экземпляр класса FinamHistorySource. Этот объект управляет получением данных с Финама. FinamHistorySource _finamHistorySource = new FinamHistorySource(); // Создаем жранилище для нативных идентификаторов (родные идентификаторы инструментов Финама) var nativeIdStorage = new InMemoryNativeIdStorage(); bool isCanceled = false; // Задаем папку, где будут сохранены запрошенные данные.. Если папку не задавать, то // на диске данные сохранены не будут _finamHistorySource.DumpFolder = "DataHist"; // Выполняем обновление хранилища инструментов Финама // Перед добавлением каждого инструмента в хранилище вызывается функция (делегат) isCanceled, если функция возвращает false, то обновление // хранилища продолжается, если true, то прерывается. // При добавлении нового инструмента в хранилище вызывается функция (делегат) newSecurity. В нашем случае этот делегат имеет пустое тело (ничего не делает). _finamHistorySource.Refresh(finamSecurityStorage, nativeIdStorage, new Security(), s => {}, () => isCanceled); // Задаем таймфрем свечи var timeFrame = TimeSpan.FromMinutes(1); var now = DateTime.Now; var end = new DateTime(now.Year, now.Month, now.Day - 1, 0, 0, 0); var start = end.AddDays(-2); // Запрашиваем свечи с Финама var candles = _finamHistorySource.GetCandles(gazp, nativeIdStorage, timeFrame, start, end); // Запрашиваем тики var ticks = _finamHistorySource.GetTicks(gmkn, nativeIdStorage, start, end); Console.Read(); }
public MainWindow() { InitializeComponent(); HistoryPath.Folder = @"..\..\..\HistoryData\".ToFullPath(); if (LocalizedStrings.ActiveLanguage == Languages.Russian) { SecId.Text = "RIZ2@FORTS"; From.Value = new DateTime(2012, 10, 1); To.Value = new DateTime(2012, 10, 25); TimeFrame.SelectedIndex = 1; } else { SecId.Text = "@ES#@CMEMINI"; From.Value = new DateTime(2015, 8, 1); To.Value = new DateTime(2015, 8, 31); TimeFrame.SelectedIndex = 0; } _progressBars.AddRange(new[] { TicksProgress, TicksAndDepthsProgress, DepthsProgress, CandlesProgress, CandlesAndDepthsProgress, OrderLogProgress, Level1Progress, FinamCandlesProgress, YahooCandlesProgress }); _checkBoxes.AddRange(new[] { TicksCheckBox, TicksAndDepthsCheckBox, DepthsCheckBox, CandlesCheckBox, CandlesAndDepthsCheckBox, OrderLogCheckBox, Level1CheckBox, FinamCandlesCheckBox, YahooCandlesCheckBox, }); _finamHistorySource = new FinamHistorySource(_nativeIdStorage, _exchangeInfoProvider); }
protected override TimeSpan OnProcess() { var source = new FinamHistorySource(); if (_settings.UseTemporaryFiles != TempFiles.NotUse) source.DumpFolder = GetTempPath(); var allSecurity = this.GetAllSecurity(); // если фильтр по инструментам выключен (выбран инструмент все инструменты) var selectedSecurities = (allSecurity != null ? this.ToHydraSecurities(_finamSecurityStorage.Securities) : Settings.Securities).ToArray(); var hasNonFinam = selectedSecurities.Any(s => !IsFinam(s)); if (selectedSecurities.IsEmpty() || hasNonFinam) { this.AddWarningLog(selectedSecurities.IsEmpty() ? LocalizedStrings.Str2289 : LocalizedStrings.Str2290.Put("Finam")); source.Refresh(_finamSecurityStorage, new Security(), SaveSecurity, () => !CanProcess(false)); selectedSecurities = (allSecurity != null ? this.ToHydraSecurities(_finamSecurityStorage.Securities) : Settings.Securities) .Where(s => { var retVal = IsFinam(s); if (!retVal) this.AddWarningLog(LocalizedStrings.Str2291Params, s.Security.Id, "Finam"); return retVal; }).ToArray(); } if (!CanProcess()) return base.OnProcess(); if (selectedSecurities.IsEmpty()) { this.AddWarningLog(LocalizedStrings.Str2292); return TimeSpan.MaxValue; } var startDate = _settings.StartFrom; var endDate = DateTime.Today - TimeSpan.FromDays(_settings.DayOffset); var allDates = startDate.Range(endDate, TimeSpan.FromDays(1)).ToArray(); foreach (var security in selectedSecurities) { if (!CanProcess()) break; #region LoadTrades if ((allSecurity ?? security).MarketDataTypesSet.Contains(typeof(Trade))) { var storage = StorageRegistry.GetTradeStorage(security.Security, _settings.Drive, _settings.StorageFormat); var emptyDates = allDates.Except(storage.Dates).ToArray(); if (emptyDates.IsEmpty()) { this.AddInfoLog(LocalizedStrings.Str2293Params, security.Security.Id); } else { foreach (var emptyDate in emptyDates) { if (!CanProcess()) break; if (_settings.IgnoreWeekends && !security.IsTradeDate(emptyDate)) { this.AddDebugLog(LocalizedStrings.WeekEndDate, emptyDate); continue; } try { this.AddInfoLog(LocalizedStrings.Str2294Params, emptyDate, security.Security.Id); var trades = source.GetTicks(security.Security, emptyDate, emptyDate); if (trades.Any()) SaveTicks(security, trades); else this.AddDebugLog(LocalizedStrings.NoData); if (_settings.UseTemporaryFiles == TempFiles.UseAndDelete) File.Delete(source.GetDumpFile(security.Security, emptyDate, emptyDate, typeof(ExecutionMessage), ExecutionTypes.Tick)); } catch (Exception ex) { HandleError(new InvalidOperationException(LocalizedStrings.Str2295Params .Put(emptyDate, security.Security.Id), ex)); } } } } else this.AddDebugLog(LocalizedStrings.MarketDataNotEnabled, security.Security.Id, typeof(Trade).Name); #endregion if (!CanProcess()) break; #region LoadCandles foreach (var series in (allSecurity ?? security).CandleSeries) { if (!CanProcess()) break; if (series.CandleType != typeof(TimeFrameCandle)) { this.AddWarningLog(LocalizedStrings.Str2296Params, series); continue; } var storage = StorageRegistry.GetCandleStorage(series.CandleType, security.Security, series.Arg, _settings.Drive, _settings.StorageFormat); var emptyDates = allDates.Except(storage.Dates).ToArray(); if (emptyDates.IsEmpty()) { this.AddInfoLog(LocalizedStrings.Str2297Params, series.Arg, security.Security.Id); continue; } var currDate = emptyDates.First(); var lastDate = emptyDates.Last(); while (currDate <= lastDate) { if (!CanProcess()) break; if (_settings.IgnoreWeekends && !security.IsTradeDate(currDate)) { this.AddDebugLog(LocalizedStrings.WeekEndDate, currDate); currDate = currDate.AddDays(1); continue; } try { var till = currDate.AddDays(_settings.CandleDayStep - 1); this.AddInfoLog(LocalizedStrings.Str2298Params, series.Arg, currDate, till, security.Security.Id); var candles = source.GetCandles(security.Security, (TimeSpan)series.Arg, currDate, till); if (candles.Any()) SaveCandles(security, candles); else this.AddDebugLog(LocalizedStrings.NoData); if (_settings.UseTemporaryFiles == TempFiles.UseAndDelete) File.Delete(source.GetDumpFile(security.Security, currDate, till, typeof(TimeFrameCandleMessage), series.Arg)); currDate = currDate.AddDays(_settings.CandleDayStep); } catch (Exception ex) { HandleError(new InvalidOperationException(LocalizedStrings.Str2299Params .Put(series.Arg, currDate, security.Security.Id), ex)); } } } #endregion } if (CanProcess()) { this.AddInfoLog(LocalizedStrings.Str2300); _settings.StartFrom = endDate; SaveSettings(); } return base.OnProcess(); }
protected override TimeSpan OnProcess() { var source = new FinamHistorySource(); if (_settings.UseTemporaryFiles != TempFiles.NotUse) { source.DumpFolder = GetTempPath(); } var allSecurity = this.GetAllSecurity(); // если фильтр по инструментам выключен (выбран инструмент все инструменты) var selectedSecurities = (allSecurity != null ? this.ToHydraSecurities(_finamSecurityStorage.Securities) : Settings.Securities).ToArray(); var hasNonFinam = selectedSecurities.Any(s => !IsFinam(s)); if (selectedSecurities.IsEmpty() || hasNonFinam) { this.AddWarningLog(selectedSecurities.IsEmpty() ? LocalizedStrings.Str2289 : LocalizedStrings.Str2290.Put("Finam")); source.Refresh(_finamSecurityStorage, new Security(), SaveSecurity, () => !CanProcess(false)); selectedSecurities = (allSecurity != null ? this.ToHydraSecurities(_finamSecurityStorage.Securities) : Settings.Securities) .Where(s => { var retVal = IsFinam(s); if (!retVal) { this.AddWarningLog(LocalizedStrings.Str2291Params, s.Security.Id, "Finam"); } return(retVal); }).ToArray(); } if (!CanProcess()) { return(base.OnProcess()); } if (selectedSecurities.IsEmpty()) { this.AddWarningLog(LocalizedStrings.Str2292); return(TimeSpan.MaxValue); } var startDate = _settings.StartFrom; var endDate = DateTime.Today - TimeSpan.FromDays(_settings.DayOffset); var allDates = startDate.Range(endDate, TimeSpan.FromDays(1)).ToArray(); foreach (var security in selectedSecurities) { if (!CanProcess()) { break; } #region LoadTrades if ((allSecurity ?? security).MarketDataTypesSet.Contains(typeof(Trade))) { var storage = StorageRegistry.GetTradeStorage(security.Security, _settings.Drive, _settings.StorageFormat); var emptyDates = allDates.Except(storage.Dates).ToArray(); if (emptyDates.IsEmpty()) { this.AddInfoLog(LocalizedStrings.Str2293Params, security.Security.Id); } else { foreach (var emptyDate in emptyDates) { if (!CanProcess()) { break; } if (_settings.IgnoreWeekends && !security.IsTradeDate(emptyDate)) { this.AddDebugLog(LocalizedStrings.WeekEndDate, emptyDate); continue; } try { this.AddInfoLog(LocalizedStrings.Str2294Params, emptyDate, security.Security.Id); var trades = source.GetTrades(security.Security, emptyDate, emptyDate); if (trades.Any()) { SaveTrades(security, trades); } else { this.AddDebugLog(LocalizedStrings.NoData); } if (_settings.UseTemporaryFiles == TempFiles.UseAndDelete) { File.Delete(source.GetDumpFile(security.Security, emptyDate, emptyDate, typeof(Trade), null)); } } catch (Exception ex) { HandleError(new InvalidOperationException(LocalizedStrings.Str2295Params .Put(emptyDate, security.Security.Id), ex)); } } } } else { this.AddDebugLog(LocalizedStrings.MarketDataNotEnabled, security.Security.Id, typeof(Trade).Name); } #endregion if (!CanProcess()) { break; } #region LoadCandles foreach (var series in (allSecurity ?? security).CandleSeries) { if (!CanProcess()) { break; } if (series.CandleType != typeof(TimeFrameCandle)) { this.AddWarningLog(LocalizedStrings.Str2296Params, series); continue; } var storage = StorageRegistry.GetCandleStorage(series.CandleType, security.Security, series.Arg, _settings.Drive, _settings.StorageFormat); var emptyDates = allDates.Except(storage.Dates).ToArray(); if (emptyDates.IsEmpty()) { this.AddInfoLog(LocalizedStrings.Str2297Params, series.Arg, security.Security.Id); continue; } foreach (var emptyDate in emptyDates) { if (!CanProcess()) { break; } if (_settings.IgnoreWeekends && !security.IsTradeDate(emptyDate)) { this.AddDebugLog(LocalizedStrings.WeekEndDate, emptyDate); continue; } try { this.AddInfoLog(LocalizedStrings.Str2298Params, series.Arg, emptyDate, security.Security.Id); var candles = source.GetCandles(security.Security, (TimeSpan)series.Arg, emptyDate, emptyDate); if (candles.Any()) { SaveCandles(security, candles); } else { this.AddDebugLog(LocalizedStrings.NoData); } if (_settings.UseTemporaryFiles == TempFiles.UseAndDelete) { File.Delete(source.GetDumpFile(security.Security, emptyDate, emptyDate, typeof(TimeFrameCandle), series.Arg)); } } catch (Exception ex) { HandleError(new InvalidOperationException(LocalizedStrings.Str2299Params .Put(series.Arg, emptyDate, security.Security.Id), ex)); } } } #endregion } if (CanProcess()) { this.AddInfoLog(LocalizedStrings.Str2300); _settings.StartFrom = endDate; SaveSettings(); } return(base.OnProcess()); }