Example #1
0
		public static IBSocket SendPrimaryExchange(this IBSocket socket, SecurityMessage security)
		{
			if (security == null)
				throw new ArgumentNullException("security");

			if (socket.ServerVersion < ServerVersions.V14)
				return socket;

			return socket.SendBoardCode(security.GetRoutingBoard());
		}
Example #2
0
        /// <summary>
        /// Fill default <see cref="SecurityTypes.CryptoCurrency"/> price and volume step by 0.00000001 value.
        /// </summary>
        /// <param name="message">A message containing info about the security.</param>
        /// <returns>A message containing info about the security.</returns>
        public static SecurityMessage FillDefaultCryptoFields(this SecurityMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            message.PriceStep    = message.VolumeStep = 0.00000001m;
            message.SecurityType = SecurityTypes.CryptoCurrency;

            return(message);
        }
Example #3
0
        /// <summary>
        /// Initialize <see cref="SecurityId.Native"/>.
        /// </summary>
        /// <param name="message">A message containing info about the security.</param>
        /// <param name="nativeId">Native (internal) trading system security id.</param>
        public static void SetNativeId(this SecurityMessage message, object nativeId)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var secId = message.SecurityId;

            secId.Native       = nativeId;
            message.SecurityId = secId;
        }
Example #4
0
        /// <summary>
        /// Initialize <see cref="SecurityId.SecurityCode"/>.
        /// </summary>
        /// <param name="message">A message containing info about the security.</param>
        /// <param name="secCode">Security code.</param>
        public static void SetSecurityCode(this SecurityMessage message, string secCode)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var secId = message.SecurityId;

            secId.SecurityCode = secCode;
            message.SecurityId = secId;
        }
Example #5
0
        /// <summary>
        /// Copy the message into the <paramref name="destination" />.
        /// </summary>
        /// <param name="destination">The object, to which copied information.</param>
        /// <param name="copyOriginalTransactionId">Copy <see cref="OriginalTransactionId"/>.</param>
        public void CopyTo(SecurityMessage destination, bool copyOriginalTransactionId = true)
        {
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }

            destination.SecurityId                  = SecurityId;
            destination.Name                        = Name;
            destination.ShortName                   = ShortName;
            destination.Currency                    = Currency;
            destination.ExpiryDate                  = ExpiryDate;
            destination.OptionType                  = OptionType;
            destination.PriceStep                   = PriceStep;
            destination.Decimals                    = Decimals;
            destination.SecurityType                = SecurityType;
            destination.CfiCode                     = CfiCode;
            destination.SettlementDate              = SettlementDate;
            destination.Strike                      = Strike;
            destination.UnderlyingSecurityCode      = UnderlyingSecurityCode;
            destination.VolumeStep                  = VolumeStep;
            destination.MinVolume                   = MinVolume;
            destination.Multiplier                  = Multiplier;
            destination.Class                       = Class;
            destination.BinaryOptionType            = BinaryOptionType;
            destination.LocalTime                   = LocalTime;
            destination.IssueSize                   = IssueSize;
            destination.IssueDate                   = IssueDate;
            destination.UnderlyingSecurityType      = UnderlyingSecurityType;
            destination.UnderlyingSecurityMinVolume = UnderlyingSecurityMinVolume;
            destination.Shortable                   = Shortable;
            destination.BasketCode                  = BasketCode;
            destination.BasketExpression            = BasketExpression;
            destination.FaceValue                   = FaceValue;

            if (copyOriginalTransactionId)
            {
                destination.OriginalTransactionId = OriginalTransactionId;
            }
        }
		/// <summary>Коллбэк результата поиска инструментов.</summary>
		/// <param name="lookupTransId">Номер транзакции операции Lookup.</param>
		/// <param name="data">Список инструментов, удовлетворяющих условию поиска.</param>
		/// <param name="ex">Ошибка поиска.</param>
		private void ClientOnProductLookupResult(long lookupTransId, IEnumerable<ProductInfo> data, Exception ex)
		{
			if (ex != null)
			{
				SendOutError(new ETradeException(LocalizedStrings.Str3363, ex));

				if (lookupTransId > 0)
					SendOutMessage(new SecurityLookupResultMessage { OriginalTransactionId = lookupTransId });
				
				return;
			}

			foreach(var info in data.Where(info => info.securityType == "EQ"))
			{
				var secId = new SecurityId
				{
					SecurityCode = info.symbol,
					BoardCode = AssociatedBoardCode,
				};

				var msg = new SecurityMessage
				{
					SecurityId = secId,
					Name = info.companyName,
					ShortName = info.companyName,
					SecurityType = SecurityTypes.Stock,
					PriceStep = 0.01m,
					Currency = CurrencyTypes.USD,
				};

				SendOutMessage(msg);
			}

			if (lookupTransId > 0)
				SendOutMessage(new SecurityLookupResultMessage { OriginalTransactionId = lookupTransId });
		}
		private void ReadBondInfo(IBSocket socket, ServerVersions version)
		{
			var requestId = version >= ServerVersions.V3 ? socket.ReadInt() : -1;

			var secCode = socket.ReadStr();
			var type = socket.ReadSecurityType();
			var cusip = socket.ReadStr();
			var coupon = socket.ReadDecimal();
			var maturity = socket.ReadStr();
			var issueDate = socket.ReadStr();
			var ratings = socket.ReadStr();
			var bondType = socket.ReadStr();
			var couponType = socket.ReadStr();
			var convertible = socket.ReadBool();
			var callable = socket.ReadBool();
			var putable = socket.ReadBool();
			var description = socket.ReadStr();
			var boardCode = socket.ReadBoardCode();
			var currency = socket.ReadCurrency();
			var marketName = socket.ReadStr();
			var secClass = socket.ReadStr();
			var contractId = socket.ReadInt();
			var priceStep = socket.ReadDecimal();
			var orderTypes = socket.ReadStr();
			var validExchanges = socket.ReadStr();

			var nextOptionDate = version >= ServerVersions.V2 ? socket.ReadStr() : null;
			var nextOptionType = version >= ServerVersions.V2 ? socket.ReadStr() : null;
			var nextOptionPartial = version >= ServerVersions.V2 ? socket.ReadBool() : (bool?)null;
			var notes = version >= ServerVersions.V2 ? socket.ReadStr() : null;

			var name = version >= ServerVersions.V4 ? socket.ReadStr() : null;
			var evRule = version >= ServerVersions.V6 ? socket.ReadStr() : null;
			var evMultiplier = version >= ServerVersions.V6 ? socket.ReadDecimal() : (decimal?)null;
			
			var secId = new SecurityId
			{
				SecurityCode = secCode,
				BoardCode = GetBoardCode(boardCode),
				InteractiveBrokers = contractId,
			};

			if (version >= ServerVersions.V5)
				socket.ReadSecurityId(secId);

			var secMsg = new SecurityMessage
			{
				SecurityId = secId,
				//Name = secName,
				SecurityType = type,
				Currency = currency,
				Class = secClass,
				PriceStep = priceStep,
			};

			secMsg.SetMarketName(marketName);
			secMsg.SetOrderTypes(orderTypes);
			secMsg.SetValidExchanges(validExchanges);

			// TODO
			//s.SetBondCusip(cusip);
			//s.SetCoupon(coupon);
			//s.SetMaturity(maturity);
			//s.SetIssueDate(issueDate);
			//s.SetRatings(ratings);
			//s.SetBondType(bondType);
			//s.SetCouponType(couponType);
			//s.SetConvertible(convertible);
			//s.SetCallable(callable);
			//s.SetPutable(putable);
			//s.SetDescription(description);

			//if (nextOptionDate != null)
			//	s.SetNextOptionDate(nextOptionDate);

			//if (nextOptionType != null)
			//	s.SetNextOptionType(nextOptionType);

			//if (nextOptionPartial != null)
			//	s.SetNextOptionPartial(nextOptionPartial.Value);

			//if (notes != null)
			//	s.SetNotes(notes);

			if (evRule != null)
				secMsg.SetEvRule(evRule);

			if (evMultiplier != null)
				secMsg.SetEvMultiplier(evMultiplier.Value);

			SendOutMessage(secMsg);
		}
		private void ReadSecurityInfo(IBSocket socket, ServerVersions version)
		{
			var requestId = version >= ServerVersions.V3 ? socket.ReadInt() : -1;

			var secName = socket.ReadStr();
			var type = socket.ReadSecurityType();
			var expiryDate = socket.ReadExpiry();
			var strike = socket.ReadDecimal();
			var optionType = socket.ReadOptionType();
			var boardCode = socket.ReadBoardCode();
			var currency = socket.ReadCurrency();
			var secCode = version >= ServerVersions.V2 ? socket.ReadLocalCode(secName) : null;
			var marketName = socket.ReadStr();
			var secClass = socket.ReadStr();
			var contractId = socket.ReadInt();
			var priceStep = socket.ReadDecimal();
			var multiplier = socket.ReadMultiplier();
			var orderTypes = socket.ReadStr();
			var validExchanges = socket.ReadStr();
			var priceMagnifier = version >= ServerVersions.V2 ? socket.ReadInt() : (int?)null;
			var underlyingSecurityNativeId = version >= ServerVersions.V4 ? socket.ReadInt() : (int?)null;
			var name = version >= ServerVersions.V4 ? socket.ReadStr() : null;
			var routingExchange = version >= ServerVersions.V4 ? socket.ReadBoardCode() : null;
			var contractMonth = version >= ServerVersions.V6 ? socket.ReadStr() : null;
			var industry = version >= ServerVersions.V6 ? socket.ReadStr() : null;
			var category = version >= ServerVersions.V6 ? socket.ReadStr() : null;
			var subCategory = version >= ServerVersions.V6 ? socket.ReadStr() : null;
			var timeZoneId = version >= ServerVersions.V6 ? socket.ReadStr() : null;
			var tradingHours = version >= ServerVersions.V6 ? socket.ReadStr() : null;
			var liquidHours = version >= ServerVersions.V6 ? socket.ReadStr() : null;
			var evRule = version >= ServerVersions.V8 ? socket.ReadStr() : null;
			var evMultiplier = version >= ServerVersions.V8 ? socket.ReadDecimal() : (decimal?)null;

			var secId = new SecurityId
			{
				SecurityCode = secCode,
				BoardCode = GetBoardCode(boardCode),
				InteractiveBrokers = contractId,
			};

			if (version >= ServerVersions.V7)
				socket.ReadSecurityId(secId);

			var secMsg = new SecurityMessage
			{
				SecurityId = secId,
				Name = secName,
				SecurityType = type,
				ExpiryDate = expiryDate,
				Strike = strike,
				OptionType = optionType,
				Currency = currency,
				Multiplier = multiplier ?? 0,
				Class = secClass,
				OriginalTransactionId = requestId,
				PriceStep = priceStep,
			};

			secMsg.SetMarketName(marketName);
			secMsg.SetOrderTypes(orderTypes);
			secMsg.SetValidExchanges(validExchanges);

			if (priceMagnifier != null)
				secMsg.SetPriceMagnifier(priceMagnifier.Value);

			if (!routingExchange.IsEmpty())
				secMsg.SetRoutingBoard(routingExchange);

			if (contractMonth != null)
				secMsg.SetContractMonth(contractMonth);

			if (industry != null)
				secMsg.SetIndustry(industry);

			if (category != null)
				secMsg.SetCategory(category);

			if (subCategory != null)
				secMsg.SetSubCategory(subCategory);

			if (timeZoneId != null)
				secMsg.SetTimeZoneId(timeZoneId);

			if (tradingHours != null)
				secMsg.SetTradingHours(tradingHours);

			if (liquidHours != null)
				secMsg.SetLiquidHours(liquidHours);

			if (evRule != null)
				secMsg.SetEvRule(evRule);

			if (evMultiplier != null)
				secMsg.SetEvMultiplier(evMultiplier.Value);

			// TODO
			//if (underlyingSecurityNativeId != null)
			//	ProcessSecurityAction(null, SecurityIdGenerator.GenerateId(underlyingSecurityNativeId.Value.To<string>(), exchangeBoard), underSec => security.UnderlyingSecurityId = underSec.Id);

			SendOutMessage(secMsg);
		}
		private void OnNewSecurity(int row, int rowCount, string smartId, string name, string secCode, string secClass, int decimals, int lotSize,
			decimal stepPrice, decimal priceStep, string isin, string board, DateTime? expiryDate, decimal daysBeforeExpiry, decimal strike)
		{
			//AMU: заглушка. 11.01.2013 обнаружил, что через SmartCom стали приходить инструменты (класс EQBR и FISS) с пустым secCode - "longName" в понятии АйтиИнвеста
			if (secCode.IsEmpty())
				secCode = smartId;

			var securityId = new SecurityId
			{
				SecurityCode = secCode,
				BoardCode = board,
				Native = smartId,
				Isin = isin
			};

			var secMsg = new SecurityMessage
			{
				PriceStep = priceStep,
				Decimals = decimals,
				Multiplier = lotSize,
				Name = name,
				ShortName = name,
				ExpiryDate = expiryDate == null ? (DateTimeOffset?)null : expiryDate.Value.ApplyTimeZone(TimeHelper.Moscow),
				ExtensionInfo = new Dictionary<object, object>
				{
					{ "Class", secClass }
				},
				OriginalTransactionId = _lookupSecuritiesId
			};

			if (secClass.CompareIgnoreCase("IDX"))
			{
				secMsg.SecurityType = SecurityTypes.Index;

				switch (secMsg.SecurityId.BoardCode)
				{
					case "RUSIDX":
						securityId.BoardCode = secCode.ContainsIgnoreCase("MICEX") || secCode.ContainsIgnoreCase("MCX") ? ExchangeBoard.Micex.Code : ExchangeBoard.Forts.Code;
						break;
					//default:
					//	security.Board = ExchangeBoard.Test;
					//	break;
				}
			}
			else
			{
				var info = SecurityClassInfo.GetSecurityClassInfo(secClass);

				secMsg.SecurityType = info.Item1;
				securityId.BoardCode = info.Item2;

				// http://stocksharp.com/forum/yaf_postsm16847_Vopros-po-vystavlieniiu-zaiavok.aspx#post16847
				if (ExchangeBoard.GetOrCreateBoard(info.Item2).IsMicex
					&&
					/* проверяем, что не началась ли трансляция правильных дробных шагов */
					secMsg.PriceStep != null && secMsg.PriceStep == (int)secMsg.PriceStep)
				{
					// http://stocksharp.com/forum/yaf_postsm21245_Sokhranieniie-stakanov-po-GAZP-EQNE.aspx#post21245
					secMsg.PriceStep = 1m / 10m.Pow(secMsg.PriceStep.Value);
				}
			}

			secMsg.SecurityId = securityId;

			if (secMsg.SecurityType == SecurityTypes.Option)
			{
				var optionInfo = secMsg.Name.GetOptionInfo();

				if (optionInfo != null)
				{
					// http://stocksharp.com/forum/yaf_postst1355_Exception-Change-Set-11052.aspx
					if (!secCode.IsEmpty())
					{
						var futureInfo = optionInfo.UnderlyingSecurityId.GetFutureInfo(secCode);
						if (futureInfo != null)
							secMsg.UnderlyingSecurityCode = futureInfo.SecurityId.SecurityCode;
					}

					secMsg.ExpiryDate = optionInfo.ExpiryDate;
					secMsg.OptionType = optionInfo.OptionType;
					secMsg.Strike = optionInfo.Strike;
				}
			}

			SendOutMessage(secMsg);

			if (stepPrice > 0)
			{
				SendOutMessage(
					new Level1ChangeMessage
					{
						SecurityId = securityId,
						ServerTime = CurrentTime.Convert(TimeHelper.Moscow),
					}
					.Add(Level1Fields.StepPrice, stepPrice));
			}

			if ((row + 1) < rowCount)
				return;

			SendOutMessage(new SecurityLookupResultMessage { OriginalTransactionId = _lookupSecuritiesId });
			_lookupSecuritiesId = 0;
		}
		public void UpdateSecurityDefinition(SecurityMessage securityDefinition)
		{
			if (securityDefinition == null)
				throw new ArgumentNullException(nameof(securityDefinition));

			_securityDefinition = securityDefinition;

			_priceStepUpdated = _securityDefinition.PriceStep != null;
			_volumeStepUpdated = _securityDefinition.VolumeStep != null;
		}
		private void OnProcessSecurities(long transactionId, string[] data)
		{
			var f = Wrapper.FieldsSecurities;
			var secMessages = new List<Tuple<int, SecurityMessage>>();
			var level1Messages = new List<Level1ChangeMessage>();

			foreach (var row in data)
			{
				var cols = row.ToColumns();

				var secType = f.ATCode.GetValue(cols);
				if(secType == null)
					continue;

				var paperNo = f.PaperNo.GetValue(cols);
				var code = f.PaperCode.GetValue(cols);
				var name = f.AnsiName.GetValue(cols);
				var time = f.ILastUpdate.GetValue(cols);

				_securityCodes[paperNo] = code;

				var secId = new SecurityId
				{
					Native = paperNo,
					SecurityCode = code,
					BoardCode = this.GetBoardCode(f.PlaceCode.GetValue(cols))
				};

				var msg = new SecurityMessage
				{
					SecurityId = secId,
					Name = name,
					ShortName = name,
					SecurityType = secType,
					Multiplier = f.LotSize.GetValue(cols),
					PriceStep = f.PriceStep.GetValue(cols),
					//LocalTime = time,
					Currency = f.CurrCode.GetValue(cols),
					Strike = f.Strike.GetValue(cols)
				};

				if(msg.SecurityType == SecurityTypes.Option || msg.SecurityType == SecurityTypes.Future)
					msg.ExpiryDate = f.MatDate.GetValue(cols).ApplyTimeZone(TimeHelper.Moscow);

				if (msg.SecurityType == SecurityTypes.Option)
				{
					msg.OptionType = f.ATCode.GetStrValue(cols).ATCodeToOptionType();
					msg.Strike = f.Strike.GetValue(cols);
				}

				secMessages.Add(Tuple.Create(f.BasePaperNo.GetValue(cols), msg));

				var l1Msg = new Level1ChangeMessage
				{
					SecurityId = secId,
					ServerTime = time.ApplyTimeZone(TimeHelper.Moscow)
				};

				l1Msg.TryAdd(Level1Fields.MarginBuy, f.GoBuy.GetValue(cols));
				l1Msg.TryAdd(Level1Fields.MarginSell, f.GoSell.GetValue(cols));
				l1Msg.TryAdd(Level1Fields.StepPrice, f.PriceStepCost.GetValue(cols));

				level1Messages.Add(l1Msg);
			}

			secMessages.Where(t => t.Item2.SecurityType == SecurityTypes.Option).ForEach(t => 
				t.Item2.UnderlyingSecurityCode = _securityCodes.TryGetValue(t.Item1));

			secMessages.ForEach(t => SendOutMessage(t.Item2));
			level1Messages.ForEach(SendOutMessage);

			if (transactionId > 0)
			{
				SendOutMessage(new SecurityLookupResultMessage
				{
					OriginalTransactionId = transactionId,
				});
			}
		}
Example #12
0
		/// <summary>
		/// Скопировать данные сообщения в <paramref name="destination"/>.
		/// </summary>
		/// <param name="destination">Объект, в который копируется информация.</param>
		public void CopyTo(SecurityMessage destination)
		{
			if (destination == null)
				throw new ArgumentNullException("destination");

			destination.SecurityId = SecurityId;
			destination.Name = Name;
			destination.ShortName = ShortName;
			destination.Currency = Currency;
			destination.ExpiryDate = ExpiryDate;
			destination.OriginalTransactionId = OriginalTransactionId;
			destination.OptionType = OptionType;
			destination.PriceStep = PriceStep;
			destination.Decimals = Decimals;
			destination.SecurityType = SecurityType;
			destination.SettlementDate = SettlementDate;
			destination.Strike = Strike;
			destination.UnderlyingSecurityCode = UnderlyingSecurityCode;
			destination.VolumeStep = VolumeStep;
			destination.Multiplier = Multiplier;
			destination.Class = Class;
			destination.BinaryOptionType = BinaryOptionType;
			destination.LocalTime = LocalTime;
		}
Example #13
0
		/// <summary>
		/// Создать копию объекта <see cref="SecurityMessage"/>.
		/// </summary>
		/// <returns>Копия.</returns>
		public override Message Clone()
		{
			var clone = new SecurityMessage();
			CopyTo(clone);
			return clone;
		}
		public void UpdateSecurityDefinition(SecurityMessage securityDefinition)
		{
			if (securityDefinition == null)
				throw new ArgumentNullException("securityDefinition");

			_securityDefinition = securityDefinition;
			_stepsUpdated = true;
		}
Example #15
0
		public static IBSocket SendSecurity(this IBSocket socket, SecurityMessage security, bool sendPrimExchange = true, bool sendPrimExchange2 = true)
		{
			if (security == null)
				throw new ArgumentNullException("security");

			var multiplier = security.Multiplier;

			socket
				.Send(security.Name)
				.SendSecurityType(security.SecurityType)
				.Send(security.ExpiryDate, _expiryFormat)
				.Send(security.Strike)
				.SendOptionType(security.OptionType)
				.SendIf(ServerVersions.V15, s => s.Send(multiplier == 1 ? string.Empty : multiplier.To<string>()))
				.SendBoardCode(security.SecurityId.BoardCode);

			if (sendPrimExchange2)
			{
				socket.Send(security.SecurityId.BoardCode);
				socket.Send(security.GetRoutingBoard());	
			}
			else if (sendPrimExchange)
				socket.SendPrimaryExchange(security);

			return socket
				.SendCurrency(security.Currency)
				.SendSecurityCode(security.SecurityId.SecurityCode);
		}