Exemple #1
0
        private static void GetCandleParams(MarketDataTypes type, object arg, out string strArg, out string intervalType)
        {
            switch (type)
            {
            case MarketDataTypes.CandleTimeFrame:
            {
                intervalType = "s";
                strArg       = arg.To <TimeSpan>().TotalSeconds.To <int>().To <string>();
                break;
            }

            case MarketDataTypes.CandleTick:
            {
                intervalType = "t";
                strArg       = arg.To <string>();
                break;
            }

            case MarketDataTypes.CandleVolume:
            {
                intervalType = "v";
                strArg       = arg.To <string>();
                break;
            }

            default:
                throw new ArgumentOutOfRangeException("type", type, LocalizedStrings.WrongCandleType);
            }
        }
Exemple #2
0
        private void SendInHistorySourceMessage(Security security, MarketDataTypes dataType, object arg, Func <DateTimeOffset, IEnumerable <Message> > getMessages)
        {
            var isSubscribe = getMessages != null;

            if (isSubscribe)
            {
                if (_historySourceSubscriptions.ChangeSubscribers(Tuple.Create(security.ToSecurityId(), dataType, arg), true) != 1)
                {
                    return;
                }
            }
            else
            {
                if (_historySourceSubscriptions.ChangeSubscribers(Tuple.Create(security.ToSecurityId(), dataType, arg), false) != 0)
                {
                    return;
                }
            }

            SendInMessage(new HistorySourceMessage
            {
                IsSubscribe = isSubscribe,
                SecurityId  = security.ToSecurityId(),
                DataType    = dataType,
                Arg         = arg,
                GetMessages = getMessages
            });
        }
        /// <summary>
        /// Отписаться от получения рыночных данных по инструменту.
        /// </summary>
        /// <param name="security">Инструмент, по которому необходимо начать получать новую информацию.</param>
        /// <param name="type">Тип рыночных данных.</param>
        public override void UnSubscribeMarketData(Security security, MarketDataTypes type)
        {
            var tf = MarketEmulator.Settings.UseCandlesTimeFrame;

            if (tf != null)
            {
                var securityId = GetSecurityId(security);
                var key        = Tuple.Create(securityId, tf.Value);

                if (_subscribedCandles.ChangeSubscribers(key, -1) != 0)
                {
                    return;
                }

                MarketDataAdapter.SendInMessage(new MarketDataMessage
                {
                    //SecurityId = securityId,
                    DataType    = MarketDataTypes.CandleTimeFrame,
                    Arg         = tf.Value,
                    IsSubscribe = false,
                }.FillSecurityInfo(this, security));
            }
            else
            {
                base.UnSubscribeMarketData(security, type);
            }
        }
Exemple #4
0
            private void UnSubscribeContinuous(ContinuousSecurity security, MarketDataTypes type)
            {
                lock (_continuousSecurities.SyncRoot)
                {
                    var node = _continuousSecurities.Find(new ContinuousInfo(security, type));

                    if (node == null)
                    {
                        return;
                    }

                    var diff = node.Value.Elapsed;
                    var curr = node;

                    while (curr != null)
                    {
                        curr.Value.Elapsed += diff;
                        curr = curr.Next;
                    }

                    _continuousSecurities.Remove(node);

                    if (_continuousSecurities.Count == 0)
                    {
                        _connector.MarketTimeChanged -= ConnectorOnMarketTimeChanged;
                    }
                }
            }
Exemple #5
0
        /// <summary>
        /// Create candle builder.
        /// </summary>
        /// <param name="dataType">Market data type.</param>
        /// <returns>Candle builder.</returns>
        public static ICandleBuilder CreateCandleBuilder(this MarketDataTypes dataType)
        {
            switch (dataType)
            {
            case MarketDataTypes.CandleTimeFrame:
                return(new TimeFrameCandleBuilder());

            case MarketDataTypes.CandleTick:
                return(new TickCandleBuilder());

            case MarketDataTypes.CandleVolume:
                return(new VolumeCandleBuilder());

            case MarketDataTypes.CandleRange:
                return(new RangeCandleBuilder());

            case MarketDataTypes.CandlePnF:
                return(new PnFCandleBuilder());

            case MarketDataTypes.CandleRenko:
                return(new RenkoCandleBuilder());

            default:
                throw new ArgumentOutOfRangeException(nameof(dataType), dataType, LocalizedStrings.Str1219);
            }
        }
Exemple #6
0
 private void TryUnSubscribe(Security subscriber, MarketDataTypes type)
 {
     if (TryUnSubscribe(GetSubscribers(type), subscriber))
     {
         SendUnSubscribeMessage(subscriber, type);
     }
 }
Exemple #7
0
            private void TryUnSubscribe(Security subscriber, MarketDataTypes type)
            {
                var subscribers = GetSubscribers(type);
                var subscribed  = false;

                lock (subscribers.SyncRoot)
                {
                    var value = subscribers.TryGetValue2(subscriber);

                    if (value == 0)
                    {
                        _unsubscribeActions.SafeAdd(subscriber).Add(type);
                    }

                    if (value > 0)
                    {
                        subscribed = true;
                    }
                }

                if (!subscribed || !TryUnSubscribe(subscribers, subscriber))
                {
                    return;
                }

                SendUnSubscribeMessage(subscriber, type);
            }
Exemple #8
0
 /// <summary>
 /// Отписаться от получения рыночных данных по инструменту.
 /// </summary>
 /// <param name="security">Инструмент, по которому необходимо начать получать новую информацию.</param>
 /// <param name="type">Тип рыночных данных.</param>
 public override void UnSubscribeMarketData(Security security, MarketDataTypes type)
 {
     if (_ownTrader)
     {
         UnderlyingConnector.UnSubscribeMarketData(security, type);
     }
 }
Exemple #9
0
            private void TrySubscribe(Security subscriber, MarketDataTypes type)
            {
                //Если уже выполняется поиск данного инструмента, то нет необходимости в повторном вызове OnRegisterXXX.
                //Если на инструмент была подписка ранее, то просто вызываем событие SubscriptionSucceed.
                var subscribersCount = GetSubscribers(type).ChangeSubscribers(subscriber, true);

                var securityId = _connector.GetSecurityId(subscriber);

                if (subscribersCount == 1)
                {
                    var lookupMessage = new SecurityLookupMessage
                    {
                        SecurityId    = securityId,
                        SecurityType  = subscriber.Type,
                        TransactionId = _connector.TransactionIdGenerator.GetNextId()
                    };

                    _lookupMessages.Add(lookupMessage.TransactionId, Tuple.Create(lookupMessage, subscriber, type));
                    _connector.LookupSecurities(lookupMessage);
                }
                else                // if (subscribed == true)
                {
                    _connector.SendOutMessage(new MarketDataMessage
                    {
                        DataType    = type,
                        IsSubscribe = true,
                        //SecurityId = securityId,
                    }.FillSecurityInfo(_connector, subscriber));
                }
            }
Exemple #10
0
            private void ProcessSecurityMarketData(Security security, MarketDataTypes dataType, Security subscriber)
            {
                var message = new MarketDataMessage
                {
                    DataType    = dataType,
                    IsSubscribe = true,
                    //SecurityId = _connector.GetSecurityId(subscriber),
                    TransactionId = _connector.TransactionIdGenerator.GetNextId()
                };

                switch (dataType)
                {
                case MarketDataTypes.Trades:
                    message.Arg = ExecutionTypes.Tick;
                    break;

                case MarketDataTypes.OrderLog:
                    message.Arg = ExecutionTypes.OrderLog;
                    break;
                }

                message.FillSecurityInfo(_connector, subscriber);

                if (security == null)
                {
                    message.Error = new ArgumentException(LocalizedStrings.Str692Params.Put(message.SecurityId, _connector.Name));
                    _connector.SendOutMessage(message);
                }
                else
                {
                    _connector.SendInMessage(message);
                }
            }
Exemple #11
0
        private void SubscribeMarketData(SecurityId securityId, MarketDataTypes type)
        {
            var message = new MarketDataMessage
            {
                DataType      = type,
                IsSubscribe   = true,
                SecurityId    = securityId,
                From          = DateTimeOffset.MinValue,
                To            = DateTimeOffset.MaxValue,
                TransactionId = _messAdapter.TransactionIdGenerator.GetNextId()
            };

            switch (type)
            {
            case MarketDataTypes.MarketDepth:
                message.MaxDepth = MarketDataMessage.DefaultMaxDepth;
                break;

            case MarketDataTypes.Trades:
                message.Arg = ExecutionTypes.Tick;
                break;

            case MarketDataTypes.OrderLog:
                message.Arg = ExecutionTypes.OrderLog;
                break;
            }

            _messAdapter.SendInMessage(message);
        }
Exemple #12
0
 private void UnSubscribeMarketData(Security security, MarketDataTypes type)
 {
     UnSubscribeMarketData(security, new MarketDataMessage
     {
         DataType    = type,
         IsSubscribe = false,
     });
 }
Exemple #13
0
 /// <summary>
 /// Нужно ли обрабатывать маркет-данные.
 /// </summary>
 /// <param name="dataType">Тип маркет-данных.</param>
 /// <param name="securityId">Идентификатор инструмента.</param>
 /// <returns>Нужно ли обрабатывать маркет-данные.</returns>
 public bool NeedProcess(MarketDataTypes dataType, SecurityId securityId)
 {
     return(_fixServer.HasSubscriptions(dataType, new SecurityId
     {
         SecurityCode = securityId.SecurityCode,
         BoardCode = GetBoardCode(securityId.BoardCode)
     }));
 }
Exemple #14
0
 /// <summary>
 /// Нужно ли обрабатывать маркет-данные.
 /// </summary>
 /// <param name="dataType">Тип маркет-данных.</param>
 /// <param name="securityId">Идентификатор инструмента.</param>
 /// <returns>Нужно ли обрабатывать маркет-данные.</returns>
 public bool NeedProcess(MarketDataTypes dataType, SecurityId securityId)
 {
     return(_fixServer.HasReceivers(dataType, new SecurityId
     {
         SecurityCode = securityId.SecurityCode,
         BoardCode = _sessionHolder.GetBoardCode(securityId.BoardCode)
     }));
 }
Exemple #15
0
        /// <summary>
        /// Add market data type into <see cref="IMessageAdapter.SupportedMarketDataTypes"/>.
        /// </summary>
        /// <param name="adapter">Adapter.</param>
        /// <param name="type">Market data type.</param>
        public static void AddSupportedMarketDataType(this IMessageAdapter adapter, MarketDataTypes type)
        {
            if (adapter == null)
            {
                throw new ArgumentNullException(nameof(adapter));
            }

            adapter.SupportedMarketDataTypes = adapter.SupportedMarketDataTypes.Concat(type).ToArray();
        }
Exemple #16
0
        /// <summary>
        /// Determines whether the specified market-data type is supported by the adapter.
        /// </summary>
        /// <param name="adapter">Adapter.</param>
        /// <param name="type">Message type.</param>
        /// <returns><see langword="true"/> if the specified message type is supported, otherwise, <see langword="false"/>.</returns>
        public static bool IsMarketDataTypeSupported(this IMessageAdapter adapter, MarketDataTypes type)
        {
            if (adapter == null)
            {
                throw new ArgumentNullException(nameof(adapter));
            }

            return(adapter.SupportedMarketDataTypes.Contains(type));
        }
Exemple #17
0
        public static MessageTypes ToMessageType(this MarketDataTypes type, out object arg)
        {
            if (!_messageTypeMap.TryGetValue(type, out var tuple))
            {
                throw new ArgumentOutOfRangeException(nameof(type), type, LocalizedStrings.Str1219);
            }

            arg = tuple.Item2;
            return(tuple.Item1);
        }
            public ICandleBuilder Get(MarketDataTypes type)
            {
                var builder = _builders.TryGetValue(type);

                if (builder == null)
                {
                    throw new ArgumentOutOfRangeException(nameof(type), type, LocalizedStrings.Str1219);
                }

                return(builder);
            }
Exemple #19
0
            private void OnConnectorMarketDataSubscriptionFailed(Security security, MarketDataTypes type, Exception error)
            {
                var types = _unsubscribeActions.TryGetValue(security);

                if (types == null)
                {
                    return;
                }

                types.Remove(type);
            }
        private bool IsSubscribed(MarketDataTypes type, Security security)
        {
            var dic = _subscriptions.TryGetValue(type);

            if (dic == null)
            {
                return(false);
            }

            return(dic.TryGetValue(security) != 0);
        }
Exemple #21
0
        private void ProcessValue(SecurityId securityId, long transactionId, MarketDataTypes dataType, Func <ICandleBuilderSourceValue> getValue)
        {
            var infos = _seriesInfos.TryGetValue(securityId);

            if (infos == null)
            {
                return;
            }

            ICandleBuilderSourceValue value = null;

            foreach (var info in infos)
            {
                if (info.DataType != dataType)
                {
                    continue;
                }

                if (info.TransactionId != transactionId && (transactionId != 0 || info.IsHistory))
                {
                    continue;
                }

                if (value == null)
                {
                    value = getValue();
                }

                if (!CheckTime(info, value))
                {
                    continue;
                }

                var mdMsg   = info.MarketDataMessage;
                var builder = _candleBuilders.Get(mdMsg.DataType);

                if (builder == null)
                {
                    throw new InvalidOperationException($"Builder for {mdMsg.DataType} not found.");
                }

                info.LastTime = value.Time;

                var result = builder.Process(mdMsg, info.CurrentCandleMessage, value);

                foreach (var candleMessage in result)
                {
                    info.CurrentCandleMessage = candleMessage;
                    SendCandle(info, candleMessage);
                }
            }
        }
Exemple #22
0
 private void SubscribeMarketData(Security security, MarketDataTypes type, DateTimeOffset?from = null, DateTimeOffset?to = null, long?count = null, MarketDataTypes?buildFrom = null, Level1Fields?buildField = null, int?maxDepth = null)
 {
     SubscribeMarketData(security, new MarketDataMessage
     {
         DataType    = type,
         IsSubscribe = true,
         From        = from,
         To          = to,
         Count       = count,
         BuildFrom   = buildFrom,
         BuildField  = buildField,
         MaxDepth    = maxDepth,
     });
 }
Exemple #23
0
        private void AddExport(Security security, MarketDataTypes type)
        {
            if (security == null)
            {
                throw new ArgumentNullException("security");
            }

            _exports.SafeAdd(security).SafeAdd(type);

            if (ConnectionState == ConnectionStates.Connected)
            {
                base.SubscribeMarketData(security, type);
            }
        }
Exemple #24
0
            private void TrySubscribe(Security subscriber, MarketDataTypes type)
            {
                var subscribers = GetSubscribers(type);

                //Если уже выполняется поиск данного инструмента, то нет необходимости в повторном вызове OnRegisterXXX.
                //Если на инструмент была подписка ранее, то просто вызываем событие SubscriptionSucceed.
                bool?subscribed = false;

                lock (subscribers.SyncRoot)
                {
                    var value = subscribers.TryGetValue2(subscriber);

                    if (value == null)
                    {
                        subscribers[subscriber] = 0;
                        subscribed = null;
                    }

                    if (value > 0)
                    {
                        subscribers[subscriber] = (int)value + 1;
                        subscribed = true;
                    }
                }

                var securityId = _connector.GetSecurityId(subscriber);

                if (subscribed == null)
                {
                    var lookupMessage = new SecurityLookupMessage
                    {
                        SecurityId    = securityId,
                        SecurityType  = subscriber.Type,
                        TransactionId = _connector.TransactionIdGenerator.GetNextId()
                    };

                    _lookupMessages.Add(lookupMessage.TransactionId, Tuple.Create(lookupMessage, subscriber, type));
                    _connector.LookupSecurities(lookupMessage);
                }

                if (subscribed == true)
                {
                    _connector.SendOutMessage(new MarketDataMessage
                    {
                        DataType    = type,
                        IsSubscribe = true,
                        //SecurityId = securityId,
                    }.FillSecurityInfo(_connector, subscriber));
                }
            }
 private long SubscribeMarketData(Security security, MarketDataTypes type, DateTimeOffset?from = null, DateTimeOffset?to = null, long?count = null, MarketDataBuildModes buildMode = MarketDataBuildModes.LoadAndBuild, MarketDataTypes?buildFrom = null, Level1Fields?buildField = null, int?maxDepth = null, IMessageAdapter adapter = null)
 {
     return(SubscribeMarketData(security, new MarketDataMessage
     {
         DataType = type,
         IsSubscribe = true,
         From = from,
         To = to,
         Count = count,
         BuildMode = buildMode,
         BuildFrom = buildFrom,
         BuildField = buildField,
         MaxDepth = maxDepth,
         Adapter = adapter
     }));
 }
        private void UnSubscribe(MarketDataTypes type, Security security)
        {
            switch (type)
            {
            case MarketDataTypes.Level1:
            case MarketDataTypes.OrderLog:
                break;

            case MarketDataTypes.Trades:
                SafeGetConnector().UnRegisterTrades(security);
                break;

            case MarketDataTypes.MarketDepth:
                SafeGetConnector().UnRegisterMarketDepth(security);
                break;
            }
        }
Exemple #27
0
            public override void SubscribeMarketData(Security security, MarketDataTypes type)
            {
                if (_isHistory && type == MarketDataTypes.Trades)
                {
                    SendInMessage(new MarketDataMessage
                    {
                        //SecurityId = GetSecurityId(security),
                        DataType    = MarketDataTypes.CandleTimeFrame,
                        IsSubscribe = true,
                        From        = _historyMessageAdapter.StartDate,
                        To          = _historyMessageAdapter.StopDate,
                        Arg         = _useCandlesTimeFrame
                    }.FillSecurityInfo(this, security));
                }

                _realConnector.SubscribeMarketData(security, type);
            }
 private Subscription SubscribeMarketData(Security security, MarketDataTypes type, DateTimeOffset?from = null, DateTimeOffset?to = null, long?count = null, MarketDataBuildModes buildMode = MarketDataBuildModes.LoadAndBuild, MarketDataTypes?buildFrom = null, Level1Fields?buildField = null, int?maxDepth = null, TimeSpan?refreshSpeed = null, IOrderLogMarketDepthBuilder depthBuilder = null, IMessageAdapter adapter = null)
 {
     return(SubscribeMarketData(security, new MarketDataMessage
     {
         DataType = type,
         IsSubscribe = true,
         From = from,
         To = to,
         Count = count,
         BuildMode = buildMode,
         BuildFrom = buildFrom,
         BuildField = buildField,
         MaxDepth = maxDepth,
         RefreshSpeed = refreshSpeed,
         DepthBuilder = depthBuilder,
         Adapter = adapter
     }));
 }
Exemple #29
0
            private void SubscribeContinuous(ContinuousSecurity security, MarketDataTypes type)
            {
                lock (_continuousSecurities.SyncRoot)
                {
                    var info = new ContinuousInfo(security, type);

                    if (_continuousSecurities.Contains(info))
                    {
                        return;
                    }

                    _continuousSecurities.AddFirst(info);

                    if (_continuousSecurities.Count == 1)
                    {
                        _connector.MarketTimeChanged += ConnectorOnMarketTimeChanged;
                    }
                }
            }
Exemple #30
0
            public void UnSubscribe(Security security, MarketDataTypes type)
            {
                if (security == null)
                {
                    throw new ArgumentNullException("security");
                }

                if (security is IndexSecurity)
                {
                    ((IndexSecurity)security).InnerSecurities.ForEach(s => _connector.UnSubscribeMarketData(s, type));
                }
                else if (security is ContinuousSecurity)
                {
                    UnSubscribeContinuous((ContinuousSecurity)security, type);
                }
                else
                {
                    TryUnSubscribe(security, type);
                }
            }
		/// <summary>
		/// Зарегистрировать исторические данные.
		/// </summary>
		/// <param name="security">Инструмент.</param>
		/// <param name="dataType">Тип данных.</param>
		/// <param name="arg">Параметр, ассоциированный с типом <paramref name="dataType"/>. Например, <see cref="Candle.Arg"/>.</param>
		/// <param name="getMessages">Функция получения исторических данных.</param>
		public void RegisterHistorySource(Security security, MarketDataTypes dataType, object arg, Func<DateTimeOffset, IEnumerable<Message>> getMessages)
		{
			SendInHistorySourceMessage(security, dataType, arg, getMessages);
		}
Exemple #32
0
        private void SubscribeMarketData(SecurityId securityId, MarketDataTypes type)
        {
            var message = new MarketDataMessage
            {
                DataType = type,
                IsSubscribe = true,
                SecurityId = securityId,
                From = DateTimeOffset.MinValue,
                To = DateTimeOffset.MaxValue,
                TransactionId = _messAdapter.TransactionIdGenerator.GetNextId()
            };

            switch (type)
            {
                case MarketDataTypes.MarketDepth:
                    message.MaxDepth = MarketDataMessage.DefaultMaxDepth;
                    break;
                case MarketDataTypes.Trades:
                    message.Arg = ExecutionTypes.Tick;
                    break;
                case MarketDataTypes.OrderLog:
                    message.Arg = ExecutionTypes.OrderLog;
                    break;
            }

            _messAdapter.SendInMessage(message);
        }
Exemple #33
0
			public override void UnSubscribeMarketData(Security security, MarketDataTypes type)
			{
				_realConnector.UnSubscribeMarketData(security, type);
			}
		private static Type GetCandleMessageType(MarketDataTypes type)
		{
			switch (type)
			{
				case MarketDataTypes.CandleTimeFrame:
					return typeof(TimeFrameCandleMessage);
				case MarketDataTypes.CandleTick:
					return typeof(TickCandleMessage);
				case MarketDataTypes.CandleVolume:
					return typeof(VolumeCandleMessage);
				case MarketDataTypes.CandleRange:
					return typeof(RangeCandleMessage);
				default:
					throw new ArgumentOutOfRangeException();
			}
		}
		private bool IsSubscribed(MarketDataTypes type, Security security)
		{
			var dic = _subscriptions.TryGetValue(type);

			if (dic == null)
				return false;

			return dic.TryGetValue(security) != 0;
		}
Exemple #36
0
			public override void SubscribeMarketData(Security security, MarketDataTypes type)
			{
				if (_isHistory && type == MarketDataTypes.Trades)
				{
					SendInMessage(new MarketDataMessage
					{
						//SecurityId = GetSecurityId(security),
						DataType = MarketDataTypes.CandleTimeFrame,
						IsSubscribe = true,
						From = _historyMessageAdapter.StartDate,
						To = _historyMessageAdapter.StopDate,
						Arg = _useCandlesTimeFrame
					}.FillSecurityInfo(this, security));
				}

				_realConnector.SubscribeMarketData(security, type);
			}
Exemple #37
0
        private void UnSubscribeMarketData(SecurityId securityId, MarketDataTypes type)
        {
            var message = new MarketDataMessage
            {
                DataType = type,
                SecurityId = securityId,
                IsSubscribe = false,
                TransactionId = _messAdapter.TransactionIdGenerator.GetNextId()
            };

            switch (type)
            {
                case MarketDataTypes.Trades:
                    message.Arg = ExecutionTypes.Tick;
                    break;
                case MarketDataTypes.OrderLog:
                    message.Arg = ExecutionTypes.OrderLog;
                    break;
            }

            _messAdapter.SendInMessage(message);
        }
		private void UnSubscribe(MarketDataTypes type, Security security)
		{
			switch (type)
			{
				case MarketDataTypes.Level1:
				case MarketDataTypes.OrderLog:
					break;

				case MarketDataTypes.Trades:
					SafeGetConnector().UnRegisterTrades(security);
					break;

				case MarketDataTypes.MarketDepth:
					SafeGetConnector().UnRegisterMarketDepth(security);
					break;
			}
		}
		private void RemoveExport(Security security, MarketDataTypes type)
		{
			if (security == null)
				throw new ArgumentNullException(nameof(security));

			if(!IsConnected)
				return;

			if (type != MarketDataTypes.CandleTimeFrame)
				_connector.UnSubscribeMarketData(security, type);
		}
Exemple #40
0
		private void RemoveExport(Security security, MarketDataTypes type)
		{
			if (security == null)
				throw new ArgumentNullException("security");

			_exports.SyncDo(d =>
			{
				var types = d.TryGetValue(security);

				if (types == null)
					return;

				types.Remove(type);
			});

			base.UnSubscribeMarketData(security, type);
		}
		private static void GetCandleParams(MarketDataTypes type, object arg, out string strArg, out string intervalType)
		{
			switch (type)
			{
				case MarketDataTypes.CandleTimeFrame:
				{
					intervalType = "s";
					strArg = arg.To<TimeSpan>().TotalSeconds.To<int>().To<string>();
					break;
				}
				case MarketDataTypes.CandleTick:
				{
					intervalType = "t";
					strArg = arg.To<string>();
					break;
				}
				case MarketDataTypes.CandleVolume:
				{
					intervalType = "v";
					strArg = arg.To<string>();
					break;
				}
				default:
					throw new ArgumentOutOfRangeException("type", type, LocalizedStrings.WrongCandleType);
			}
		}
Exemple #42
0
		public override void SubscribeMarketData(Security security, MarketDataTypes type)
		{
			AddExport(security, type);
		}
Exemple #43
0
		private void AddExport(Security security, MarketDataTypes type)
		{
			if (security == null)
				throw new ArgumentNullException("security");

			_exports.SafeAdd(security).SafeAdd(type);

			if (ConnectionState == ConnectionStates.Connected)
				base.SubscribeMarketData(security, type);
		}
		/// <summary>
		/// Удалить регистрацию, ранее осуществленную через <see cref="RegisterHistorySource"/>.
		/// </summary>
		/// <param name="security">Инструмент.</param>
		/// <param name="dataType">Тип данных.</param>
		/// <param name="arg">Параметр, ассоциированный с типом <paramref name="dataType"/>. Например, <see cref="Candle.Arg"/>.</param>
		public void UnRegisterHistorySource(Security security, MarketDataTypes dataType, object arg)
		{
			SendInHistorySourceMessage(security, dataType, arg, null);
		}
		private void SendInHistorySourceMessage(Security security, MarketDataTypes dataType, object arg, Func<DateTimeOffset, IEnumerable<Message>> getMessages)
		{
			var isSubscribe = getMessages != null;

			if (isSubscribe)
			{
				if (_historySourceSubscriptions.ChangeSubscribers(Tuple.Create(security.ToSecurityId(), dataType, arg), true) != 1)
					return;
			}
			else
			{
				if (_historySourceSubscriptions.ChangeSubscribers(Tuple.Create(security.ToSecurityId(), dataType, arg), false) != 0)
					return;
			}

			SendInMessage(new HistorySourceMessage
			{
				IsSubscribe = isSubscribe,
				SecurityId = security.ToSecurityId(),
				DataType = dataType,
				Arg = arg,
				GetMessages = getMessages
			});
		}
Exemple #46
0
		/// <summary>
		/// Нужно ли обрабатывать маркет-данные.
		/// </summary>
		/// <param name="dataType">Тип маркет-данных.</param>
		/// <param name="securityId">Идентификатор инструмента.</param>
		/// <returns>Нужно ли обрабатывать маркет-данные.</returns>
		public bool NeedProcess(MarketDataTypes dataType, SecurityId securityId)
		{
			return _fixServer.HasSubscriptions(dataType, new SecurityId
			{
				SecurityCode = securityId.SecurityCode,
				BoardCode = GetBoardCode(securityId.BoardCode)
			});
		}
Exemple #47
0
		public override void UnSubscribeMarketData(Security security, MarketDataTypes type)
		{
			RemoveExport(security, type);
		}
		/// <summary>
		/// Отписаться от получения рыночных данных по инструменту.
		/// </summary>
		/// <param name="security">Инструмент, по которому необходимо начать получать новую информацию.</param>
		/// <param name="type">Тип рыночных данных.</param>
		public override void UnSubscribeMarketData(Security security, MarketDataTypes type)
		{
			var tf = MarketEmulator.Settings.UseCandlesTimeFrame;

			if (tf != null)
			{
				var securityId = GetSecurityId(security);
				var key = Tuple.Create(securityId, tf.Value);

				if (_subscribedCandles.ChangeSubscribers(key, -1) != 0)
					return;

				MarketDataAdapter.SendInMessage(new MarketDataMessage
				{
					//SecurityId = securityId,
					DataType = MarketDataTypes.CandleTimeFrame,
					Arg = tf.Value,
					IsSubscribe = false,
				}.FillSecurityInfo(this, security));
			}
			else
				base.UnSubscribeMarketData(security, type);
		}
		private void Subscribe(MarketDataTypes type, Security security)
		{
			switch (type)
			{
				case MarketDataTypes.Level1:
					SafeGetConnector().RegisterSecurity(security);
					break;

				case MarketDataTypes.OrderLog:
					break;

				case MarketDataTypes.Trades:
				{
					security
						.WhenNewTrades(SafeGetConnector())
						.Do(trades => new NewTradesCommand(trades).Process(this))
						.Until(() => !(CanProcess && IsSubscribed(MarketDataTypes.Trades, security)))
						.Apply(this);

					SafeGetConnector().RegisterTrades(security);
					break;
				}

				case MarketDataTypes.MarketDepth:
				{
					security
						.WhenMarketDepthChanged(SafeGetConnector())
						.Do(md => new UpdateMarketDepthCommand(md).Process(this))
						.Until(() => !(CanProcess && IsSubscribed(MarketDataTypes.MarketDepth, security)))
						.Apply(this);

					SafeGetConnector().RegisterMarketDepth(security);
					break;
				}
			}
		}
		public RefuseMarketDataCommand(Security security, MarketDataTypes type)
		{
			Security = security;
			Type = type;
		}
Exemple #51
0
		private void RaiseMarketDataSubscriptionFailed(Security security, MarketDataTypes dataType, Exception error)
		{
			this.AddErrorLog(LocalizedStrings.Str634Params, security.Id, dataType, error);
			MarketDataSubscriptionFailed.SafeInvoke(security, dataType, error);
		}