Exemple #1
0
            private void Load()
            {
                if (!File.Exists(_file))
                {
                    return;
                }

                var proxySet = _format
                               .Split(';')
                               .Select(s => MemberProxy.Create(typeof(Security), s.Substring(1, s.Length - 2)))
                               .ToArray();

                CultureInfo.InvariantCulture.DoInCulture(() =>
                {
                    foreach (var line in File.ReadAllLines(_file))
                    {
                        var security = new Security();

                        var cells = line.Split(';');

                        for (var i = 0; i < proxySet.Length; i++)
                        {
                            proxySet[i].SetValue(security, cells[i].To(proxySet[i].ReturnType));
                        }

                        var id         = security.Id.ToSecurityId();
                        security.Code  = id.SecurityCode;
                        security.Board = _parent.ExchangeInfoProvider.GetOrCreateBoard(id.BoardCode);

                        _securities.Add(security);
                    }
                });
            }
Exemple #2
0
        /// <summary>
        /// Подписаться на получение свечек.
        /// </summary>
        /// <param name="series">Серия свечек.</param>
        /// <param name="from">Начальная дата, с которой необходимо получать данные.</param>
        /// <param name="to">Конечная дата, до которой необходимо получать данные.</param>
        public void SubscribeCandles(CandleSeries series, DateTimeOffset from, DateTimeOffset to)
        {
            if (series == null)
            {
                throw new ArgumentNullException("series");
            }

            if (series.CandleType != typeof(TimeFrameCandle))
            {
                throw new ArgumentException(LocalizedStrings.NotSupportCandle.Put("SmartCOM", series.CandleType), "series");
            }

            if (!(series.Arg is TimeSpan))
            {
                throw new ArgumentException(LocalizedStrings.WrongCandleArg.Put(series.Arg), "series");
            }

            var timeFrame = (TimeSpan)series.Arg;

            using (new Scope <CandleSeries>(series))
            {
                to = timeFrame.GetCandleBounds(series.Security.ToExchangeTime(CurrentTime)).Min;

                if (from >= (to - timeFrame))
                {
                    from = to - timeFrame;
                }

                RequestCandles(series.Security, timeFrame, new Range <DateTimeOffset>(from, to));
                _realTimeSeries.Add(series);
            }
        }
        private void ProcessMarketData(MarketDataMessage mdMsg)
        {
            switch (mdMsg.DataType)
            {
            case MarketDataTypes.Level1:
            {
                if (mdMsg.IsSubscribe)
                {
                    _subscribedLevel1.Add(mdMsg.SecurityId);
                }
                else
                {
                    _subscribedLevel1.Remove(mdMsg.SecurityId);
                }

                break;
            }

            case MarketDataTypes.MarketDepth:
            {
                if (mdMsg.IsSubscribe)
                {
                    _subscribedDepths.Add(mdMsg.SecurityId, mdMsg.MaxDepth ?? MarketDataMessage.DefaultMaxDepth);
                }
                else
                {
                    _subscribedDepths.Remove(mdMsg.SecurityId);
                }

                break;
            }

            case MarketDataTypes.Trades:
            {
                if (mdMsg.IsSubscribe)
                {
                    _subscribedTicks.Add(mdMsg.SecurityId);
                }
                else
                {
                    _subscribedTicks.Remove(mdMsg.SecurityId);
                }

                break;
            }

            default:
            {
                SendOutMarketDataNotSupported(mdMsg.TransactionId);
                return;
            }
            }

            var reply = (MarketDataMessage)mdMsg.Clone();

            reply.OriginalTransactionId = mdMsg.OriginalTransactionId;
            SendOutMessage(reply);
        }
        /// <inheritdoc />
        protected override bool OnSendInMessage(Message message)
        {
            switch (message.Type)
            {
            case MessageTypes.PortfolioLookup:
            {
                var lookupMsg = (PortfolioLookupMessage)message;

                if (lookupMsg.IsSubscribe)
                {
                    if (lookupMsg.To == null)
                    {
                        this.AddDebugLog("Subscription {0} added.", lookupMsg.TransactionId);
                        _subscriptions.Add(lookupMsg.TransactionId);

                        lock (_sync)
                            _positionManager.ProcessMessage(message);
                    }

                    if (IsEmulate)
                    {
                        RaiseNewOutMessage(lookupMsg.CreateResult());
                        return(true);
                    }
                }
                else
                {
                    if (_subscriptions.Remove(lookupMsg.OriginalTransactionId))
                    {
                        this.AddDebugLog("Subscription {0} removed.", lookupMsg.OriginalTransactionId);

                        lock (_sync)
                            _positionManager.ProcessMessage(message);
                    }

                    if (IsEmulate)
                    {
                        //RaiseNewOutMessage(lookupMsg.CreateResponse());
                        return(true);
                    }
                }

                break;
            }

            default:
            {
                lock (_sync)
                    _positionManager.ProcessMessage(message);

                break;
            }
            }

            return(base.OnSendInMessage(message));
        }
Exemple #5
0
        /// <summary>
        /// Добавить новое подключение к базе данных.
        /// </summary>
        /// <param name="connection">Новое подключение.</param>
        public void AddConnection(DatabaseConnectionPair connection)
        {
            if (connection == null)
            {
                throw new ArgumentNullException(nameof(connection));
            }

            _connections.Add(connection);
            NewConnectionCreated.SafeInvoke(connection);
        }
        private void ProcessMarketData(MarketDataMessage mdMsg)
        {
            switch (mdMsg.DataType)
            {
            case MarketDataTypes.Level1:
            {
                if (mdMsg.IsSubscribe)
                {
                    _subscribedLevel1.Add(mdMsg.SecurityId);
                }
                else
                {
                    _subscribedLevel1.Remove(mdMsg.SecurityId);
                }

                break;
            }

            case MarketDataTypes.MarketDepth:
            {
                if (mdMsg.IsSubscribe)
                {
                    _subscribedDepths.Add(mdMsg.SecurityId, mdMsg.MaxDepth);
                }
                else
                {
                    _subscribedDepths.Remove(mdMsg.SecurityId);
                }

                break;
            }

            case MarketDataTypes.Trades:
            {
                if (mdMsg.IsSubscribe)
                {
                    _subscribedTicks.Add(mdMsg.SecurityId);
                }
                else
                {
                    _subscribedTicks.Remove(mdMsg.SecurityId);
                }

                break;
            }

            default:
                throw new ArgumentOutOfRangeException("mdMsg", mdMsg.DataType, LocalizedStrings.Str1618);
            }

            var reply = (MarketDataMessage)mdMsg.Clone();

            reply.OriginalTransactionId = mdMsg.OriginalTransactionId;
            SendOutMessage(reply);
        }
Exemple #7
0
        private bool AddOrder(Order o)
        {
            if (_chartOrders.Contains(o))
            {
                return(false);
            }

            _chartOrders.Add(o);
            Orders.Add(o);

            return(true);
        }
Exemple #8
0
        /// <summary>
        /// Отправить заявку на присоединение.
        /// </summary>
        /// <param name="join">Заявка.</param>
        public void Join(ChatJoin join)
        {
            if (join == null)
            {
                throw new ArgumentNullException("join");
            }

            join.Id = Invoke(f => f.Join(SessionId, join));

            if (join.Id != 0)
            {
                _myJoins.Add(join.Id, join);
            }

            //для открытых комнат событие JoinAccepted не вызывается
            //поэтому сразу добавляем ее в доступные комнаты
            if (_rooms[join.RoomId].IsEveryOne)
            {
                _accessedRooms.Add(join.RoomId);
            }
        }
        private void ProcessExchanges(IEnumerable <string> exchanges)
        {
            foreach (var exchange in exchanges)
            {
                _boards.Add(exchange);

                SendOutMessage(new BoardMessage
                {
                    Code         = exchange,
                    ExchangeCode = exchange,
                });
            }
        }
Exemple #10
0
        /// <summary>
        /// Подписаться на получение свечек.
        /// </summary>
        /// <param name="series">Серия свечек.</param>
        /// <param name="from">Начальная дата, с которой необходимо получать данные.</param>
        /// <param name="to">Конечная дата, до которой необходимо получать данные.</param>
        public void SubscribeCandles(CandleSeries series, DateTimeOffset from, DateTimeOffset to)
        {
            if (series == null)
            {
                throw new ArgumentNullException("series");
            }

            var timeFrame     = series.Arg.To <TimeSpan>();
            var transactionId = TransactionIdGenerator.GetNextId();

            _series[transactionId] = series;
            _realTimeSeries.Add(series);

            RequestCandles(series.Security, timeFrame, from, to, transactionId);
        }
            public void RegisterPortfolio(Portfolio portfolio)
            {
                if (portfolio == null)
                {
                    throw new ArgumentNullException(nameof(portfolio));
                }

                if (portfolio is BasketPortfolio basketPortfolio)
                {
                    basketPortfolio.InnerPortfolios.ForEach(_connector.RegisterPortfolio);
                }
                else
                {
                    _registeredPortfolios.Add(portfolio);
                    _connector.OnRegisterPortfolio(portfolio);
                }
            }
        private void ProcessConnectMessage(IMessageAdapter innerAdapter, ConnectMessage message)
        {
            if (message.Error != null)
            {
                this.AddErrorLog(LocalizedStrings.Str625Params, innerAdapter.GetType().Name, message.Error);
            }
            else
            {
                var adapter = _hearbeatAdapters[innerAdapter];

                foreach (var supportedMessage in adapter.SupportedMessages)
                {
                    _messageTypeAdapters.SafeAdd(supportedMessage).Add(adapter);
                }

                _connectedAdapters.Add(adapter);
            }

            SendOutMessage(message);
        }
Exemple #13
0
        private void ProcessMarketData(MarketDataMessage mdMsg)
        {
            var secCode   = mdMsg.SecurityId.SecurityCode;
            var boardCode = mdMsg.SecurityId.BoardCode;

            switch (mdMsg.DataType)
            {
            case MarketDataTypes.Level1:
            {
                if (mdMsg.IsSubscribe)
                {
                    _client.SubscribeQuote(secCode, boardCode);
                }
                else
                {
                    _client.UnsubsribeQuote(secCode, boardCode);
                }

                break;
            }

            case MarketDataTypes.MarketDepth:
            {
                if (mdMsg.IsSubscribe)
                {
                    _client.SubscribeLevel2(secCode, boardCode);
                }
                else
                {
                    _client.UnsubsribeLevel2(secCode, boardCode);
                }

                break;
            }

            case MarketDataTypes.Trades:
            {
                if (mdMsg.IsSubscribe)
                {
                    _subscribedSecuritiesToTrade.Add(secCode);
                    _client.SubscribeQuote(secCode, boardCode);
                }
                else
                {
                    _subscribedSecuritiesToTrade.Remove(secCode);
                    _client.UnsubsribeQuote(secCode, boardCode);
                }

                break;
            }

            case MarketDataTypes.News:
            {
                if (mdMsg.IsSubscribe)
                {
                    _client.SubscribeNews();
                }
                else
                {
                    _client.UnsubscribeNews();
                }

                break;
            }

            default:
            {
                SendOutMarketDataNotSupported(mdMsg.TransactionId);
                return;
            }
            }

            var reply = (MarketDataMessage)mdMsg.Clone();

            reply.OriginalTransactionId = mdMsg.TransactionId;
            SendOutMessage(reply);
        }
        /// <inheritdoc />
        protected override bool OnSendInMessage(Message message)
        {
            switch (message.Type)
            {
            case MessageTypes.Reset:
            {
                lock (_syncObject)
                {
                    _byId.Clear();
                    _online.Clear();
                    _passThrough.Clear();
                    _allSecSubscriptions.Clear();
                    _allSecSubscriptionsPassThrough.Clear();
                }

                break;
            }

            case MessageTypes.MarketData:
            {
                var mdMsg = (MarketDataMessage)message;

                if (mdMsg.IsSubscribe)
                {
                    if (mdMsg.DataType2 == DataType.MarketDepth)
                    {
                        var transId = mdMsg.TransactionId;

                        lock (_syncObject)
                        {
                            if (mdMsg.SecurityId == default)
                            {
                                if (mdMsg.DoNotBuildOrderBookInrement)
                                {
                                    _allSecSubscriptionsPassThrough.Add(transId);
                                }
                                else
                                {
                                    _allSecSubscriptions.Add(transId);
                                }

                                break;
                            }

                            if (mdMsg.DoNotBuildOrderBookInrement)
                            {
                                _passThrough.Add(transId);
                                break;
                            }

                            var info = new BookInfo(mdMsg.SecurityId)
                            {
                                Builder = { Parent = this }
                            };

                            info.SubscriptionIds.Add(transId);

                            _byId.Add(transId, info);
                        }

                        this.AddInfoLog("OB incr subscribed {0}/{1}.", mdMsg.SecurityId, transId);
                    }
                }
                else
                {
                    RemoveSubscription(mdMsg.OriginalTransactionId);
                }

                break;
            }
            }

            return(base.OnSendInMessage(message));
        }
        private void ProcessMarketData(MarketDataMessage mdMsg)
        {
            var secCode   = mdMsg.SecurityId.SecurityCode;
            var boardCode = mdMsg.SecurityId.BoardCode;

            switch (mdMsg.DataType)
            {
            case MarketDataTypes.Level1:
            {
                if (mdMsg.IsSubscribe)
                {
                    SessionHolder.Session.SubscribeQuote(secCode, boardCode);
                }
                else
                {
                    SessionHolder.Session.UnsubsribeQuote(secCode, boardCode);
                }

                break;
            }

            case MarketDataTypes.MarketDepth:
            {
                if (mdMsg.IsSubscribe)
                {
                    SessionHolder.Session.SubscribeLevel2(secCode, boardCode);
                }
                else
                {
                    SessionHolder.Session.UnsubsribeLevel2(secCode, boardCode);
                }
                break;
            }

            case MarketDataTypes.Trades:
            {
                if (mdMsg.IsSubscribe)
                {
                    _subscribedSecuritiesToTrade.Add(secCode);
                    SessionHolder.Session.SubscribeQuote(secCode, boardCode);
                }
                else
                {
                    _subscribedSecuritiesToTrade.Remove(secCode);
                    SessionHolder.Session.UnsubsribeQuote(secCode, boardCode);
                }
                break;
            }

            case MarketDataTypes.News:
            {
                if (mdMsg.IsSubscribe)
                {
                    SessionHolder.Session.SubscribeNews();
                }
                else
                {
                    SessionHolder.Session.UnsubscribeNews();
                }
                break;
            }

            default:
                throw new ArgumentOutOfRangeException("message", mdMsg.DataType, LocalizedStrings.Str1618);
            }

            var reply = (MarketDataMessage)mdMsg.Clone();

            reply.OriginalTransactionId = mdMsg.TransactionId;
            SendOutMessage(reply);
        }
Exemple #16
0
        private void ProcessMarketData(MarketDataMessage mdMsg)
        {
            switch (mdMsg.DataType)
            {
            case MarketDataTypes.Level1:
            {
                //if (mdMsg.IsSubscribe)
                //	_subscribedLevel1.Add(secCode);
                //else
                //	_subscribedLevel1.Remove(secCode);

                break;
            }

            case MarketDataTypes.MarketDepth:
            {
                if (mdMsg.IsSubscribe)
                {
                    _subscribedDepths.Add(mdMsg.SecurityId);

                    if (_subscribedDepths.Count == 1)
                    {
                        _pusherClient.SubscribeDepths();
                    }
                }
                else
                {
                    _subscribedDepths.Remove(mdMsg.SecurityId);

                    if (_subscribedDepths.Count == 0)
                    {
                        _pusherClient.UnSubscribeDepths();
                    }
                }

                break;
            }

            case MarketDataTypes.Trades:
            {
                if (mdMsg.IsSubscribe)
                {
                    if (mdMsg.From != null && mdMsg.From.Value.DateTime == DateTime.Today)
                    {
                        _httpClient.RequestTransactions().Select(t => new ExecutionMessage
                            {
                                ExecutionType = ExecutionTypes.Tick,
                                SecurityId    = _btcUsd,
                                TradeId       = t.Id,
                                TradePrice    = (decimal)t.Price,
                                TradeVolume   = (decimal)t.Amount,
                                ServerTime    = t.Time.ApplyTimeZone(TimeZoneInfo.Utc)
                            }).ForEach(SendOutMessage);
                    }

                    _subscribedTicks.Add(mdMsg.SecurityId);

                    if (_subscribedTicks.Count == 1)
                    {
                        _pusherClient.SubscribeTrades();
                    }
                }
                else
                {
                    _subscribedTicks.Remove(mdMsg.SecurityId);

                    if (_subscribedTicks.Count == 0)
                    {
                        _pusherClient.UnSubscribeTrades();
                    }
                }

                break;
            }

            default:
            {
                SendOutMarketDataNotSupported(mdMsg.TransactionId);
                return;
            }
            }

            var reply = (MarketDataMessage)mdMsg.Clone();

            reply.OriginalTransactionId = mdMsg.OriginalTransactionId;
            SendOutMessage(reply);
        }
        /// <inheritdoc />
        protected override bool OnSendInMessage(Message message)
        {
            switch (message.Type)
            {
            case MessageTypes.Reset:
            {
                _subscriptions.Clear();
                _strategyIdMap.Clear();
                _strategySubscriptions.Clear();

                lock (_sync)
                    _positionManager.ProcessMessage(message);

                break;
            }

            case MessageTypes.PortfolioLookup:
            {
                var lookupMsg = (PortfolioLookupMessage)message;

                if (lookupMsg.IsSubscribe)
                {
                    if (!lookupMsg.StrategyId.IsEmpty())
                    {
                        this.AddDebugLog("Subscription (strategy='{1}') {0} added.", lookupMsg.TransactionId, lookupMsg.StrategyId);
                        _strategyIdMap.Add(lookupMsg.TransactionId, lookupMsg.StrategyId);
                        _strategySubscriptions.SafeAdd(lookupMsg.StrategyId).Add(lookupMsg.TransactionId);
                        RaiseNewOutMessage(lookupMsg.CreateResult());
                        return(true);
                    }

                    if (lookupMsg.To == null)
                    {
                        this.AddDebugLog("Subscription {0} added.", lookupMsg.TransactionId);
                        _subscriptions.Add(lookupMsg.TransactionId);

                        lock (_sync)
                            _positionManager.ProcessMessage(message);
                    }

                    if (IsEmulate)
                    {
                        RaiseNewOutMessage(lookupMsg.CreateResult());
                        return(true);
                    }
                }
                else
                {
                    if (_subscriptions.Remove(lookupMsg.OriginalTransactionId))
                    {
                        this.AddDebugLog("Subscription {0} removed.", lookupMsg.OriginalTransactionId);

                        lock (_sync)
                            _positionManager.ProcessMessage(message);
                    }
                    else if (_strategyIdMap.TryGetAndRemove(lookupMsg.OriginalTransactionId, out var strategyId))
                    {
                        _strategySubscriptions.TryGetValue(strategyId)?.Remove(lookupMsg.OriginalTransactionId);
                        this.AddDebugLog("Subscription (strategy='{1}') {0} removed.", lookupMsg.OriginalTransactionId, strategyId);
                        return(true);
                    }

                    if (IsEmulate)
                    {
                        //RaiseNewOutMessage(lookupMsg.CreateResponse());
                        return(true);
                    }
                }

                break;
            }

            default:
            {
                lock (_sync)
                    _positionManager.ProcessMessage(message);

                break;
            }
            }

            return(base.OnSendInMessage(message));
        }