Exemplo n.º 1
0
        private void LoadData(string path)
        {
            _candle = null;
            _allCandles.Clear();

            Chart.Reset(new IChartElement[] { _candleElement, _activeOrdersElement });

            var storage = new StorageRegistry();

            var maxDays = 2;

            BusyIndicator.IsBusy = true;

            Task.Factory.StartNew(() =>
            {
                var date = DateTime.MinValue;

                foreach (var tick in storage.GetTickMessageStorage(_security, new LocalMarketDataDrive(path)).Load())
                {
                    AppendTick(_security, tick);

                    if (date != tick.ServerTime.Date)
                    {
                        date = tick.ServerTime.Date;

                        this.GuiAsync(() =>
                        {
                            BusyIndicator.BusyContent = date.ToString();
                        });

                        maxDays--;

                        if (maxDays == 0)
                        {
                            break;
                        }
                    }
                }
            })
            .ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    Error(t.Exception.Message);
                }

                this.GuiAsync(() =>
                {
                    BusyIndicator.IsBusy            = false;
                    Chart.IsAutoRange               = false;
                    _area.YAxises.First().AutoRange = false;

                    Chart.Draw(DateTimeOffset.MinValue, _activeOrdersElement, _chartOrders);

                    Log($"Loaded {_allCandles.Count} candles");
                });
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Exemplo n.º 2
0
        private IEnumerableEx <CandleMessage> GetCandles()
        {
            var from = From.Value;
            var to   = To.Value.EndOfDay();

            switch (BuildFrom.SelectedIndex)
            {
            case 0:
                return(StorageRegistry
                       .GetCandleMessageStorage(CandleSeries.CandleType.ToCandleMessageType(), CandleSeries.Security, CandleSeries.Arg, Drive, StorageFormat)
                       .Load(from, to));

            case 1:
                return(StorageRegistry
                       .GetTickMessageStorage(SelectedSecurity, Drive, StorageFormat)
                       .Load(from, to)
                       .ToCandles(CandleSeries));

            case 2:
                return(StorageRegistry
                       .GetOrderLogMessageStorage(SelectedSecurity, Drive, StorageFormat)
                       .Load(from, to)
                       .ToTicks()
                       .ToCandles(CandleSeries));

            case 3:
                return(StorageRegistry
                       .GetQuoteMessageStorage(SelectedSecurity, Drive, StorageFormat)
                       .Load(from, to)
                       .ToCandles(CandleSeries));

            case 4:
                return(StorageRegistry
                       .GetOrderLogMessageStorage(SelectedSecurity, Drive, StorageFormat)
                       .Load(from, to)
                       .ToMarketDepths(OrderLogBuilders.Plaza2.CreateBuilder(SelectedSecurity.ToSecurityId()))
                       .ToCandles(CandleSeries));

            case 5:
                return(StorageRegistry
                       .GetCandleMessageStorage(typeof(TimeFrameCandleMessage), SelectedSecurity, TimeSpan.FromMinutes(1), Drive, StorageFormat)
                       .Load(from, to)
                       .ToTrades(SelectedSecurity.VolumeStep ?? 1m)
                       .ToCandles(CandleSeries));

            case 6:
                return(StorageRegistry
                       .GetLevel1MessageStorage(SelectedSecurity, Drive, StorageFormat)
                       .Load(from, to)
                       .ToTicks()
                       .ToCandles(CandleSeries));

            default:
                throw new InvalidOperationException(LocalizedStrings.Str2874Params.Put(BuildFrom.SelectedIndex));
            }
        }
Exemplo n.º 3
0
        private void LoadData(string path)
        {
            var storage = new StorageRegistry();

            var maxDays = 2;

            BusyIndicator.IsBusy = true;

            Task.Factory.StartNew(() =>
            {
                var date = DateTime.MinValue;

                foreach (var tick in storage.GetTickMessageStorage(_security, new LocalMarketDataDrive(path)).Load())
                {
                    AppendTick(tick);
                    _lastTime = tick.ServerTime;

                    if (date != tick.ServerTime.Date)
                    {
                        date = tick.ServerTime.Date;

                        this.GuiAsync(() =>
                        {
                            BusyIndicator.BusyContent = date.ToString();
                        });

                        maxDays--;

                        if (maxDays == 0)
                        {
                            break;
                        }
                    }
                }
            })
            .ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    Error(t.Exception.Message);
                }

                BusyIndicator.IsBusy = false;
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Exemplo n.º 4
0
        private IEnumerableEx <ExecutionMessage> GetTrades()
        {
            switch (BuildFrom.SelectedIndex)
            {
            case 0:
            {
                var trades = StorageRegistry
                             .GetTickMessageStorage(SelectedSecurity, Drive, StorageFormat)
                             .Load(From, To + TimeHelper.LessOneDay);

                if (IsNonSystem.IsChecked == false)
                {
                    trades = trades.Where(t => t.IsSystem != false).ToEx(trades.Count);
                }

                return(trades);
            }

            case 1:
            {
                var orderLog = StorageRegistry
                               .GetOrderLogMessageStorage(SelectedSecurity, Drive, StorageFormat)
                               .Load(From, To + TimeHelper.LessOneDay);

                if (IsNonSystem.IsChecked == false)
                {
                    orderLog = orderLog.Where(i => i.IsSystem != false).ToEx(orderLog.Count);
                }

                return(orderLog.ToTicks());
            }

            case 2:
            {
                var level1 = StorageRegistry
                             .GetLevel1MessageStorage(SelectedSecurity, Drive, StorageFormat)
                             .Load(From, To + TimeHelper.LessOneDay);

                return(level1.ToTicks());
            }

            default:
                throw new InvalidOperationException();
            }
        }
Exemplo n.º 5
0
        protected override TimeSpan OnProcess()
        {
            // если фильтр по инструментам выключен (выбран инструмент все инструменты)
            if (this.GetAllSecurity() != null)
            {
                this.AddWarningLog(LocalizedStrings.Str2549);
                return(TimeSpan.MaxValue);
            }

            if (_settings.IsRealTime)
            {
                return(base.OnProcess());
            }

            var startDate = _settings.StartFrom;
            var endDate   = DateTime.Today - TimeSpan.FromDays(_settings.Offset);

            var allDates = startDate.Range(endDate, TimeSpan.FromDays(1)).ToArray();

            var hasSecurities = false;

            foreach (var security in GetWorkingSecurities())
            {
                hasSecurities = true;

                if (!CanProcess())
                {
                    break;
                }

                if (security.MarketDataTypesSet.Contains(typeof(Level1ChangeMessage)))
                {
                    var tradeStorage = StorageRegistry.GetTickMessageStorage(security.Security, _settings.Drive, _settings.StorageFormat);

                    foreach (var date in allDates.Except(tradeStorage.Dates))
                    {
                        if (!CanProcess())
                        {
                            break;
                        }

                        if (_settings.IgnoreWeekends && !security.IsTradeDate(date))
                        {
                            this.AddDebugLog(LocalizedStrings.WeekEndDate, date);
                            continue;
                        }

                        this.AddInfoLog(LocalizedStrings.Str2294Params, date, security.Security.Id);

                        bool isSuccess;
                        var  trades = Connector.Connector.GetHistoricalLevel1(security.Security.ToSecurityId(), _settings.StartFrom, _settings.StartFrom.EndOfDay(), out isSuccess);

                        if (isSuccess)
                        {
                            if (trades.Any())
                            {
                                SaveLevel1Changes(security, trades);
                            }
                            else
                            {
                                this.AddDebugLog(LocalizedStrings.NoData);
                            }
                        }
                        else
                        {
                            this.AddErrorLog(LocalizedStrings.Str2550);
                        }
                    }
                }
                else
                {
                    this.AddDebugLog(LocalizedStrings.MarketDataNotEnabled, security.Security.Id, typeof(Level1ChangeMessage).Name);
                }

                foreach (var series in security.CandleSeries)
                {
                    if (!CanProcess())
                    {
                        break;
                    }

                    if (series.CandleType != typeof(TimeFrameCandle))
                    {
                        this.AddWarningLog(LocalizedStrings.Str2296Params, series);
                        continue;
                    }

                    var candleStorage = StorageRegistry.GetCandleMessageStorage(series.CandleType.ToCandleMessageType(), security.Security, series.Arg, _settings.Drive, _settings.StorageFormat);

                    foreach (var date in allDates.Except(candleStorage.Dates))
                    {
                        if (!CanProcess())
                        {
                            break;
                        }

                        if (_settings.IgnoreWeekends && !security.IsTradeDate(date))
                        {
                            this.AddDebugLog(LocalizedStrings.WeekEndDate, date);
                            continue;
                        }

                        this.AddInfoLog(LocalizedStrings.Str2298Params, series, date, security.Security.Id);

                        bool isSuccess;
                        var  candles = Connector.Connector.GetHistoricalCandles(security.Security, series.CandleType, series.Arg, date, date.EndOfDay(), out isSuccess);

                        if (isSuccess)
                        {
                            if (candles.Any())
                            {
                                SaveCandles(security, candles);
                            }
                            else
                            {
                                this.AddDebugLog(LocalizedStrings.NoData);
                            }
                        }
                        else
                        {
                            this.AddErrorLog(LocalizedStrings.Str2550);
                        }
                    }
                }
            }

            if (!hasSecurities)
            {
                this.AddWarningLog(LocalizedStrings.Str2292);
                return(TimeSpan.MaxValue);
            }

            if (CanProcess())
            {
                this.AddInfoLog(LocalizedStrings.Str2300);

                _settings.StartFrom = endDate;
                SaveSettings();
            }

            return(_settings.Interval);
        }
Exemplo n.º 6
0
        protected override TimeSpan OnProcess()
        {
            // если фильтр по инструментам выключен (выбран инструмент все инструменты)
            if (this.GetAllSecurity() != null)
            {
                this.AddWarningLog(LocalizedStrings.Str2549);
                return(TimeSpan.MaxValue);
            }

            if (_settings.IsRealTime)
            {
                return(base.OnProcess());
            }

            var startDate = _settings.StartFrom;
            var endDate   = DateTime.Today - TimeSpan.FromDays(_settings.Offset);

            var allDates = startDate.Range(endDate, TimeSpan.FromDays(1)).ToArray();

            var hasSecurities = false;

            foreach (var security in GetWorkingSecurities())
            {
                hasSecurities = true;

                if (!CanProcess())
                {
                    break;
                }

                if (security.IsLevel1Enabled())
                {
                    var tradeStorage = StorageRegistry.GetTickMessageStorage(security.Security, _settings.Drive, _settings.StorageFormat);

                    foreach (var date in allDates.Except(tradeStorage.Dates))
                    {
                        if (!CanProcess())
                        {
                            break;
                        }

                        if (_settings.IgnoreWeekends && !security.IsTradeDate(date))
                        {
                            this.AddDebugLog(LocalizedStrings.WeekEndDate, date);
                            continue;
                        }

                        this.AddInfoLog(LocalizedStrings.Str2294Params, date, security.Security.Id);

                        bool isSuccess;
                        var  trades = ((BarChartTrader)Connector).GetHistoricalTicks(security.Security, _settings.StartFrom, _settings.StartFrom.EndOfDay(), out isSuccess);

                        if (isSuccess)
                        {
                            if (trades.Any())
                            {
                                SaveTicks(security, trades);
                            }
                            else
                            {
                                this.AddDebugLog(LocalizedStrings.NoData);
                            }
                        }
                        else
                        {
                            this.AddErrorLog(LocalizedStrings.Str2550);
                        }
                    }
                }
                else
                {
                    this.AddDebugLog(LocalizedStrings.MarketDataNotEnabled, security.Security.Id, typeof(Level1ChangeMessage).Name);
                }

                foreach (var pair in security.GetCandleSeries())
                {
                    if (!CanProcess())
                    {
                        break;
                    }

                    if (pair.MessageType != typeof(TimeFrameCandleMessage))
                    {
                        this.AddWarningLog(LocalizedStrings.Str2296Params, pair);
                        continue;
                    }

                    var tf = (TimeSpan)pair.Arg;

                    var candleStorage = StorageRegistry.GetCandleMessageStorage(pair.MessageType, security.Security, tf, _settings.Drive, _settings.StorageFormat);
                    var emptyDates    = allDates.Except(candleStorage.Dates).ToArray();

                    if (emptyDates.IsEmpty())
                    {
                        this.AddInfoLog(LocalizedStrings.Str2297Params, tf, 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;
                        }

                        var till = currDate.AddDays(_settings.CandleDayStep - 1).EndOfDay();
                        this.AddInfoLog(LocalizedStrings.Str2298Params, pair, currDate, till, security.Security.Id);

                        bool isSuccess;
                        var  candles = ((BarChartTrader)Connector).GetHistoricalCandles(security.Security, pair.MessageType, tf, currDate, till, out isSuccess);

                        if (isSuccess)
                        {
                            if (candles.Any())
                            {
                                SaveCandles(security, candles);
                            }
                            else
                            {
                                this.AddDebugLog(LocalizedStrings.NoData);
                            }
                        }
                        else
                        {
                            this.AddErrorLog(LocalizedStrings.Str2550);
                        }

                        currDate = currDate.AddDays(_settings.CandleDayStep);
                    }
                }
            }

            if (!hasSecurities)
            {
                this.AddWarningLog(LocalizedStrings.Str2292);
                return(TimeSpan.MaxValue);
            }

            if (CanProcess())
            {
                this.AddInfoLog(LocalizedStrings.Str2300);

                _settings.StartFrom = endDate;
                SaveSettings();
            }

            return(_settings.Interval);
        }
Exemplo n.º 7
0
        private void LoadData(CandleSeries series)
        {
            var msgType = series.CandleType.ToCandleMessageType();

            _transactionId = _transactionIdGenerator.GetNextId();
            _holder.Clear();
            _holder.CreateCandleSeries(_transactionId, series);

            _candleTransform.Process(new ResetMessage());
            _candleBuilder = _builderProvider.Get(msgType.ToCandleMarketDataType());

            var storage = new StorageRegistry();

            BusyIndicator.IsBusy = true;

            var path    = HistoryPath.Folder;
            var isBuild = BuildFromTicks.IsChecked == true;
            var format  = Format.SelectedFormat;

            var maxDays = (isBuild || series.CandleType != typeof(TimeFrameCandle))
                                ? 2
                                : 30 * (int)((TimeSpan)series.Arg).TotalMinutes;

            _mdMsg = series.ToMarketDataMessage(true);

            Task.Factory.StartNew(() =>
            {
                var date = DateTime.MinValue;

                if (isBuild)
                {
                    foreach (var tick in storage.GetTickMessageStorage(series.Security, new LocalMarketDataDrive(path), format).Load())
                    {
                        _tradeGenerator.Process(tick);

                        if (_candleTransform.Process(tick))
                        {
                            var candles = _candleBuilder.Process(_mdMsg, _currCandle, _candleTransform);

                            foreach (var candle in candles)
                            {
                                _currCandle = candle;
                                _updatedCandles.Add((CandleMessage)candle.Clone());
                            }
                        }

                        _lastTime = tick.ServerTime;

                        if (date != tick.ServerTime.Date)
                        {
                            date = tick.ServerTime.Date;

                            var str = date.To <string>();
                            this.GuiAsync(() => BusyIndicator.BusyContent = str);

                            maxDays--;

                            if (maxDays == 0)
                            {
                                break;
                            }
                        }
                    }
                }
                else
                {
                    foreach (var candleMsg in storage.GetCandleMessageStorage(msgType, series.Security, series.Arg, new LocalMarketDataDrive(path), format).Load())
                    {
                        if (candleMsg.State != CandleStates.Finished)
                        {
                            candleMsg.State = CandleStates.Finished;
                        }

                        _currCandle = candleMsg;
                        _updatedCandles.Add(candleMsg);

                        _lastTime = candleMsg.OpenTime;

                        if (candleMsg is TimeFrameCandleMessage)
                        {
                            _lastTime += (TimeSpan)series.Arg;
                        }

                        _tradeGenerator.Process(new ExecutionMessage
                        {
                            ExecutionType = ExecutionTypes.Tick,
                            SecurityId    = series.Security.ToSecurityId(),
                            ServerTime    = _lastTime,
                            TradePrice    = candleMsg.ClosePrice,
                        });

                        if (date != candleMsg.OpenTime.Date)
                        {
                            date = candleMsg.OpenTime.Date;

                            var str = date.To <string>();
                            this.GuiAsync(() => BusyIndicator.BusyContent = str);

                            maxDays--;

                            if (maxDays == 0)
                            {
                                break;
                            }
                        }
                    }
                }

                _historyLoaded = true;
            })
            .ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    Error(t.Exception.Message);
                }

                BusyIndicator.IsBusy          = false;
                Chart.IsAutoRange             = false;
                ModifyAnnotationBtn.IsEnabled = true;
                NewAnnotationBtn.IsEnabled    = true;
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Exemplo n.º 8
0
        private void ProcessMarketDataMessage(MarketDataMessage message)
        {
            var securityId = message.SecurityId;
            var security   = SecurityProvider.LookupById(securityId.ToStringId());

            if (security == null)
            {
                RaiseMarketDataMessage(message, new InvalidOperationException(LocalizedStrings.Str704Params.Put(securityId)));
                return;
            }

            if (StorageRegistry == null)
            {
                RaiseMarketDataMessage(message, new InvalidOperationException(LocalizedStrings.Str1117Params.Put(message.DataType, securityId)));
                return;
            }

            var history = message as HistorySourceMessage;

            Exception error = null;

            switch (message.DataType)
            {
            case MarketDataTypes.Level1:
            {
                if (message.IsSubscribe)
                {
                    if (history == null)
                    {
                        BasketStorage.AddStorage(StorageRegistry.GetLevel1MessageStorage(security, Drive, StorageFormat));

                        BasketStorage.AddStorage(new InMemoryMarketDataStorage <ClearingMessage>(security, null, date => new[]
                            {
                                new ClearingMessage
                                {
                                    LocalTime        = date.Date + security.Board.ExpiryTime,
                                    SecurityId       = securityId,
                                    ClearMarketDepth = true
                                }
                            }));
                    }
                    else
                    {
                        BasketStorage.AddStorage(new InMemoryMarketDataStorage <Level1ChangeMessage>(security, null, history.GetMessages));
                    }
                }
                else
                {
                    BasketStorage.RemoveStorage <IMarketDataStorage <Level1ChangeMessage> >(security, MessageTypes.Level1Change, null);
                    BasketStorage.RemoveStorage <InMemoryMarketDataStorage <ClearingMessage> >(security, ExtendedMessageTypes.Clearing, null);
                }

                break;
            }

            case MarketDataTypes.MarketDepth:
            {
                if (message.IsSubscribe)
                {
                    BasketStorage.AddStorage(history == null
                                                        ? StorageRegistry.GetQuoteMessageStorage(security, Drive, StorageFormat)
                                                        : new InMemoryMarketDataStorage <QuoteChangeMessage>(security, null, history.GetMessages));
                }
                else
                {
                    BasketStorage.RemoveStorage <IMarketDataStorage <QuoteChangeMessage> >(security, MessageTypes.QuoteChange, null);
                }

                break;
            }

            case MarketDataTypes.Trades:
            {
                if (message.IsSubscribe)
                {
                    BasketStorage.AddStorage(history == null
                                                        ? StorageRegistry.GetTickMessageStorage(security, Drive, StorageFormat)
                                                        : new InMemoryMarketDataStorage <ExecutionMessage>(security, null, history.GetMessages));
                }
                else
                {
                    BasketStorage.RemoveStorage <IMarketDataStorage <ExecutionMessage> >(security, MessageTypes.Execution, ExecutionTypes.Tick);
                }

                break;
            }

            case MarketDataTypes.OrderLog:
            {
                if (message.IsSubscribe)
                {
                    BasketStorage.AddStorage(history == null
                                                        ? StorageRegistry.GetOrderLogMessageStorage(security, Drive, StorageFormat)
                                                        : new InMemoryMarketDataStorage <ExecutionMessage>(security, null, history.GetMessages));
                }
                else
                {
                    BasketStorage.RemoveStorage <IMarketDataStorage <ExecutionMessage> >(security, MessageTypes.Execution, ExecutionTypes.OrderLog);
                }

                break;
            }

            case MarketDataTypes.CandleTimeFrame:
            case MarketDataTypes.CandleTick:
            case MarketDataTypes.CandleVolume:
            case MarketDataTypes.CandleRange:
            case MarketDataTypes.CandlePnF:
            case MarketDataTypes.CandleRenko:
            {
                var msgType = message.DataType.ToCandleMessageType();

                if (message.IsSubscribe)
                {
                    var candleType = message.DataType.ToCandleMessage();

                    BasketStorage.AddStorage(history == null
                                                        ? StorageRegistry.GetCandleMessageStorage(candleType, security, message.Arg, Drive, StorageFormat)
                                                        : new InMemoryMarketDataStorage <CandleMessage>(security, message.Arg, history.GetMessages, candleType));
                }
                else
                {
                    BasketStorage.RemoveStorage <IMarketDataStorage <CandleMessage> >(security, msgType, message.Arg);
                }

                break;
            }

            default:
                error = new InvalidOperationException(LocalizedStrings.Str1118Params.Put(message.DataType));
                break;
            }

            RaiseMarketDataMessage(message, error);
        }
Exemplo n.º 9
0
        private void LoadData(Security security)
        {
            _candle    = null;
            _lastPrice = 0m;
            _allCandles.Clear();

            Chart.Reset(new IChartElement[] { _candleElement });

            var storage = new StorageRegistry();

            BusyIndicator.IsBusy = true;

            var path    = HistoryPath.Folder;
            var isBuild = BuildFromTicks.IsChecked == true;
            var format  = Format.SelectedFormat;

            var maxDays = isBuild ? 2 : 30 * (int)_timeframe.TotalMinutes;

            Task.Factory.StartNew(() =>
            {
                var date = DateTime.MinValue;

                if (isBuild)
                {
                    foreach (var tick in storage.GetTickMessageStorage(security, new LocalMarketDataDrive(path), format).Load())
                    {
                        AppendTick(security, tick);

                        _lastTime = tick.ServerTime;

                        if (date != tick.ServerTime.Date)
                        {
                            date = tick.ServerTime.Date;

                            var str = date.To <string>();
                            this.GuiAsync(() => BusyIndicator.BusyContent = str);

                            maxDays--;

                            if (maxDays == 0)
                            {
                                break;
                            }
                        }
                    }
                }
                else
                {
                    foreach (var candle in storage.GetCandleStorage(typeof(TimeFrameCandle), security, _timeframe, new LocalMarketDataDrive(path), format).Load())
                    {
                        lock (_updatedCandles.SyncRoot)
                            _updatedCandles[candle.OpenTime] = _candle = (TimeFrameCandle)candle;

                        _lastTime  = candle.OpenTime + _timeframe;
                        _lastPrice = _candle.ClosePrice;

                        _tradeGenerator.Process(new ExecutionMessage
                        {
                            ExecutionType = ExecutionTypes.Tick,
                            SecurityId    = security.ToSecurityId(),
                            ServerTime    = _lastTime,
                            TradePrice    = _lastPrice,
                        });

                        if (date != candle.OpenTime.Date)
                        {
                            date = candle.OpenTime.Date;

                            var str = date.To <string>();
                            this.GuiAsync(() => BusyIndicator.BusyContent = str);

                            maxDays--;

                            if (maxDays == 0)
                            {
                                break;
                            }
                        }
                    }
                }
            })
            .ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    Error(t.Exception.Message);
                }

                this.GuiAsync(() =>
                {
                    BusyIndicator.IsBusy = false;
                    Chart.IsAutoRange    = false;
                    //_areaComb.YAxises.First().AutoRange = false;
                });
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Exemplo n.º 10
0
        protected override TimeSpan OnProcess()
        {
            var hasSecurities = false;

            this.AddInfoLog(LocalizedStrings.Str2306Params.Put(_settings.StartFrom));

            foreach (var security in GetWorkingSecurities())
            {
                hasSecurities = true;

                if (!CanProcess())
                {
                    break;
                }

                //this.AddInfoLog("Обработка инструмента {0}. Конвертация {1}.".Put(security.Security.Id, mode));

                IMarketDataStorage fromStorage;
                IMarketDataStorage toStorage;

                switch (_settings.ConvertMode)
                {
                case ConvertModes.OrderLogToTicks:
                    fromStorage = StorageRegistry.GetOrderLogMessageStorage(security.Security, _settings.Drive, _settings.StorageFormat);
                    toStorage   = StorageRegistry.GetTickMessageStorage(security.Security, _settings.DestinationDrive, _settings.DestinationStorageFormat);
                    break;

                case ConvertModes.OrderLogToDepths:
                    fromStorage = StorageRegistry.GetOrderLogMessageStorage(security.Security, _settings.Drive, _settings.StorageFormat);
                    toStorage   = StorageRegistry.GetQuoteMessageStorage(security.Security, _settings.DestinationDrive, _settings.DestinationStorageFormat);
                    break;

                case ConvertModes.OrderLogToCandles:
                    fromStorage = StorageRegistry.GetOrderLogMessageStorage(security.Security, _settings.Drive, _settings.StorageFormat);
                    toStorage   = StorageRegistry.GetCandleMessageStorage(_settings.CandleSettings.CandleType.ToCandleMessageType(), security.Security, _settings.CandleSettings.Arg, _settings.DestinationDrive, _settings.DestinationStorageFormat);
                    break;

                case ConvertModes.TicksToCandles:
                    fromStorage = StorageRegistry.GetTickMessageStorage(security.Security, _settings.Drive, _settings.StorageFormat);
                    toStorage   = StorageRegistry.GetCandleMessageStorage(_settings.CandleSettings.CandleType.ToCandleMessageType(), security.Security, _settings.CandleSettings.Arg, _settings.DestinationDrive, _settings.DestinationStorageFormat);
                    break;

                case ConvertModes.DepthsToCandles:
                    fromStorage = StorageRegistry.GetQuoteMessageStorage(security.Security, _settings.Drive, _settings.StorageFormat);
                    toStorage   = StorageRegistry.GetCandleMessageStorage(_settings.CandleSettings.CandleType.ToCandleMessageType(), security.Security, _settings.CandleSettings.Arg, _settings.DestinationDrive, _settings.DestinationStorageFormat);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                var from = fromStorage.GetFromDate();
                var to   = fromStorage.GetToDate();

                if (from == null || to == null)
                {
                    //this.AddInfoLog("Нет данных для конвертации.");
                    continue;
                }

                from = _settings.StartFrom.Max(from.Value);
                to   = (DateTime.Today - TimeSpan.FromDays(_settings.Offset)).Min(to.Value);

                foreach (var date in from.Value.Range(to.Value, TimeSpan.FromDays(1)).Except(toStorage.Dates))
                {
                    if (!CanProcess())
                    {
                        break;
                    }

                    this.AddInfoLog(LocalizedStrings.Str3786Params.Put(security.Security.Id, _settings.ConvertMode, date));

                    try
                    {
                        switch (_settings.ConvertMode)
                        {
                        case ConvertModes.OrderLogToTicks:
                        {
                            var ticks = ((IMarketDataStorage <ExecutionMessage>)fromStorage)
                                        .Load(date)
                                        .ToTicks();

                            toStorage.Save(ticks);
                            RaiseDataLoaded(security.Security, typeof(ExecutionMessage), ExecutionTypes.Tick, date, ticks.Count);
                            break;
                        }

                        case ConvertModes.OrderLogToDepths:
                        {
                            var depths = ((IMarketDataStorage <ExecutionMessage>)fromStorage)
                                         .Load(date)
                                         .ToMarketDepths(_settings.MarketDepthInterval, _settings.MarketDepthMaxDepth);

                            toStorage.Save(depths);
                            RaiseDataLoaded(security.Security, typeof(QuoteChangeMessage), null, date, depths.Count);
                            break;
                        }

                        case ConvertModes.OrderLogToCandles:
                        {
                            var candles = ((IMarketDataStorage <ExecutionMessage>)fromStorage)
                                          .Load(date)
                                          .ToTicks()
                                          .ToCandles(new CandleSeries(_settings.CandleSettings.CandleType, security.Security, _settings.CandleSettings.Arg));

                            toStorage.Save(candles);
                            RaiseDataLoaded(security.Security, _settings.CandleSettings.CandleType, _settings.CandleSettings.Arg, date, candles.Count);
                            break;
                        }

                        case ConvertModes.TicksToCandles:
                        {
                            var candles = ((IMarketDataStorage <ExecutionMessage>)fromStorage)
                                          .Load(date)
                                          .ToCandles(new CandleSeries(_settings.CandleSettings.CandleType, security.Security, _settings.CandleSettings.Arg));

                            toStorage.Save(candles);
                            RaiseDataLoaded(security.Security, _settings.CandleSettings.CandleType, _settings.CandleSettings.Arg, date, candles.Count);
                            break;
                        }

                        case ConvertModes.DepthsToCandles:
                        {
                            var candles = ((IMarketDataStorage <QuoteChangeMessage>)fromStorage)
                                          .Load(date)
                                          .ToCandles(new CandleSeries(_settings.CandleSettings.CandleType, security.Security, _settings.CandleSettings.Arg));

                            toStorage.Save(candles);
                            RaiseDataLoaded(security.Security, _settings.CandleSettings.CandleType, _settings.CandleSettings.Arg, date, candles.Count);
                            break;
                        }

                        default:
                            throw new ArgumentOutOfRangeException();
                        }
                    }
                    catch (Exception ex)
                    {
                        HandleError(ex);
                    }
                }
            }

            if (!hasSecurities)
            {
                this.AddWarningLog(LocalizedStrings.Str2292);
                return(TimeSpan.MaxValue);
            }

            if (CanProcess())
            {
                this.AddInfoLog(LocalizedStrings.Str2300);
            }

            return(base.OnProcess());
        }
Exemplo n.º 11
0
        private void LoadData()
        {
            _lastPrice = 0m;

            _candles.Clear();
            var id = _securityId.ToSecurityId();

            _security = new Security
            {
                Id        = _securityId,
                PriceStep = _priceStep,
                Board     = _exchangeInfoProvider.GetExchangeBoard(id.BoardCode) ?? ExchangeBoard.Associated
            };

            Chart.Reset(new IChartElement[] { _candleElement });

            var storage = new StorageRegistry();

            var maxDays = 50;

            //BusyIndicator.IsBusy = true;

            var path = _historyPath;

            _curCandleNum = 0;

            Task.Factory.StartNew(() =>
            {
                var date = DateTime.MinValue;

                foreach (var tick in storage.GetTickMessageStorage(_security, new LocalMarketDataDrive(path)).Load())
                {
                    if (date != tick.ServerTime.Date)
                    {
                        date = tick.ServerTime.Date;

                        //var str = $"Loading ticks for {date:dd MMM yyyy}...";
                        //this.GuiAsync(() => BusyIndicator.BusyContent = str);

                        if (--maxDays == 0)
                        {
                            break;
                        }
                    }

                    AppendTick(tick);
                }
            })
            .ContinueWith(t =>
            {
                //this.GuiAsync(() => BusyIndicator.IsBusy = false);

                for (var i = 0; i < _candles.Count; i += _candlesPacketSize)
                {
                    var data = new ChartDrawData();

                    var candles = _candles.GetRange(i, Math.Min(_candlesPacketSize, _candles.Count - i)).Select(c => c.ToCandle(_tfSpan, _security));

                    foreach (var candle in candles)
                    {
                        candle.State = CandleStates.Finished;

                        var group = data.Group(candle.OpenTime);

                        group.Add(_candleElement, candle);

                        if (_indicatorElement != null)
                        {
                            group.Add(_indicatorElement, _indicator.Process((double)candle.ClosePrice));
                        }
                    }

                    Chart.Draw(data);
                }
            })
            .ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    Error(t.Exception.Message);
                }

                _dataIsLoaded = true;

                //this.GuiAsync(() => BusyIndicator.IsBusy = false);

                Chart.IsAutoRange = false;
                //_area.YAxises.FirstOrDefault().Do(a => a.AutoRange = false);
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Exemplo n.º 12
0
        private void LoadData()
        {
            _candle    = null;
            _lastPrice = 0m;
            _allCandles.Clear();

            var id = new SecurityIdGenerator().Split(SecurityId.Text);

            _security = new Security
            {
                Id        = SecurityId.Text,
                PriceStep = _priceStep,
                Board     = _exchangeInfoProvider.GetExchangeBoard(id.BoardCode)
            };

            Chart.Reset(new IChartElement[] { _candleElement1 });

            var storage = new StorageRegistry();

            var maxDays = 2;

            BusyIndicator.IsBusy = true;

            var path = HistoryPath.Folder;

            Task.Factory.StartNew(() =>
            {
                var date = DateTime.MinValue;

                foreach (var tick in storage.GetTickMessageStorage(_security, new LocalMarketDataDrive(path)).Load())
                {
                    AppendTick(_security, tick);

                    _lastTime = tick.ServerTime;

                    if (date != tick.ServerTime.Date)
                    {
                        date = tick.ServerTime.Date;

                        var str = date.To <string>();
                        this.GuiAsync(() => BusyIndicator.BusyContent = str);

                        maxDays--;

                        if (maxDays == 0)
                        {
                            break;
                        }
                    }
                }
            })
            .ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    Error(t.Exception.Message);
                }

                this.GuiAsync(() =>
                {
                    BusyIndicator.IsBusy = false;
                    Chart.IsAutoRange    = false;
                    _areaComb.YAxises.First().AutoRange = false;
                });
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Exemplo n.º 13
0
        private void LoadData()
        {
            _lastPrice = 0m;

            _candles.Clear();
            var id = new SecurityIdGenerator().Split(SecurityId);

            _security = new Security
            {
                Id        = SecurityId,
                PriceStep = PriceStep,
                Board     = ExchangeBoard.GetBoard(id.BoardCode)
            };

            Chart.Reset(new IChartElement[] { _candleElement });

            var storage = new StorageRegistry();

            var maxDays = 1;

            BusyIndicator.IsBusy = true;

            var path = HistoryPath;

            _curCandleNum = 0;

            Task.Factory.StartNew(() =>
            {
                var date = DateTime.MinValue;

                foreach (var tick in storage.GetTickMessageStorage(_security, new LocalMarketDataDrive(path)).Load())
                {
                    if (date != tick.ServerTime.Date)
                    {
                        date = tick.ServerTime.Date;

                        this.GuiAsync(() => BusyIndicator.BusyContent = $"Loading ticks for {date:dd MMM yyyy}...");

                        if (maxDays-- == 0)
                        {
                            break;
                        }
                    }

                    AppendTick(tick);
                }
            })
            .ContinueWith(t =>
            {
                this.GuiAsync(() => BusyIndicator.IsBusy = false);

                for (var i = 0; i < _candles.Count; i += CandlesPacketSize)
                {
                    var candles = _candles.GetRange(i, Math.Min(CandlesPacketSize, _candles.Count - i)).Select(c => c.ToCandle(TFSpan));

                    Chart.Draw(candles.Select(c =>
                    {
                        c.State = CandleStates.Finished;

                        var dict = (IDictionary <IChartElement, object>) new Dictionary <IChartElement, object>
                        {
                            { _candleElement, c }
                        };

                        if (_indicatorElement != null)
                        {
                            dict.Add(_indicatorElement, _indicator.Process((double)c.ClosePrice));
                        }

                        if (_tradeElement != null && _curCandleNum++ % TradeEveryNCandles == 0)
                        {
                            dict.Add(_tradeElement, new MyTrade
                            {
                                Trade = new Trade
                                {
                                    Security       = _security,
                                    Volume         = 1,
                                    Price          = c.LowPrice,
                                    OrderDirection = Sides.Buy,
                                    Time           = c.OpenTime
                                },
                                Order = new Order {
                                    Security = _security, Direction = Sides.Buy
                                }
                            });
                        }

                        return(RefTuple.Create(c.OpenTime, dict));
                    }).ToArray());
                }
            })
            .ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    Error(t.Exception.Message);
                }

                _dataIsLoaded = true;

                this.GuiAsync(() => BusyIndicator.IsBusy = false);

                Chart.IsAutoRange = false;
                //_area.YAxises.FirstOrDefault().Do(a => a.AutoRange = false);
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Exemplo n.º 14
0
		private void LoadData(string path)
		{
			var storage = new StorageRegistry();

			var maxDays = 2;

			BusyIndicator.IsBusy = true;

			Task.Factory.StartNew(() =>
			{
				var date = DateTime.MinValue;

				foreach (var tick in storage.GetTickMessageStorage(_security, new LocalMarketDataDrive(path)).Load())
				{
					AppendTick(tick.ServerTime, tick.TradePrice.Value, tick.Volume.Value);
					_lastTime = tick.ServerTime;

					if (date != tick.ServerTime.Date)
					{
						date = tick.ServerTime.Date;

                        this.GuiAsync(() =>
						{
							BusyIndicator.BusyContent = date.ToString();
						});

						maxDays--;

						if (maxDays == 0)
							break;
					}
				}
			})
			.ContinueWith(t =>
			{
				if (t.Exception != null)
					Error(t.Exception.Message);

				BusyIndicator.IsBusy = false;
			}, TaskScheduler.FromCurrentSynchronizationContext());
		}
Exemplo n.º 15
0
		private void LoadData()
		{
			_candle = null;
			_lastPrice = 0m;
			_allCandles.Clear();

			var id = new SecurityIdGenerator().Split(SecurityId.Text);

			_security = new Security
			{
				Id = SecurityId.Text,
				PriceStep = 5,
				Board = ExchangeBoard.GetBoard(id.BoardCode)
			};

			Chart.Reset(new IChartElement[] { _candleElement1 });

			var storage = new StorageRegistry();

			var maxDays = 2;

			BusyIndicator.IsBusy = true;

			var path = HistoryPath.Folder;

			Task.Factory.StartNew(() =>
			{
				var date = DateTime.MinValue;

				foreach (var tick in storage.GetTickMessageStorage(_security, new LocalMarketDataDrive(path)).Load())
				{
					AppendTick(_security, tick);
					_lastTime = tick.ServerTime;

					if (date != tick.ServerTime.Date)
					{
						date = tick.ServerTime.Date;

						this.GuiAsync(() =>
						{
							BusyIndicator.BusyContent = date.ToString();
						});

						maxDays--;

						if (maxDays == 0)
							break;
					}
				}
			})
			.ContinueWith(t =>
			{
				if (t.Exception != null)
					Error(t.Exception.Message);

				BusyIndicator.IsBusy = false;
			}, TaskScheduler.FromCurrentSynchronizationContext());
		}
Exemplo n.º 16
0
        private void LoadData(CandleSeries series)
        {
            _currCandle    = null;
            _historyLoaded = false;
            _allCandles.Clear();

            _candleTransform.Process(new ResetMessage());
            _candleBuilder = series.CandleType.ToCandleMessageType().ToCandleMarketDataType().CreateCandleBuilder();

            Chart.Reset(new IChartElement[] { _candleElement });

            var storage = new StorageRegistry();

            BusyIndicator.IsBusy = true;

            var path    = HistoryPath.Folder;
            var isBuild = BuildFromTicks.IsChecked == true;
            var format  = Format.SelectedFormat;

            var maxDays = (isBuild || series.CandleType != typeof(TimeFrameCandle))
                                ? 5
                                : 30 * (int)((TimeSpan)series.Arg).TotalMinutes;

            _mdMsg = series.ToMarketDataMessage(true);

            Task.Factory.StartNew(() =>
            {
                var date = DateTime.MinValue;

                if (isBuild)
                {
                    foreach (var tick in storage.GetTickMessageStorage(series.Security, new LocalMarketDataDrive(path), format).Load())
                    {
                        _tradeGenerator.Process(tick);

                        if (_candleTransform.Process(tick))
                        {
                            var candles = _candleBuilder.Process(_mdMsg, _currCandle, _candleTransform);

                            lock (_lock)
                            {
                                foreach (var candle in candles)
                                {
                                    _currCandle = candle;
                                    _updatedCandles[candle.OpenTime] = Tuple.Create(candle, candle.State == CandleStates.Finished);
                                }
                            }
                        }

                        _lastTime = tick.ServerTime;

                        if (date != tick.ServerTime.Date)
                        {
                            date = tick.ServerTime.Date;

                            var str = date.To <string>();
                            this.GuiAsync(() => BusyIndicator.BusyContent = str);

                            maxDays--;

                            if (maxDays == 0)
                            {
                                break;
                            }
                        }
                    }
                }
                else
                {
                    foreach (var candleMsg in storage.GetCandleMessageStorage(series.CandleType.ToCandleMessageType(), series.Security, series.Arg, new LocalMarketDataDrive(path), format).Load())
                    {
                        lock (_updatedCandles.SyncRoot)
                        {
                            _currCandle = candleMsg;
                            _updatedCandles[candleMsg.OpenTime] = Tuple.Create(candleMsg, true);
                        }

                        _lastTime = candleMsg.OpenTime;

                        if (candleMsg is TimeFrameCandleMessage)
                        {
                            _lastTime += (TimeSpan)series.Arg;
                        }

                        _tradeGenerator.Process(new ExecutionMessage
                        {
                            ExecutionType = ExecutionTypes.Tick,
                            SecurityId    = series.Security.ToSecurityId(),
                            ServerTime    = _lastTime,
                            TradePrice    = candleMsg.ClosePrice,
                        });

                        if (date != candleMsg.OpenTime.Date)
                        {
                            date = candleMsg.OpenTime.Date;

                            var str = date.To <string>();
                            this.GuiAsync(() => BusyIndicator.BusyContent = str);

                            maxDays--;

                            if (maxDays == 0)
                            {
                                break;
                            }
                        }
                    }
                }

                _historyLoaded = true;
            })
            .ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    Error(t.Exception.Message);
                }

                this.GuiAsync(() =>
                {
                    BusyIndicator.IsBusy = false;
                    Chart.IsAutoRange    = false;
                    //_areaComb.YAxises.First().AutoRange = false;
                });
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }