Esempio n. 1
0
        /// <summary>
        /// To process the message, containing market data.
        /// </summary>
        /// <param name="message">The message, containing market data.</param>
        protected override void OnProcessMessage(Message message)
        {
            if (message.Type == MessageTypes.Connect && message.Adapter == TransactionAdapter)
            {
                // передаем первоначальное значение размера портфеля в эмулятор
                TransactionAdapter.SendInMessage(_portfolio.ToMessage());
                TransactionAdapter.SendInMessage(new PortfolioChangeMessage
                {
                    PortfolioName = _portfolio.Name
                }.TryAdd(PositionChangeTypes.BeginValue, _portfolio.BeginValue));
            }
            else if (message.Adapter == MarketDataAdapter)
            {
                switch (message.Type)
                {
                case MessageTypes.Connect:
                case MessageTypes.Disconnect:
                case MessageTypes.MarketData:
                case MessageTypes.SecurityLookupResult:
                    break;

                default:
                    TransactionAdapter.SendInMessage(message);
                    break;
                }
            }

            base.OnProcessMessage(message);
        }
 /// <summary>
 /// Остановить получение новой информации по портфелю.
 /// </summary>
 /// <param name="portfolio">Портфель, по которому необходимо остановить получение новой информации.</param>
 protected virtual void OnUnRegisterPortfolio(Portfolio portfolio)
 {
     TransactionAdapter.SendInMessage(new PortfolioMessage
     {
         PortfolioName = portfolio.Name,
         TransactionId = TransactionIdGenerator.GetNextId(),
         IsSubscribe   = false
     });
 }
Esempio n. 3
0
            protected override void OnProcess(FixSession session, string client, string msgStr, bool isMarketData)
            {
                var msgType = QuickFix.Message.GetMsgType(msgStr);

                switch (msgType)
                {
                case QuikFixMessages.NewStopOrderSingle:
                {
                    this.AddInfoLog("From client {0}: NewStopOrderSingle", client);

                    var fixMsg = session.ToMessage <NewStopOrderSingle>(msgStr);
                    var regMsg = fixMsg.ToRegisterMessage();

                    regMsg.TransactionId = CreateTransactionId(client, regMsg.TransactionId);

                    var condition = new QuikOrderCondition
                    {
                        Type                            = (QuikOrderConditionTypes)fixMsg.Type.Obj,
                        Result                          = fixMsg.IsSetResult() ? (QuikOrderConditionResults?)fixMsg.Result.Obj : null,
                        StopPriceCondition              = (QuikStopPriceConditions)fixMsg.StopPriceCondition.Obj,
                        StopPrice                       = fixMsg.IsSetStopPx() ? fixMsg.StopPx.Obj : (decimal?)null,
                        StopLimitPrice                  = fixMsg.IsSetStopLimitPrice() ? fixMsg.StopLimitPrice.Obj : (decimal?)null,
                        IsMarketStopLimit               = fixMsg.IsSetIsMarketStopLimit() ? fixMsg.IsMarketStopLimit.Obj : (bool?)null,
                        ConditionOrderId                = fixMsg.IsSetConditionOrderId() ? fixMsg.ConditionOrderId.Obj : (long?)null,
                        ConditionOrderSide              = (Sides)fixMsg.ConditionOrderSide.Obj,
                        ConditionOrderPartiallyMatched  = fixMsg.IsSetConditionOrderPartiallyMatched() ? fixMsg.ConditionOrderPartiallyMatched.Obj : (bool?)null,
                        ConditionOrderUseMatchedBalance = fixMsg.IsSetConditionOrderUseMatchedBalance() ? fixMsg.ConditionOrderUseMatchedBalance.Obj : (bool?)null,
                        LinkedOrderPrice                = fixMsg.IsSetLinkedOrderPrice() ? fixMsg.LinkedOrderPrice.Obj : (decimal?)null,
                        LinkedOrderCancel               = fixMsg.LinkedOrderCancel.Obj,
                        Offset                          = fixMsg.IsSetOffset() ? fixMsg.Offset.Obj.ToUnit() : null,
                        Spread                          = fixMsg.IsSetStopSpread() ? fixMsg.StopSpread.Obj.ToUnit() : null,
                        IsMarketTakeProfit              = fixMsg.IsSetIsMarketTakeProfit() ? fixMsg.IsMarketTakeProfit.Obj : (bool?)null,
                    };

                    if (fixMsg.IsSetOtherSecurityCode())
                    {
                        condition.OtherSecurityId = new SecurityId {
                            SecurityCode = fixMsg.OtherSecurityCode.Obj
                        }
                    }
                    ;
                    if (fixMsg.IsSetActiveTimeFrom() && fixMsg.IsSetActiveTimeTo())
                    {
                        condition.ActiveTime = new Range <DateTimeOffset>(fixMsg.ActiveTimeFrom.Obj.ApplyTimeZone(TimeHelper.Moscow), fixMsg.ActiveTimeTo.Obj.ApplyTimeZone(TimeHelper.Moscow));
                    }

                    regMsg.Condition = condition;

                    TransactionAdapter.SendInMessage(regMsg);
                    return;
                }
                }

                base.OnProcess(session, client, msgStr, isMarketData);
            }
Esempio n. 4
0
        private void OnEmulationStarting()
        {
            IsFinished = false;

            // подписчики StateChanged запускают стратегии, которые интересуются MarketTime в OnRunning
            TransactionAdapter.SendInMessage(new ResetMessage());

            _sessionHolder.SecurityProvider.LookupAll().ForEach(SendSecurity);
            _initialMoney.ForEach(p => SendPortfolio(p.Key));

            SetEmulationState(EmulationStates.Started);
        }
Esempio n. 5
0
 /// <summary>
 /// Перерегистрировать заявку на бирже.
 /// </summary>
 /// <param name="oldOrder">Заявка, которую нужно снять.</param>
 /// <param name="newOrder">Новая заявка, которую нужно зарегистрировать.</param>
 protected override void OnReRegisterOrder(Order oldOrder, Order newOrder)
 {
     //Quik не поддерживает Move с MODE=1 для Единой Денежной Позиции.
     //http://quik.ru/forum/import/57855/57855/
     //Поэтому делаем Cancel, потом Register
     if (IsSupportAtomicReRegister && oldOrder.Security.Board.IsSupportAtomicReRegister && !IsCommonMonetaryPosition)
     {
         TransactionAdapter.SendInMessage(oldOrder.CreateReplaceMessage(newOrder, GetSecurityId(newOrder.Security)));
     }
     else
     {
         base.OnReRegisterOrder(oldOrder, newOrder);
     }
 }
Esempio n. 6
0
        /// <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);
        }
Esempio n. 7
0
 /// <summary>
 /// Перерегистрировать заявку на бирже.
 /// </summary>
 /// <param name="oldOrder">Старая заявка, которую нужно перерегистрировать.</param>
 /// <param name="newOrder">Информация о новой заявке.</param>
 protected override void OnReRegisterOrder(Order oldOrder, Order newOrder)
 {
     if (IsSupportAtomicReRegister &&
         oldOrder.Security.Board.IsSupportAtomicReRegister
         // http://www.itinvest.ru/forum/index.php?showtopic=63720&view=findpost&p=262059
         && oldOrder.Balance == newOrder.Volume)
     {
         TransactionAdapter.SendInMessage(oldOrder.CreateReplaceMessage(newOrder, GetSecurityId(newOrder.Security)));
     }
     else
     {
         base.OnReRegisterOrder(oldOrder, newOrder);
     }
 }
Esempio n. 8
0
        /// <summary>
        /// Начать эмуляцию.
        /// </summary>
        /// <param name="startDate">Дата в истории, с которой необходимо начать эмуляцию.</param>
        /// <param name="stopDate">Дата в истории, на которой необходимо закончить эмуляцию (дата включается).</param>
        public void Start(DateTime startDate, DateTime stopDate)
        {
            if (stopDate < startDate)
            {
                throw new ArgumentOutOfRangeException("startDate", startDate, LocalizedStrings.Str1119Params.Put(startDate, stopDate));
            }

            //f (stopDate == startDate)
            //throw new ArgumentOutOfRangeException("startDate", startDate, "Дата начала {0} равна дате окончания.".Put(startDate));

            if (!CheckState(EmulationStates.Stopped))
            {
                throw new InvalidOperationException(LocalizedStrings.Str1120Params.Put(State));
            }

            //_sessionHolder.StartDate = startDate;
            //_sessionHolder.StopDate = stopDate;

            ClearCache();

            ((IncrementalIdGenerator)TransactionIdGenerator).Current = MarketEmulator.Settings.InitialTransactionId;

            TransactionAdapter.SendInMessage(new TimeMessage
            {
                ServerTime = startDate,
                LocalTime  = startDate,
            });
            //base.OnProcessMessage(new TimeMessage { LocalTime = startDate }, MessageAdapterTypes.Transaction, MessageDirections.In);

            ProcessedEventCount = 0;

            //SetEmulationState(EmulationStates.Starting);
            MarketDataAdapter.SendInMessage(new EmulationStateMessage
            {
                //OldState = State,
                NewState  = EmulationStates.Starting,
                StartDate = startDate,
                StopDate  = stopDate,
                LocalTime = startDate,
            });
        }
        /// <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);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Сменить пароль.
        /// </summary>
        /// <param name="adapterType">Тип адаптера, в который необходимо отправить сообщение о смене пароля.</param>
        /// <param name="newPassword">Новый пароль.</param>
        public void ChangePassword(MessageAdapterTypes adapterType, string newPassword)
        {
            var msg = new ChangePasswordMessage
            {
                NewPassword   = newPassword.To <SecureString>(),
                TransactionId = TransactionIdGenerator.GetNextId()
            };

            switch (adapterType)
            {
            case MessageAdapterTypes.Transaction:
                TransactionAdapter.SendInMessage(msg);
                break;

            case MessageAdapterTypes.MarketData:
                MarketDataAdapter.SendInMessage(msg);
                break;

            default:
                throw new ArgumentOutOfRangeException("adapterType");
            }
        }
Esempio n. 11
0
        /// <summary>
        /// To process the message, containing market data.
        /// </summary>
        /// <param name="message">The message, containing market data.</param>
        protected override void OnProcessMessage(Message message)
        {
            try
            {
                switch (message.Type)
                {
                case MessageTypes.Connect:
                {
                    base.OnProcessMessage(message);

                    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;

                case MessageTypes.Security:
                case MessageTypes.Board:
                case MessageTypes.Level1Change:
                case MessageTypes.QuoteChange:
                case MessageTypes.Time:
                case MessageTypes.CandlePnF:
                case MessageTypes.CandleRange:
                case MessageTypes.CandleRenko:
                case MessageTypes.CandleTick:
                case MessageTypes.CandleTimeFrame:
                case MessageTypes.CandleVolume:
                case MessageTypes.Execution:
                {
                    if (message.Adapter == MarketDataAdapter)
                    {
                        TransactionAdapter.SendInMessage(message);
                    }
                    else if (message.Adapter == TransactionAdapter)
                    {
                        var candleMsg = message as CandleMessage;

                        if (candleMsg != null)
                        {
                            if (!UseExternalCandleSource)
                            {
                                break;
                            }

                            var series = _series.TryGetValue(Tuple.Create(candleMsg.SecurityId, candleMsg.Type.ToCandleMarketDataType(), candleMsg.Arg));

                            if (series != null)
                            {
                                _newCandles.SafeInvoke(series, new[] { candleMsg.ToCandle(series) });

                                if (candleMsg.IsFinished)
                                {
                                    _stopped.SafeInvoke(series);
                                }
                            }

                            break;
                        }
                    }

                    base.OnProcessMessage(message);
                    break;
                }

                default:
                {
                    if (State == EmulationStates.Stopping && message.Type != MessageTypes.Disconnect)
                    {
                        break;
                    }

                    base.OnProcessMessage(message);
                    break;
                }
                }
            }
            catch (Exception ex)
            {
                SendOutError(ex);
                SendEmulationState(EmulationStates.Stopping);
            }
        }