private void OnConnectorNewMessage(Message message, MessageDirections direction) { switch (message.Type) { case MessageTypes.SecurityLookupResult: { var id = ((SecurityLookupResultMessage)message).OriginalTransactionId; var tuple = _lookupMessages.TryGetValue(id); if (tuple != null) { var security = _connector.FilterSecurities(tuple.Item1).FirstOrDefault(); ProcessSecurityMarketData(security, tuple.Item3, tuple.Item2); _lookupMessages.Remove(id); } break; } //TODO убрать подписку на MarketDataSubscriptionSucceeded //case MessageTypes.MarketData: //{ // if (direction == MessageDirections.ToMarketData) // break; // break; //} } }
/// <summary> /// Обработать сообщение, содержащее рыночные данные. /// </summary> /// <param name="message">Сообщение, содержащее рыночные данные.</param> /// <param name="direction">Направление сообщения.</param> protected override void OnProcessMessage(Message message, MessageDirections direction) { var candleMsg = message as CandleMessage; if (candleMsg == null) { base.OnProcessMessage(message, direction); return; } var series = _series.TryGetValue(candleMsg.OriginalTransactionId); if (series == null) { return; } var candle = candleMsg.ToCandle(series); // тиковый ТФ if (candleMsg.TotalVolume == 0) { candle.TotalVolume = (candle.OpenVolume + candle.CloseVolume) ?? 0; candle.HighPrice = candle.OpenPrice.Max(candle.ClosePrice); candle.LowPrice = candle.OpenPrice.Min(candle.ClosePrice); } NewCandles.SafeInvoke(series, new[] { candle }); }
public void ApplyMessageProcessor(string name, MessageDirections direction, bool isTransaction, bool isMarketData, IMessageProcessor defaultProcessor = null) { var processor = new MessageProcessorPool(defaultProcessor ?? new MessageProcessor("Processor '{0}' ({1})".Put(name, direction), _errorHandler)); ISmartPointer pointer = new SmartPointer <IMessageProcessor>(processor, p => { p.Stop(); _processorPointers.Remove(p); }); _processorPointers[processor] = pointer; switch (direction) { case MessageDirections.In: if (isTransaction) { DecRefProcessor(TransactionAdapter, direction); pointer.IncRef(); TransactionAdapter.InMessageProcessor = processor; } if (isMarketData) { DecRefProcessor(MarketDataAdapter, direction); pointer.IncRef(); MarketDataAdapter.InMessageProcessor = processor; } break; case MessageDirections.Out: if (isTransaction) { DecRefProcessor(TransactionAdapter, direction); pointer.IncRef(); TransactionAdapter.OutMessageProcessor = processor; } if (isMarketData) { DecRefProcessor(MarketDataAdapter, direction); pointer.IncRef(); MarketDataAdapter.OutMessageProcessor = processor; } break; default: _processorPointers.Remove(processor); throw new ArgumentOutOfRangeException("direction"); } }
private void TraderOnNewMessage(Message msg, MessageDirections dir) { if (dir == MessageDirections.Out && msg.Type == MessageTypes.Level1Change) { var level1Msg = (Level1ChangeMessage)msg; var wnd = _level1Windows.TryGetValue(level1Msg.SecurityId.SecurityCode); if (wnd != null) { wnd.Level1Grid.Messages.Add(level1Msg); } } }
/// <summary> /// Обработать сообщение, содержащее рыночные данные. /// </summary> /// <param name="message">Сообщение, содержащее рыночные данные.</param> /// <param name="direction">Направление сообщения.</param> protected override void OnProcessMessage(Message message, MessageDirections direction) { if (direction == MessageDirections.Out) { switch (message.Type) { case MessageTypes.Connect: if (((ConnectMessage)message).Error == null) { _candlesTimer = this.StartRealTime(_realTimeSeries, RealTimeCandleOffset, (series, range) => RequestCandles(series.Security, (TimeSpan)series.Arg, range.Min, range.Max, _series.TryGetKey(series)), TimeSpan.FromSeconds(3)); } break; case MessageTypes.Disconnect: if (((DisconnectMessage)message).Error == null && _candlesTimer != null) { _candlesTimer.Dispose(); _candlesTimer = null; } break; default: { var candleMsg = message as CandleMessage; if (candleMsg == null) { break; } var series = _series.TryGetValue(candleMsg.OriginalTransactionId); if (series == null) { return; } var candle = candleMsg.ToCandle(series); NewCandles.SafeInvoke(series, new[] { candle }); return; // base class throws exception } } } base.OnProcessMessage(message, direction); }
private void RealConnectorNewMessage(Message message, MessageDirections direction) { switch (message.Type) { case MessageTypes.Connect: case MessageTypes.Disconnect: return; } if (!_isHistory) { SendOutMessage(message); } }
/// <summary> /// Обработать сообщение, содержащее рыночные данные. /// </summary> /// <param name="message">Сообщение, содержащее рыночные данные.</param> /// <param name="direction">Направление сообщения.</param> protected override void OnProcessMessage(Message message, MessageDirections direction) { if (message.Type == MessageTypes.Connect && message.Adapter == TransactionAdapter && direction == MessageDirections.Out) { // передаем первоначальное значение размера портфеля в эмулятор TransactionAdapter.SendInMessage(_portfolio.ToMessage()); TransactionAdapter.SendInMessage(new PortfolioChangeMessage { PortfolioName = _portfolio.Name }.Add(PositionChangeTypes.BeginValue, _portfolio.BeginValue)); } base.OnProcessMessage(message, direction); }
/// <summary> /// Обработать сообщение, содержащее рыночные данные. /// </summary> /// <param name="message">Сообщение, содержащее рыночные данные.</param> /// <param name="direction">Направление сообщения.</param> protected override void OnProcessMessage(Message message, MessageDirections direction) { var candleMsg = message as CandleMessage; if (candleMsg == null) { base.OnProcessMessage(message, direction); return; } var series = _series[candleMsg.OriginalTransactionId]; NewCandles.SafeInvoke(series, new[] { candleMsg.ToCandle(series) }); }
/// <summary> /// Обработать сообщение, содержащее рыночные данные. /// </summary> /// <param name="message">Сообщение, содержащее рыночные данные.</param> /// <param name="direction">Направление сообщения.</param> protected override void OnProcessMessage(Message message, MessageDirections direction) { switch (message.Type) { case MessageTypes.Level1Change: { var hist = message as HistoryLevel1ChangeMessage; if (hist == null) { break; } // TODO NewSecurityChanges.SafeInvoke(null, hist); return; } } base.OnProcessMessage(message, direction); }
private void DecRefProcessor(IMessageAdapter adapter, MessageDirections direction) { switch (direction) { case MessageDirections.In: if (adapter.InMessageProcessor != null) { DecRefProcessor(adapter.InMessageProcessor); adapter.InMessageProcessor = null; } break; case MessageDirections.Out: if (adapter.OutMessageProcessor != null) { DecRefProcessor(adapter.OutMessageProcessor); adapter.OutMessageProcessor = null; } break; default: throw new ArgumentOutOfRangeException("direction"); } }
/// <summary> /// Обработать сообщение, содержащее рыночные данные. /// </summary> /// <param name="message">Сообщение, содержащее рыночные данные.</param> /// <param name="adapterType">Тип адаптера, от которого пришло сообщение.</param> /// <param name="direction">Направление сообщения.</param> protected override void OnProcessMessage(Message message, MessageAdapterTypes adapterType, MessageDirections direction) { try { if (adapterType == MessageAdapterTypes.Transaction) { switch (message.Type) { case ExtendedMessageTypes.Last: { var lastMsg = (LastMessage)message; if (State == EmulationStates.Started) { IsFinished = !lastMsg.IsError; // все данных пришли без ошибок или в процессе чтения произошла ошибка - начинаем остановку SetEmulationState(EmulationStates.Stopping); SetEmulationState(EmulationStates.Stopped); } if (State == EmulationStates.Stopping) { // тестирование было отменено и пришли все ранее прочитанные данные SetEmulationState(EmulationStates.Stopped); } break; } case ExtendedMessageTypes.Clearing: break; case ExtendedMessageTypes.EmulationState: ProcessEmulationStateMessage((EmulationStateMessage)message); break; default: { var candleMsg = message as CandleMessage; if (candleMsg != null) { ProcessCandleMessage((CandleMessage)message); break; } if (State == EmulationStates.Stopping && message.Type != MessageTypes.Disconnect) { break; } base.OnProcessMessage(message, adapterType, direction); ProcessedEventCount++; break; } } } else { base.OnProcessMessage(message, adapterType, direction); } } catch (Exception ex) { RaiseProcessDataError(ex); SetEmulationState(EmulationStates.Stopping); } }
protected override void OnProcessMessage(Message message, MessageDirections direction) { //_historyMessageAdapter.UpdateCurrentTime(message.LocalTime); switch (message.Type) { case MessageTypes.Connect: { if (message.Adapter == MarketDataAdapter) { break; } _isHistory = true; _isInitialization = true; _connectTime = message.LocalTime; _strategy.SetIsInitialization(true); _historyMessageAdapter .SecurityProvider .LookupAll() .ForEach(s => SendOutMessage(s.ToMessage())); break; } case (MessageTypes)(-1): { new ChartAutoRangeCommand(false).Process(_strategy); _strategy.PositionManager.Positions = _sessionStrategy.Positions.Select(p => p.Position).ToList(); if (_onlyInitialize) { if (message.Adapter == MarketDataAdapter) { new StopStrategyCommand(_strategy).Process(this); } return; } _historyMessageAdapter.StopDate = DateTimeOffset.MaxValue; _historyMessageAdapter.MarketTimeChangedInterval = TimeSpan.FromMilliseconds(10); var messages = new List <Message>(); messages.AddRange(_realConnector.Trades.Select(t => t.ToMessage())); messages.AddRange(_realConnector.Orders.Select(o => o.ToMessage())); messages.AddRange(_realConnector.OrderRegisterFails.Select(o => o.ToMessage())); messages.AddRange(_realConnector.OrderCancelFails.Select(o => o.ToMessage())); messages.AddRange(_realConnector.MyTrades.Select(t => t.ToMessage())); messages.ForEach(SendOutMessage); _isHistory = false; return; } case MessageTypes.Execution: { var execMsg = (ExecutionMessage)message; if (execMsg.ExecutionType == ExecutionTypes.Tick && !_isHistory && _isInitialization) { ProcessTime(execMsg.ServerTime, execMsg.SecurityId.BoardCode); } break; } default: { var candleMsg = message as CandleMessage; if (candleMsg == null) { break; } if (!_isHistory) { break; } var stocksharpId = CreateSecurityId(candleMsg.SecurityId.SecurityCode, candleMsg.SecurityId.BoardCode); var security = Securities.FirstOrDefault(s => s.Id.CompareIgnoreCase(stocksharpId)); if (security == null) { throw new InvalidOperationException(LocalizedStrings.Str704Params.Put(candleMsg.SecurityId)); } var volumeStep = security.VolumeStep ?? 1m; var decimals = volumeStep.GetCachedDecimals(); var trades = candleMsg.ToTrades(volumeStep, decimals); foreach (var executionMessage in trades) { base.OnProcessMessage(executionMessage, direction); } return; } } base.OnProcessMessage(message, direction); }
/// <summary> /// Обработать сообщение, содержащее рыночные данные. /// </summary> /// <param name="message">Сообщение, содержащее рыночные данные.</param> /// <param name="direction">Направление сообщения.</param> protected override void OnProcessMessage(Message message, MessageDirections direction) { try { switch (message.Type) { case MessageTypes.Connect: { base.OnProcessMessage(message, direction); if (message.Adapter == TransactionAdapter) { _initialMoney.ForEach(p => SendPortfolio(p.Key)); } break; } case ExtendedMessageTypes.Last: { var lastMsg = (LastMessage)message; if (State == EmulationStates.Started) { IsFinished = !lastMsg.IsError; // все данных пришли без ошибок или в процессе чтения произошла ошибка - начинаем остановку SendEmulationState(EmulationStates.Stopping); SendEmulationState(EmulationStates.Stopped); } if (State == EmulationStates.Stopping) { // тестирование было отменено и пришли все ранее прочитанные данные SendEmulationState(EmulationStates.Stopped); } break; } case ExtendedMessageTypes.Clearing: break; case ExtendedMessageTypes.EmulationState: ProcessEmulationStateMessage(((EmulationStateMessage)message).State); break; default: { var candleMsg = message as CandleMessage; if (candleMsg != null) { ProcessCandleMessage((CandleMessage)message); break; } if (State == EmulationStates.Stopping && message.Type != MessageTypes.Disconnect) { break; } base.OnProcessMessage(message, direction); break; } } } catch (Exception ex) { SendOutError(ex); SendEmulationState(EmulationStates.Stopping); } }
/// <summary> /// Обработать сообщение, содержащее рыночные данные. /// </summary> /// <param name="message">Сообщение, содержащее рыночные данные.</param> /// <param name="adapterType">Тип адаптера, от которого пришло сообщение.</param> /// <param name="direction">Направление сообщения.</param> protected override void OnProcessMessage(Message message, MessageAdapterTypes adapterType, MessageDirections direction) { var candleMsg = message as CandleMessage; if (candleMsg == null) { base.OnProcessMessage(message, adapterType, direction); return; } var series = _candleSeries.TryGetValue(candleMsg.OriginalTransactionId); if (series == null) { return; } var candle = candleMsg.ToCandle(series); NewCandles.SafeInvoke(series, new[] { candle }); }
protected override void OnProcessMessage(Message message, MessageDirections direction) { switch (message.Type) { case MessageTypes.Connect: { if (message.Adapter == MarketDataAdapter) { if (direction == MessageDirections.Out && ((ConnectMessage)message).Error == null) { SendPortfoliosToEmulator(); TrySubscribeMarketData(); } } else { var emu = Adapter.InnerAdapters.OfType <StudioEmulationAdapter>().FirstOrDefault(); if (emu == null) { this.AddWarningLog(LocalizedStrings.Str3625); break; } emu.Emulator.Settings.ConvertTime = true; emu.Emulator.Settings.InitialOrderId = DateTime.Now.Ticks; emu.Emulator.Settings.InitialTradeId = DateTime.Now.Ticks; _marketDataAdapter.NewOutMessage += emu.ProcessMessage; } break; } case MessageTypes.Disconnect: { if (direction != MessageDirections.Out) { break; } if (message.Adapter == MarketDataAdapter) { ResetMarketDataSubscriptions(); } else { var emu = Adapter.InnerAdapters.OfType <StudioEmulationAdapter>().FirstOrDefault(); if (emu != null) { _marketDataAdapter.NewOutMessage -= emu.ProcessMessage; } } break; } case MessageTypes.MarketData: { var mdMsg = (MarketDataMessage)message; var securityId = mdMsg.SecurityId; if (direction == MessageDirections.Out && mdMsg.Error == null && !securityId.SecurityCode.IsDefault() && !securityId.BoardCode.IsDefault()) { var security = GetSecurity(securityId); var types = _exports.TryGetValue(security); if (types != null && !types.TryGetValue(mdMsg.DataType)) { types[mdMsg.DataType] = true; } } break; } case MessageTypes.Security: { var secMsg = (SecurityMessage)message; var board = ExchangeBoard.GetBoard(secMsg.SecurityId.BoardCode); if (board != null) { SendToEmulator(new[] { board.ToMessage() }); } break; } } base.OnProcessMessage(message, direction); }
/// <summary> /// Вызвать событие <see cref="NewMessage"/>. /// </summary> /// <param name="message">Новое сообщение.</param> /// <param name="direction">Направление сообщения.</param> private void RaiseNewMessage(Message message, MessageDirections direction) { NewMessage.SafeInvoke(message, direction); }
private void NewMessageHandler(Message message, MessageDirections direction) { AddGuiAction(() => NewMessage.SafeInvoke(message, direction)); }
/// <summary> /// Обработать сообщение, содержащее рыночные данные. /// </summary> /// <param name="message">Сообщение, содержащее рыночные данные.</param> /// <param name="adapterType">Тип адаптера, от которого пришло сообщение.</param> /// <param name="direction">Направление сообщения.</param> protected override void OnProcessMessage(Message message, MessageAdapterTypes adapterType, MessageDirections direction) { if (direction == MessageDirections.Out) { switch (message.Type) { case ExtendedMessageTypes.Scanner: { var scannerMsg = (ScannerResultMessage)message; var state = (ScannerFilter)_states[scannerMsg.OriginalTransactionId]; NewScannerResults.SafeInvoke(state, scannerMsg.Results); break; } case ExtendedMessageTypes.ScannerParameters: { var scannerMsg = (ScannerParametersMessage)message; NewScannerParameters.SafeInvoke(scannerMsg.Parameters); break; } case ExtendedMessageTypes.FinancialAdvise: { var adviseMsg = (FinancialAdviseMessage)message; NewFinancialAdvise.SafeInvoke(adviseMsg.AdviseType, adviseMsg.Data); break; } case ExtendedMessageTypes.FundamentalReport: { var reportMsg = (FundamentalReportMessage)message; var state = (Tuple <Security, FundamentalReports>)_states[reportMsg.OriginalTransactionId]; NewFundamentalReport.SafeInvoke(state.Item1, state.Item2, reportMsg.Data); break; } default: { var candleMsg = message as CandleMessage; if (candleMsg == null) { break; } var series = _candleSeries.TryGetValue(candleMsg.OriginalTransactionId); if (series != null) { var candle = candleMsg.ToCandle(series); NewCandles.SafeInvoke(series, new[] { candle }); } return; } } } base.OnProcessMessage(message, adapterType, direction); }
/// <summary> /// Обработать сообщение, содержащее рыночные данные. /// </summary> /// <param name="message">Сообщение, содержащее рыночные данные.</param> /// <param name="direction">Направление сообщения.</param> protected override void OnProcessMessage(Message message, MessageDirections direction) { if (direction == MessageDirections.Out) { switch (message.Type) { case MessageTypes.Connect: case MessageTypes.Disconnect: { PulseWaiting(); break; } case MessageTypes.MarketData: { var mdMsg = (MarketDataMessage)message; if (mdMsg.Error != null) { var candleInfo = _candleInfo.TryGetValue(mdMsg.OriginalTransactionId); if (candleInfo != null) { lock (candleInfo.Second) { candleInfo.Third = true; candleInfo.Second.Pulse(); } _candleInfo.Remove(mdMsg.OriginalTransactionId); } var l1Info = _level1Info.TryGetValue(mdMsg.OriginalTransactionId); if (l1Info != null) { lock (l1Info.Second) { l1Info.Third = true; l1Info.Second.Pulse(); } _level1Info.Remove(mdMsg.OriginalTransactionId); } } break; } case MessageTypes.CandleRange: case MessageTypes.CandleTick: case MessageTypes.CandleTimeFrame: case MessageTypes.CandleVolume: { var candleMsg = (CandleMessage)message; var series = _candleSeries.TryGetValue(candleMsg.OriginalTransactionId); if (series == null) { return; } var candle = candleMsg.ToCandle(series); // сообщение с IsFinished = true не содержит данные по свече, // только флаг, что получение исторических данных завершено if (!candleMsg.IsFinished) { NewCandles.SafeInvoke(series, new[] { candle }); } var info = _candleInfo.TryGetValue(candleMsg.OriginalTransactionId); if (info != null) { if (candleMsg.IsFinished) { lock (info.Second) { info.Third = true; info.Fifth = true; info.Second.Pulse(); } _candleInfo.Remove(candleMsg.OriginalTransactionId); } else { info.First.Add(candle); } } // DO NOT send historical data to Connector return; } case MessageTypes.Level1Change: { var l1Msg = (Level1ChangeMessage)message; var transactionId = l1Msg.GetRequestId(); var info = _level1Info.TryGetValue(transactionId); // IsFinished = true message do not contains any data, // just mark historical data gathering as finished if (l1Msg.GetValue <bool>("IsFinished")) { if (info == null) { this.AddWarningLog(LocalizedStrings.Str2149Params.Put(transactionId)); return; } lock (info.Second) { info.Third = true; info.Fifth = true; info.Second.Pulse(); } _level1Info.Remove(transactionId); } else { // streaming l1 message (non historical) if (info == null) { break; } info.First.Add((Level1ChangeMessage)l1Msg.Clone()); } // DO NOT send historical data to Connector return; } case ExtendedMessageTypes.System: { var msg = (IQFeedSystemMessage)message; if (msg.Feed.Address == _adapter.LookupAddress) { PulseWaiting(); } return; } } } base.OnProcessMessage(message, direction); }
/// <summary> /// ќбработать сообщение, содержащее рыночные данные. /// </summary> /// <param name="message">—ообщение, содержащее рыночные данные.</param> /// <param name="adapterType">“ип адаптера, от которого пришло сообщение.</param> /// <param name="direction">Ќаправление сообщени¤.</param> protected override void OnProcessMessage(Message message, MessageAdapterTypes adapterType, MessageDirections direction) { if (adapterType == MessageAdapterTypes.MarketData && direction == MessageDirections.Out) { switch (message.Type) { case MessageTypes.Connect: case MessageTypes.Disconnect: case MessageTypes.MarketData: case MessageTypes.Error: case MessageTypes.SecurityLookupResult: case MessageTypes.PortfolioLookupResult: base.OnProcessMessage(message, adapterType, direction); break; case MessageTypes.Execution: { var execMsg = (ExecutionMessage)message; if (execMsg.ExecutionType != ExecutionTypes.Trade) { TransactionAdapter.SendInMessage(message); } else { base.OnProcessMessage(message, adapterType, direction); } break; } default: TransactionAdapter.SendInMessage(message); break; } } else { base.OnProcessMessage(message, adapterType, direction); } }
protected override void OnProcessMessage(Message message, MessageAdapterTypes adapterType, MessageDirections direction) { switch (message.Type) { case MessageTypes.Connect: { if (direction == MessageDirections.Out && adapterType == MessageAdapterTypes.MarketData && ((ConnectMessage)message).Error == null) { SendPortfoliosToEmulator(); TrySubscribeMarketData(); } break; } case MessageTypes.Disconnect: { if (direction == MessageDirections.Out && adapterType == MessageAdapterTypes.MarketData) { ResetMarketDataSubscriptions(); } break; } case MessageTypes.MarketData: { var mdMsg = (MarketDataMessage)message; var securityId = mdMsg.SecurityId; if (direction == MessageDirections.Out && mdMsg.Error == null && !securityId.SecurityCode.IsDefault() && !securityId.BoardCode.IsDefault()) { var security = GetSecurity(securityId); var types = _exports.TryGetValue(security); if (types != null && !types.TryGetValue(mdMsg.DataType)) { types[mdMsg.DataType] = true; } } break; } case MessageTypes.Security: { var secMsg = (SecurityMessage)message; var board = ExchangeBoard.GetBoard(secMsg.SecurityId.BoardCode); if (board != null) { SendToEmulator(new[] { board.ToMessage() }); } break; } } base.OnProcessMessage(message, adapterType, direction); }