Ejemplo n.º 1
0
        public static IBSocket SendCombo(this IBSocket socket, WeightedIndexSecurity security, IBOrderCondition condition = null)
        {
            if (security == null)
            {
                throw new ArgumentNullException(nameof(security));
            }

            var innerSecurities = security.InnerSecurities.ToArray();

            socket.Send(innerSecurities.Length);

            foreach (var innerSecurity in innerSecurities)
            {
                var weight = security.Weights[innerSecurity];

                socket
                .SendContractId(innerSecurity.ToSecurityId())
                .Send((int)weight.Abs())
                .SendSide(weight >= 0 ? Sides.Buy : Sides.Sell)
                .SendBoardCode(innerSecurity.Board.Code);

                if (condition == null)
                {
                    continue;
                }

                var shortSale = condition.Combo.ShortSales[innerSecurity.ToSecurityId()];

                socket
                .Send(shortSale.IsOpenOrClose)
                .SendShortSale(shortSale, true);
            }

            return(socket);
        }
Ejemplo n.º 2
0
        public static IBSocket SendFinancialAdvisor(this IBSocket socket, IBOrderCondition.FinancialAdvisorAllocations?allocation)
        {
            if (allocation == null)
            {
                return(socket.Send(string.Empty));
            }

            switch (allocation.Value)
            {
            case IBOrderCondition.FinancialAdvisorAllocations.PercentChange:
                return(socket.Send("PctChange"));

            case IBOrderCondition.FinancialAdvisorAllocations.AvailableEquity:
                return(socket.Send("AvailableEquity"));

            case IBOrderCondition.FinancialAdvisorAllocations.NetLiquidity:
                return(socket.Send("NetLiq"));

            case IBOrderCondition.FinancialAdvisorAllocations.EqualQuantity:
                return(socket.Send("EqualQuantity"));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 3
0
        public static OrderStatus ReadOrderStatus(this IBSocket socket)
        {
            var str = socket.ReadStr();

            switch (str)
            {
            case "PendingSubmit":
                return(OrderStatus.SentToServer);

            case "PendingCancel":
                return(OrderStatus.SentToCanceled);

            case "PreSubmitted":
                return(OrderStatus.ReceiveByServer);

            case "Submitted":
                return(OrderStatus.Accepted);

            case "Cancelled":
                return(OrderStatus.Cancelled);

            case "Filled":
                return(OrderStatus.Matched);

            case "Inactive":
                return(OrderStatus.GateError);

            default:
                throw new InvalidOperationException(LocalizedStrings.Str2503Params.Put(str));
            }
        }
Ejemplo n.º 4
0
        public static IBSocket SendSecurity(this IBSocket socket, SecurityMessage security, bool sendPrimExchange = true, bool sendPrimExchange2 = true)
        {
            if (security == null)
            {
                throw new ArgumentNullException(nameof(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));
        }
Ejemplo n.º 5
0
        public static IBSocket SendSecurityId(this IBSocket socket, SecurityId id)
        {
            if (socket.ServerVersion < ServerVersions.V45)
            {
                return(socket);
            }

            if (!id.Cusip.IsEmpty())
            {
                socket.Send("CUSIP");
                socket.Send(id.Cusip);
            }
            else if (!id.Isin.IsEmpty())
            {
                socket.Send("ISIN");
                socket.Send(id.Isin);
            }
            else if (!id.Sedol.IsEmpty())
            {
                socket.Send("SEDOL");
                socket.Send(id.Sedol);
            }
            else if (!id.Ric.IsEmpty())
            {
                socket.Send("RIC");
                socket.Send(id.Ric);
            }
            else
            {
                socket.Send(string.Empty);
                socket.Send(string.Empty);
            }

            return(socket);
        }
Ejemplo n.º 6
0
        public static IBSocket SendFundamental(this IBSocket socket, FundamentalReports report)
        {
            switch (report)
            {
            case FundamentalReports.Overview:
                return(socket.Send("ReportSnapshot"));

            case FundamentalReports.Statements:
                return(socket.Send("ReportsFinStatements"));

            case FundamentalReports.Summary:
                return(socket.Send("ReportsFinSummary"));

            case FundamentalReports.Ratio:
                return(socket.Send("ReportRatios"));

            case FundamentalReports.Estimates:
                return(socket.Send("RESC"));

            case FundamentalReports.Calendar:
                return(socket.Send("CalendarReport"));

            default:
                throw new ArgumentOutOfRangeException(nameof(report));
            }
        }
Ejemplo n.º 7
0
        public static void ReadSecurityId(this IBSocket socket, SecurityId securityId)
        {
            var count = socket.ReadInt();

            for (var i = 0; i < count; i++)
            {
                var idType = socket.ReadStr();
                switch (idType)
                {
                case "CUSIP":
                    securityId.Cusip = socket.ReadStr();
                    break;

                case "ISIN":
                    securityId.Isin = socket.ReadStr();
                    break;

                case "SEDOL":
                    securityId.Sedol = socket.ReadStr();
                    break;

                case "RIC":
                    securityId.Ric = socket.ReadStr();
                    break;

                default:
                    throw new InvalidOperationException(LocalizedStrings.Str2509Params.Put(idType));
                }
            }
        }
Ejemplo n.º 8
0
        public static void ReadHedge(this IBSocket socket, IBOrderCondition ibCon)
        {
            var str = socket.ReadStr();

            if (str.IsEmpty())
            {
                ibCon.Hedge.Type = null;
                return;
            }

            switch (str)
            {
            case "D":
                ibCon.Hedge.Type = IBOrderCondition.HedgeTypes.Delta;
                break;

            case "B":
                ibCon.Hedge.Type = IBOrderCondition.HedgeTypes.Beta;
                break;

            case "F":
                ibCon.Hedge.Type = IBOrderCondition.HedgeTypes.FX;
                break;

            case "P":
                ibCon.Hedge.Type = IBOrderCondition.HedgeTypes.Pair;
                break;

            default:
                throw new InvalidOperationException(LocalizedStrings.Str2508Params.Put(str));
            }

            ibCon.Hedge.Param = socket.ReadStr();
        }
Ejemplo n.º 9
0
        public static IBSocket SendIncludeExpired(this IBSocket socket, DateTimeOffset?expiryDate)
        {
            if (socket.ServerVersion < ServerVersions.V31)
            {
                return(socket);
            }

            return(socket.Send((expiryDate != null && !(expiryDate < DateTimeOffset.Now))));
        }
Ejemplo n.º 10
0
        public static IBSocket SendEndDate(this IBSocket socket, DateTimeOffset endDate)
        {
            if (socket.ServerVersion < ServerVersions.V20)
            {
                return(socket);
            }

            //yyyymmdd hh:mm:ss tmz
            return(socket.Send(endDate.ToUniversalTime().ToString("yyyyMMdd HH:mm:ss") + " GMT"));
        }
Ejemplo n.º 11
0
        public static SecurityTypes ReadSecurityType(this IBSocket socket)
        {
            var str = socket.ReadStr();

            switch (str)
            {
            case "STK":
            case "SLB":                     // short stock
                return(SecurityTypes.Stock);

            case "FUT":
            case "ICU":
            case "ICS":
                return(SecurityTypes.Future);

            case "FOP":                     // option on fut
            case "OPT":
            case "IOPT":                    // interactive option
                return(SecurityTypes.Option);

            case "IND":
            case "BAG":
            case "BSK":
                return(SecurityTypes.Index);

            case "CASH":
                return(SecurityTypes.Currency);

            case "BOND":
            case "BILL":
            case "FIXED":
                return(SecurityTypes.Bond);

            case "FUND":
                return(SecurityTypes.Fund);

            case "WAR":
                return(SecurityTypes.Warrant);

            case "CFD":
                return(SecurityTypes.Cfd);

            case "FWD":
                return(SecurityTypes.Forward);

            case "NEWS":
                return(SecurityTypes.News);

            case "CMDTY":
                return(SecurityTypes.Commodity);

            default:
                throw new InvalidOperationException(LocalizedStrings.Str2502Params.Put(str));
            }
        }
Ejemplo n.º 12
0
        public static IBSocket SendPortfolio(this IBSocket socket, string portfolioName, bool allowNull = true)
        {
            if (!portfolioName.IsEmpty())
            {
                return(socket.ServerVersion < ServerVersions.V9 ? socket : socket.Send(portfolioName));
            }

            if (allowNull)
            {
                return(socket.Send(string.Empty));
            }

            throw new ArgumentNullException(nameof(portfolioName));
        }
Ejemplo n.º 13
0
        public static IBSocket SendIf(this IBSocket socket, ServerVersions minVersion, Action <IBSocket> handler)
        {
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }

            if (socket.ServerVersion >= minVersion)
            {
                handler(socket);
            }

            return(socket);
        }
Ejemplo n.º 14
0
        public static IBSocket SendPrimaryExchange(this IBSocket socket, SecurityMessage security)
        {
            if (security == null)
            {
                throw new ArgumentNullException(nameof(security));
            }

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

            return(socket.SendBoardCode(security.GetRoutingBoard()));
        }
Ejemplo n.º 15
0
        public static Sides?ReadTradeSide(this IBSocket socket)
        {
            switch (socket.ReadStr())
            {
            case "BOT":
                return(Sides.Buy);

            case "SLD":
                return(Sides.Sell);

            default:
                return(null);
            }
        }
Ejemplo n.º 16
0
        public static IBSocket SendTimeFrame(this IBSocket socket, IBTimeFrames timeFrame)
        {
            if (timeFrame == null)
            {
                throw new ArgumentNullException(nameof(timeFrame));
            }

            if (socket.ServerVersion < ServerVersions.V20)
            {
                return(socket);
            }

            return(socket.Send(timeFrame.Interval));
        }
Ejemplo n.º 17
0
        public static IBSocket SendOrderExpiration(this IBSocket socket, OrderRegisterMessage msg)
        {
            if (msg == null)
            {
                throw new ArgumentNullException(nameof(msg));
            }

            if (msg.OrderType != OrderTypes.Conditional)
            {
                switch (msg.TimeInForce)
                {
                case TimeInForce.PutInQueue:
                case null:
                {
                    if (msg.TillDate == null || msg.TillDate == DateTimeOffset.MaxValue)
                    {
                        return(socket.Send("GTC"));
                    }
                    else if (msg.TillDate.Value.DateTime != DateTime.Today)
                    {
                        return(socket.Send("GTD"));
                    }
                    else
                    {
                        return(socket.Send("DAY"));
                    }
                }

                case TimeInForce.MatchOrCancel:
                    return(socket.Send("FOK"));

                case TimeInForce.CancelBalance:
                    return(socket.Send("IOC"));

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            else if (msg.OrderType == OrderTypes.Conditional)
            {
                var ibCon = (IBOrderCondition)msg.Condition;

                return(socket.Send(ibCon.IsMarketOnOpen ? "OPG" : "DAY"));
            }
            else
            {
                throw new ArgumentException(LocalizedStrings.Str2501Params.Put(msg.Type), nameof(msg));
            }
        }
Ejemplo n.º 18
0
        public static IBSocket SendShortSale(this IBSocket socket, IBOrderCondition.ShortSaleCondition shortSale, bool extendCode = false)
        {
            socket.Send((int)shortSale.Slot);
            socket.Send(shortSale.Location);

            if (extendCode)
            {
                if (socket.ServerVersion >= ServerVersions.V51)
                {
                    socket.Send(shortSale.ExemptCode);
                }
            }

            return(socket);
        }
Ejemplo n.º 19
0
        public static string ReadLocalCode(this IBSocket socket, string secCode)
        {
            if (secCode.IsEmpty())
            {
                throw new ArgumentNullException(nameof(secCode));
            }

            var localCode = socket.ReadStr();

            if (localCode.IsEmpty())
            {
                return(secCode);
            }

            return(localCode);
        }
Ejemplo n.º 20
0
        public static Sides ReadOrderSide(this IBSocket socket)
        {
            var str = socket.ReadStr();

            switch (str)
            {
            case "BUY":
                return(Sides.Buy);

            case "SELL":
                return(Sides.Sell);

            default:
                throw new InvalidOperationException(LocalizedStrings.Str2506Params.Put(str));
            }
        }
Ejemplo n.º 21
0
        public static IBOrderCondition.VolatilityTimeFrames?ReadVolatilityType(this IBSocket socket)
        {
            var str = socket.ReadStr();

            if (str.IsEmpty())
            {
                return(null);
            }

            var value = str.To <int>();

            if (value == 0)
            {
                return(null);
            }

            return((IBOrderCondition.VolatilityTimeFrames)value);
        }
Ejemplo n.º 22
0
        public static IBOrderCondition.ClearingIntents ReadIntent(this IBSocket socket)
        {
            var str = socket.ReadStr();

            switch (str.ToUpperInvariant())
            {
            case "IB":
                return(IBOrderCondition.ClearingIntents.Broker);

            case "AWAY":
                return(IBOrderCondition.ClearingIntents.Away);

            case "PTA":
                return(IBOrderCondition.ClearingIntents.PostTradeAllocation);

            default:
                throw new InvalidOperationException(LocalizedStrings.Str2510Params.Put(str));
            }
        }
Ejemplo n.º 23
0
        public static IBSocket SendSide(this IBSocket socket, Sides?side)
        {
            if (side == null)
            {
                return(socket.Send(string.Empty));
            }

            switch (side.Value)
            {
            case Sides.Buy:
                return(socket.Send("BUY"));

            case Sides.Sell:
                return(socket.Send("SELL"));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 24
0
        public static IBSocket SendHedge(this IBSocket socket, IBOrderCondition condition)
        {
            if (condition == null)
            {
                throw new ArgumentNullException(nameof(condition));
            }

            if (socket.ServerVersion < ServerVersions.V54)
            {
                return(socket);
            }

            if (condition.Hedge.Type == null)
            {
                return(socket.Send(string.Empty));
            }
            else
            {
                switch (condition.Hedge.Type.Value)
                {
                case IBOrderCondition.HedgeTypes.Delta:
                    socket.Send("D");
                    break;

                case IBOrderCondition.HedgeTypes.Beta:
                    socket.Send("B");
                    break;

                case IBOrderCondition.HedgeTypes.FX:
                    socket.Send("F");
                    break;

                case IBOrderCondition.HedgeTypes.Pair:
                    socket.Send("P");
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                return(socket.Send(condition.Hedge.Param));
            }
        }
Ejemplo n.º 25
0
        public static IBOrderCondition.AgentDescriptions?ReadAgent(this IBSocket socket)
        {
            var str = socket.ReadStr();

            if (str.IsEmpty())
            {
                return(null);
            }

            switch (str)
            {
            case "I":
                return(IBOrderCondition.AgentDescriptions.Individual);

            case "A":
                return(IBOrderCondition.AgentDescriptions.Agency);

            case "W":
                return(IBOrderCondition.AgentDescriptions.AgentOtherMember);

            case "J":
                return(IBOrderCondition.AgentDescriptions.IndividualPTIA);

            case "U":
                return(IBOrderCondition.AgentDescriptions.AgencyPTIA);

            case "M":
                return(IBOrderCondition.AgentDescriptions.AgentOtherMemberPTIA);

            case "K":
                return(IBOrderCondition.AgentDescriptions.IndividualPT);

            case "Y":
                return(IBOrderCondition.AgentDescriptions.AgencyPT);

            case "N":
                return(IBOrderCondition.AgentDescriptions.AgentOtherMemberPT);

            default:
                throw new InvalidOperationException(LocalizedStrings.Str2507Params.Put(str));
            }
        }
Ejemplo n.º 26
0
        public static IBSocket SendDeltaNeutral(this IBSocket socket, IBOrderCondition condition)
        {
            if (condition == null)
            {
                throw new ArgumentNullException(nameof(condition));
            }

            var volatility = condition.Volatility;

            if (socket.ServerVersion < ServerVersions.V28)
            {
                return(socket.Send(volatility.OrderType == OrderTypes.Market));
            }
            else
            {
                socket.SendOrderType(volatility.OrderType, volatility.ExtendedOrderType);
                socket.Send(volatility.StopPrice);

                if (volatility.ExtendedOrderType != IBOrderCondition.ExtendedOrderTypes.Empty)
                {
                    if (socket.ServerVersion >= ServerVersions.V58)
                    {
                        socket
                        .Send(volatility.ConId)
                        .Send(volatility.SettlingFirm)
                        .SendPortfolio(volatility.ClearingPortfolio)
                        .Send(volatility.ClearingIntent);
                    }

                    if (socket.ServerVersion >= ServerVersions.V66)
                    {
                        socket
                        .Send(volatility.ShortSale.IsOpenOrClose)
                        .Send(volatility.IsShortSale)
                        .SendShortSale(volatility.ShortSale);
                    }
                }

                return(socket);
            }
        }
Ejemplo n.º 27
0
        public static IBSocket SendLevel1Field(this IBSocket socket, Level1Fields field)
        {
            switch (field)
            {
            case CandleDataTypes.Trades:
                return(socket.Send("TRADES"));

            case CandleDataTypes.Midpoint:
                return(socket.Send("MIDPOINT"));

            case CandleDataTypes.Bid:
                return(socket.Send("BID"));

            case CandleDataTypes.Ask:
                return(socket.Send("ASK"));

            case CandleDataTypes.BidAsk:
                return(socket.Send("BID_ASK"));

            case CandleDataTypes.HistoricalVolatility:
                return(socket.Send("HISTORICAL_VOLATILITY"));

            case CandleDataTypes.ImpliedVolatility:
                return(socket.Send("OPTION_IMPLIED_VOLATILITY"));

            case CandleDataTypes.YieldAsk:
                return(socket.Send("YIELD_ASK"));

            case CandleDataTypes.YieldBid:
                return(socket.Send("YIELD_BID"));

            case CandleDataTypes.YieldBidAsk:
                return(socket.Send("YIELD_BID_ASK"));

            case CandleDataTypes.YieldLast:
                return(socket.Send("YIELD_LAST"));

            default:
                throw new ArgumentOutOfRangeException(nameof(field));
            }
        }
Ejemplo n.º 28
0
        public static IBSocket SendAgent(this IBSocket socket, IBOrderCondition.AgentDescriptions?description)
        {
            if (description == null)
            {
                return(socket.Send(string.Empty));
            }

            switch (description.Value)
            {
            case IBOrderCondition.AgentDescriptions.Individual:
                return(socket.Send("I"));

            case IBOrderCondition.AgentDescriptions.Agency:
                return(socket.Send("A"));

            case IBOrderCondition.AgentDescriptions.AgentOtherMember:
                return(socket.Send("W"));

            case IBOrderCondition.AgentDescriptions.IndividualPTIA:
                return(socket.Send("J"));

            case IBOrderCondition.AgentDescriptions.AgencyPTIA:
                return(socket.Send("U"));

            case IBOrderCondition.AgentDescriptions.AgentOtherMemberPTIA:
                return(socket.Send("M"));

            case IBOrderCondition.AgentDescriptions.IndividualPT:
                return(socket.Send("K"));

            case IBOrderCondition.AgentDescriptions.AgencyPT:
                return(socket.Send("Y"));

            case IBOrderCondition.AgentDescriptions.AgentOtherMemberPT:
                return(socket.Send("N"));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 29
0
        public static IBSocket SendIntent(this IBSocket socket, IBOrderCondition.ClearingIntents?intent)
        {
            if (intent == null)
            {
                return(socket);
            }

            switch (intent.Value)
            {
            case IBOrderCondition.ClearingIntents.Broker:
                return(socket.Send("IB"));

            case IBOrderCondition.ClearingIntents.Away:
                return(socket.Send("Away"));

            case IBOrderCondition.ClearingIntents.PostTradeAllocation:
                return(socket.Send("PTA"));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 30
0
        public static IBSocket SendSecurityType(this IBSocket socket, SecurityTypes?securityType)
        {
            if (securityType == null)
            {
                return(socket.Send(string.Empty));
            }

            switch (securityType)
            {
            case SecurityTypes.Stock:
                return(socket.Send("STK"));

            case SecurityTypes.Future:
                return(socket.Send("FUT"));

            case SecurityTypes.Option:
                return(socket.Send("OPT"));

            case SecurityTypes.Index:
                return(socket.Send("IND"));

            case SecurityTypes.Currency:
                return(socket.Send("CASH"));

            case SecurityTypes.Bond:
                return(socket.Send("BOND"));

            case SecurityTypes.Warrant:
                return(socket.Send("WAR"));

            case SecurityTypes.Forward:
            case SecurityTypes.Swap:
                throw new NotSupportedException(LocalizedStrings.Str2499Params.Put(securityType));

            default:
                throw new ArgumentOutOfRangeException(nameof(securityType));
            }
        }
		private void ReadFundamentalData(IBSocket socket)
		{
			var requestId = socket.ReadInt();
			var data = socket.ReadStr();

			SendOutMessage(new FundamentalReportMessage
			{
				Data = data,
				OriginalTransactionId = requestId,
			});
		}
		private void ReadPortfolio(IBSocket socket, ServerVersions version)
		{
			var name = socket.ReadStr();
			var value = socket.ReadStr();
			var currency = socket.ReadStr();
			var port = version >= ServerVersions.V2 ? socket.ReadStr() : null;

			if (port == null || currency == "BASE")
				return;

			var pfMsg = this.CreatePortfolioChangeMessage(port);

			switch (name)
			{
				case "CashBalance":
					pfMsg.Add(PositionChangeTypes.CurrentValue, value.To<decimal>());
					break;
				case "Currency":
					pfMsg.Add(PositionChangeTypes.Currency, currency.To<CurrencyTypes>());
					break;
				case "RealizedPnL":
					pfMsg.Add(PositionChangeTypes.RealizedPnL, value.To<decimal>());
					break;
				case "UnrealizedPnL":
					pfMsg.Add(PositionChangeTypes.UnrealizedPnL, value.To<decimal>());
					break;
				case "NetLiquidation":
					pfMsg.Add(PositionChangeTypes.CurrentPrice, value.To<decimal>());
					break;
				case "Leverage-S":
					pfMsg.Add(PositionChangeTypes.Leverage, value.To<decimal>());
					break;
				default:
					var info = pfMsg.ExtensionInfo = new Dictionary<object, object>();

					if (currency.IsEmpty())
						info[name] = value;
					else
					{
						info[name] = new Currency
						{
							Type = currency.To<CurrencyTypes>(),
							Value = value.To<decimal>(),
						};
					}

					break;
			}

			SendOutMessage(pfMsg);
		}
		private void ReadAccountSummaryEnd(IBSocket socket)
		{
			var requestId = socket.ReadInt();
			SendOutMessage(new PortfolioLookupResultMessage { OriginalTransactionId = requestId });
		}
		private bool ProcessTransactionResponse(IBSocket socket, ResponseMessages message, ServerVersions version)
		{
			switch (message)
			{
				case ResponseMessages.OrderStatus:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/orderstatus.htm
					ReadOrderStatus(socket, version);
					return true;
				}
				case ResponseMessages.Portfolio:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/updateaccountvalue.htm
					ReadPortfolio(socket, version);
					return true;
				}
				case ResponseMessages.PortfolioPosition:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/updateportfolio.htm
					ReadPortfolioPosition(socket, version);
					return true;
				}
				case ResponseMessages.PortfolioUpdateTime:
				{
					ReadPortfolioUpdateTime(socket);
					return true;
				}
				case ResponseMessages.OpenOrder:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/openorder.htm
					ReadOpenOrder(socket, version);
					return true;
				}
				case ResponseMessages.NextOrderId:
				{
					ReadNextOrderId(socket);
					return true;
				}
				case ResponseMessages.MyTrade:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/execdetails.htm
					ReadMyTrade(socket, version);
					return true;
				}
				case ResponseMessages.ManagedAccounts:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/managedaccounts.htm
					ReadManagedAccounts(socket);
					return true;
				}
				case ResponseMessages.OpenOrderEnd:
				{
					//openOrderEnd(socket);
					return true;
				}
				case ResponseMessages.AccountDownloadEnd:
				{
					ReadPortfolioName(socket);
					return true;
				}
				case ResponseMessages.MyTradeEnd:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/execdetailsend.htm
					ReadMyTradeEnd(socket);
					return true;
				}
				case ResponseMessages.CommissionReport:
				{
					ReadCommissionReport(socket);
					return true;
				}
				case ResponseMessages.Position:
				{
					ReadPosition(socket, version);
					return true;
				}
				case ResponseMessages.PositionEnd:
				{
					ReadPositionEnd(socket);
					return true;
				}
				case ResponseMessages.AccountSummary:
				{
					ReadAccountSummary(socket);
					return true;
				}
				case ResponseMessages.AccountSummaryEnd:
				{
					ReadAccountSummaryEnd(socket);
					return true;
				}
				default:
					return false;
			}
		}
		private void ReadPositionEnd(IBSocket socket)
		{
		}
		private void ReadCommissionReport(IBSocket socket)
		{
			var tradeId = socket.ReadStr();
			var value = socket.ReadDecimal();
			var currency = socket.ReadCurrency();
			var pnl = socket.ReadNullDecimal();
			var yield = socket.ReadNullDecimal();
			var redemptionDate = socket.ReadNullDateTime("yyyyMMdd");

			var secId = _secIdByTradeIds.TryGetValue2(tradeId);

			if (secId == null)
				return;

			// TODO
			//SendOutMessage(new ExecutionMessage
			//{
			//	ExecutionType = ExecutionTypes.Trade,
			//	TradeStringId = tradeId,
			//	Commission = value,
			//	SecurityId = secId.Value,
			//});
		}
		private void ReadMyTrade(IBSocket socket, ServerVersions version)
		{
			/* requestId */
			if (version >= ServerVersions.V7)
				socket.ReadInt();

			// http://www.interactivebrokers.com/en/software/api/apiguide/java/execution.htm

			var transactionId = socket.ReadInt();

			//Handle the 2^31-1 == 0 bug
			if (transactionId == int.MaxValue)
				transactionId = 0;

			//Read Contract Fields
			var contractId = version >= ServerVersions.V5 ? socket.ReadInt() : -1;

			var secName = socket.ReadStr();
			var type = socket.ReadSecurityType();
			var expiryDate = socket.ReadExpiry();
			var strike = socket.ReadDecimal();
			var optionType = socket.ReadOptionType();
			var multiplier = version >= ServerVersions.V9 ? socket.ReadMultiplier() : null;
			var boardCode = socket.ReadBoardCode();
			var currency = socket.ReadCurrency();
			var secCode = socket.ReadLocalCode(secName);
			var secClass = (version >= ServerVersions.V10) ? socket.ReadStr() : null;

			var tradeId = socket.ReadStr();
			var time = socket.ReadDateTime("yyyyMMdd  HH:mm:ss");
			var portfolio = socket.ReadStr();
			/* exchange */
			socket.ReadStr();
			var side = socket.ReadTradeSide();
			var volume = socket.ReadDecimal();
			var price = socket.ReadDecimal();
			var permId = version >= ServerVersions.V2 ? socket.ReadInt() : (int?)null;
			var clientId = version >= ServerVersions.V3 ? socket.ReadInt() : (int?)null;
			var liquidation = version >= ServerVersions.V4 ? socket.ReadInt() : (int?)null;
			var cumulativeQuantity = version >= ServerVersions.V6 ? socket.ReadInt() : (int?)null;
			var averagePrice = version >= ServerVersions.V6 ? socket.ReadDecimal() : (decimal?)null;
			var orderRef = version >= ServerVersions.V8 ? socket.ReadStr() : null;
			var evRule = version >= ServerVersions.V9 ? socket.ReadStr() : null;
			var evMultiplier = version >= ServerVersions.V9 ? socket.ReadDecimal() : (decimal?)null;

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

			SendOutMessage(new SecurityMessage
			{
				SecurityId = secId,
				Name = secName,
				SecurityType = type,
				ExpiryDate = expiryDate,
				Strike = strike,
				OptionType = optionType,
				Currency = currency,
				Multiplier = multiplier ?? 0,
				Class = secClass
			});

			// заявка была создана руками
			if (transactionId == 0)
				return;

			_secIdByTradeIds[tradeId] = secId;

			var execMsg = new ExecutionMessage
			{
				ExecutionType = ExecutionTypes.Transaction,
				OriginalTransactionId = transactionId,
				TradeStringId = tradeId,
				OriginSide = side,
				TradePrice = price,
				TradeVolume = volume,
				PortfolioName = portfolio,
				ServerTime = time,
				SecurityId = secId,
				HasTradeInfo = true,
			};

			if (permId != null)
				execMsg.SetPermId(permId.Value);

			if (clientId != null)
				execMsg.SetClientId(clientId.Value);

			if (liquidation != null)
				execMsg.SetLiquidation(liquidation.Value);

			if (cumulativeQuantity != null)
				execMsg.SetCumulativeQuantity(cumulativeQuantity.Value);

			if (averagePrice != null)
				execMsg.SetAveragePrice(averagePrice.Value);

			if (orderRef != null)
				execMsg.SetOrderRef(orderRef);

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

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

			SendOutMessage(execMsg);
		}
		private void ReadNextOrderId(IBSocket socket)
		{
			((IncrementalIdGenerator)TransactionIdGenerator).Current = socket.ReadInt();
		}
		private void ReadTickOptionComputation(IBSocket socket, ServerVersions version)
		{
			var requestId = socket.ReadInt();
			var fieldType = (FieldTypes)socket.ReadInt();

			decimal? impliedVol = socket.ReadDecimal();
			if (impliedVol < 0)
			{
				// -1 is the "not yet computed" indicator
				impliedVol = null;
			}

			decimal? delta = socket.ReadDecimal();
			if (Math.Abs(delta.Value) > 1)
			{
				// -2 is the "not yet computed" indicator
				delta = null;
			}

			decimal? optPrice = null;
			decimal? pvDividend = null;
			decimal? gamma = null;
			decimal? vega = null;
			decimal? theta = null;
			decimal? undPrice;

			if (version >= ServerVersions.V6 || fieldType == FieldTypes.ModelOption)
			{
				// introduced in version == 5
				optPrice = socket.ReadDecimal();
				if (optPrice < 0)
				{
					// -1 is the "not yet computed" indicator
					optPrice = null;
				}

				pvDividend = socket.ReadDecimal();
				if (pvDividend < 0)
				{
					// -1 is the "not yet computed" indicator
					pvDividend = null;
				}
			}

			if (version >= ServerVersions.V6)
			{
				gamma = socket.ReadDecimal();
				if (Math.Abs(gamma.Value) > 1)
				{
					// -2 is the "not yet computed" indicator
					gamma = null;
				}

				vega = socket.ReadDecimal();
				if (Math.Abs(vega.Value) > 1)
				{
					// -2 is the "not yet computed" indicator
					vega = null;
				}

				theta = socket.ReadDecimal();
				if (Math.Abs(theta.Value) > 1)
				{
					// -2 is the "not yet computed" indicator
					theta = null;
				}

				undPrice = socket.ReadDecimal();
				if (undPrice < 0)
				{
					// -1 is the "not yet computed" indicator
					undPrice = null;
				}
			}

			var l1Msg = GetLevel1Message(requestId)
				.TryAdd(Level1Fields.Delta, delta)
				.TryAdd(Level1Fields.Gamma, gamma)
				.TryAdd(Level1Fields.Vega, vega)
				.TryAdd(Level1Fields.Theta, theta)
				.TryAdd(Level1Fields.ImpliedVolatility, impliedVol)
				.TryAdd(Level1Fields.TheorPrice, optPrice)
				.TryAdd(Level1Fields.Yield, pvDividend);

			SendOutMessage(l1Msg);

			//tickOptionComputation(tickerId, tickType, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta,
			//                      undPrice);
		}
		private void ReadRealTimeBars(IBSocket socket)
		{
			var requestId = socket.ReadInt();
			var time = socket.ReadLongDateTime();
			var open = socket.ReadDecimal();
			var high = socket.ReadDecimal();
			var low = socket.ReadDecimal();
			var close = socket.ReadDecimal();
			var volume = socket.ReadLong();
			var wap = socket.ReadDecimal();
			var count = socket.ReadInt();

			SendOutMessage(new TimeFrameCandleMessage
			{
				OpenPrice = open,
				HighPrice = high,
				LowPrice = low,
				ClosePrice = close,
				TotalVolume = volume,
				OpenTime = time,
				CloseVolume = count,
				SecurityId = GetSecurityId(requestId),
				OriginalTransactionId = requestId,
			});

			//realTimeBar(reqId, time, open, high, low, close, volume, wap, count);
		}
		private void ReadScannerParameters(IBSocket socket)
		{
			var xml = socket.ReadStr();
			SendOutMessage(new ScannerParametersMessage { Parameters = xml });
		}
		private void ReadPortfolioUpdateTime(IBSocket socket)
		{
			/*var timeStamp = */socket.ReadStr();
			//updateAccountTime(timeStamp);
		}
		private void ReadTickGeneric(IBSocket socket)
		{
			var requestId = socket.ReadInt();
			var field = (FieldTypes)socket.ReadInt();
			var valueRenamed = socket.ReadDecimal();

			ProcessTick(requestId, field, valueRenamed, null);

			//tickGeneric(tickerId, (FieldTypes) tickType, valueRenamed);
		}
		private void ReadSecurityInfoEnd(IBSocket socket)
		{
			SendOutMessage(new SecurityLookupResultMessage { OriginalTransactionId = socket.ReadInt() });
		}
		private void ReadManagedAccounts(IBSocket socket)
		{
			var names = socket.ReadStr().Split(',');
			//managedAccounts(accountsList);

			names.ForEach(pf => SendOutMessage(new PortfolioMessage { PortfolioName = pf }));
		}
		private void ReadDeltaNuetralValidation(IBSocket socket)
		{
			/* requestId */
			socket.ReadInt();

			//UnderComp underComp = new UnderComp();
			//underComp.ConId = 
			socket.ReadInt();
			//underComp.Delta = 
			socket.ReadDecimal();
			//underComp.Price = 
			socket.ReadDecimal();

			//deltaNuetralValidation(reqId, underComp);
		}
		private void ReadMyTradeEnd(IBSocket socket)
		{
			/* requestId */
			socket.ReadInt();
			//executionDataEnd(reqId);
		}
		private void ReadTickSnapshotEnd(IBSocket socket)
		{
			/*var requestId = */socket.ReadInt();
			//SendOutMessage(_level1Messages.GetAndRemove(requestId));
		}
		private void ReadPosition(IBSocket socket, ServerVersions version)
		{
			var account = socket.ReadStr();

			var contractId = socket.ReadInt();
			var secName = socket.ReadStr();
			var type = socket.ReadSecurityType();
			var expiryDate = socket.ReadExpiry();
			var strike = socket.ReadDecimal();
			var optionType = socket.ReadOptionType();
			var multiplier = socket.ReadMultiplier();
			var boardCode = socket.ReadBoardCode();
			var currency = socket.ReadCurrency();
			var secCode = socket.ReadLocalCode(secName);
			var secClass = (version >= ServerVersions.V2) ? socket.ReadStr() : null;

			var pos = socket.ReadDecimal();

			var avgCost = 0m;
			if (version >= ServerVersions.V3)
				avgCost = socket.ReadDecimal();

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

			SendOutMessage(new SecurityMessage
			{
				SecurityId = secId,
				Name = secName,
				SecurityType = type,
				ExpiryDate = expiryDate,
				Strike = strike,
				OptionType = optionType,
				Currency = currency,
				Multiplier = multiplier ?? 0,
				Class = secClass
			});

			SendOutMessage(this
				.CreatePositionChangeMessage(account, secId)
					.Add(PositionChangeTypes.CurrentValue, pos)
					.Add(PositionChangeTypes.AveragePrice, avgCost));
		}
		private void ReadMarketDataType(IBSocket socket)
		{
			/* requestId */
			socket.ReadInt();

			IsRealTimeMarketData = socket.ReadBool();

			//marketDataType(reqId, mdt);
		}
		private void ReadAccountSummary(IBSocket socket)
		{
			/* requestId */
			socket.ReadInt();

			var account = socket.ReadStr();
			var tag = socket.ReadStr().To<AccountSummaryTag>();
			var value = socket.ReadStr();
			var currency = socket.ReadCurrency();

			var msg = this.CreatePortfolioChangeMessage(account);

			msg.Add(PositionChangeTypes.Currency, currency);

			switch (tag)
			{
				case AccountSummaryTag.TotalCashValue:
					msg.Add(PositionChangeTypes.CurrentValue, value.To<decimal>());
					break;
				case AccountSummaryTag.SettledCash:
					msg.Add(PositionChangeTypes.BlockedValue, value.To<decimal>());
					break;
				case AccountSummaryTag.AccruedCash:
					msg.Add(PositionChangeTypes.VariationMargin, value.To<decimal>());
					break;
				case AccountSummaryTag.InitMarginReq:
					msg.Add(PositionChangeTypes.BeginValue, value.To<decimal>());
					break;
				case AccountSummaryTag.Leverage:
					msg.Add(PositionChangeTypes.Leverage, value.To<decimal>());
					break;
			}

			SendOutMessage(msg);
		}
		private void ReadFinancialAdvice(IBSocket socket)
		{
			var type = socket.ReadInt();
			var xml = socket.ReadStr();

			SendOutMessage(new FinancialAdviseMessage
			{
				AdviseType = type,
				Data = xml
			});
		}
		private void ReadPortfolioName(IBSocket socket)
		{
			/*var str = */socket.ReadStr();

			//return str.IsEmpty() ? null : str;
		}
		private bool ProcessMarketDataResponse(IBSocket socket, ResponseMessages message, ServerVersions version)
		{
			switch (message)
			{
				case ResponseMessages.TickPrice:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/tickprice.htm
					ReadTickPrice(socket, version);
					return true;
				}
				case ResponseMessages.TickVolume:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/ticksize.htm
					ReadTickVolume(socket);
					return true;
				}
				case ResponseMessages.TickOptionComputation:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/tickoptioncomputation.htm
					ReadTickOptionComputation(socket, version);
					return true;
				}
				case ResponseMessages.TickGeneric:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/tickgeneric.htm
					ReadTickGeneric(socket);
					return true;
				}
				case ResponseMessages.TickString:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/tickstring.htm
					ReadTickString(socket);
					return true;
				}
				case ResponseMessages.TickEfp:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/tickefp.htm
					ReadTickEfp(socket);
					return true;
				}
				case ResponseMessages.ScannerData:
				{
					ReadScannerData(socket, version);
					return true;
				}
				case ResponseMessages.SecurityInfo:
				{
					ReadSecurityInfo(socket, version);
					return true;
				}
				case ResponseMessages.BondInfo:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/bondcontractdetails.htm
					ReadBondInfo(socket, version);
					return true;
				}
				case ResponseMessages.MarketDepth:
				case ResponseMessages.MarketDepthL2:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/updatemktdepth.htm
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/updatemktdepthl2.htm
					ReadMarketDepth(socket, message);
					return true;
				}
				case ResponseMessages.NewsBulletins:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/updatenewsbulletin.htm
					ReadNewsBulletins(socket);
					return true;
				}
				case ResponseMessages.FinancialAdvice:
				{
					ReadFinancialAdvice(socket);
					return true;
				}
				case ResponseMessages.HistoricalData:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/historicaldata.htm
					ReadHistoricalData(socket, version);
					return true;
				}
				case ResponseMessages.ScannerParameters:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/scannerparameters.htm
					ReadScannerParameters(socket);
					return true;
				}
				case ResponseMessages.RealTimeBars:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/realtimebar.htm
					ReadRealTimeBars(socket);
					return true;
				}
				case ResponseMessages.FundamentalData:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/fundamentaldata.htm
					ReadFundamentalData(socket);
					return true;
				}
				case ResponseMessages.SecurityInfoEnd:
				{
					ReadSecurityInfoEnd(socket);
					return true;
				}
				case ResponseMessages.DeltaNuetralValidation:
				{
					ReadDeltaNuetralValidation(socket);
					return true;
				}
				case ResponseMessages.TickSnapshotEnd:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/ticksnapshotend.htm
					ReadTickSnapshotEnd(socket);
					return true;
				}
				case ResponseMessages.MarketDataType:
				{
					// http://www.interactivebrokers.com/en/software/api/apiguide/java/marketdatatype.htm
					ReadMarketDataType(socket);
					return true;
				}
				default:
					return false;
			}
		}
		private void ReadOrderStatus(IBSocket socket, ServerVersions version)
		{
			var id = socket.ReadInt();

			var status = socket.ReadOrderStatus();
			/* filled */
			socket.ReadInt();
			var balance = socket.ReadDecimal();
			var avgPrice = socket.ReadDecimal();
			var permId = version >= ServerVersions.V2 ? socket.ReadInt() : (int?)null;
			var parentId = version >= ServerVersions.V3 ? socket.ReadInt() : (int?)null;
			var lastTradePrice = version >= ServerVersions.V4 ? socket.ReadDecimal() : (decimal?)null;
			var clientId = version >= ServerVersions.V5 ? socket.ReadInt() : (int?)null;
			var whyHeld = version >= ServerVersions.V6 ? socket.ReadStr() : null;

			var execMsg = new ExecutionMessage
			{
				ExecutionType = ExecutionTypes.Transaction,
				OriginalTransactionId = id,
				Balance = balance,
				OrderStatus = status,
				OrderState = status.ToOrderState(),
				HasOrderInfo = true,
			};

			execMsg.SetAveragePrice(avgPrice);

			if (permId != null)
				execMsg.SetPermId(permId.Value);

			if (parentId != null)
				execMsg.Condition = new IBOrderCondition { ParentId = parentId.Value };

			if (lastTradePrice != null)
				execMsg.SetLastTradePrice(lastTradePrice.Value);

			if (clientId != null)
				execMsg.SetClientId(clientId.Value);

			if (whyHeld != null)
				execMsg.SetWhyHeld(whyHeld);

			SendOutMessage(execMsg);
		}
		private void ReadTickPrice(IBSocket socket, ServerVersions version)
		{
			var requestId = socket.ReadInt();
			var priceField = (FieldTypes)socket.ReadInt();
			var price = socket.ReadDecimal();
			var volume = version >= ServerVersions.V2 ? socket.ReadInt() : (decimal?)null;
			var canAutoExecute = version >= ServerVersions.V3 ? socket.ReadBool() : (bool?)null;

			ProcessTick(requestId, priceField, price, volume);
		}
		private void ReadPortfolioPosition(IBSocket socket, ServerVersions version)
		{
			var contractId = version >= ServerVersions.V6 ? socket.ReadInt() : -1;

			var secName = socket.ReadStr();
			var type = socket.ReadSecurityType();
			var expiryDate = socket.ReadExpiry();
			var strike = socket.ReadDecimal();
			var optionType = socket.ReadOptionType();
			var multiplier = version >= ServerVersions.V7 ? socket.ReadMultiplier() : null;
			var boardCode = version >= ServerVersions.V7 ? socket.ReadBoardCode() : null;
			var currency = socket.ReadCurrency();

			var secCode = (version >= ServerVersions.V2) ? socket.ReadStr() : secName;

			var secClass = (version >= ServerVersions.V8) ? socket.ReadStr() : null;

			var position = socket.ReadDecimal();
			var marketPrice = socket.ReadDecimal();
			var marketValue = socket.ReadDecimal();

			var averagePrice = 0m;
			var unrealizedPnL = 0m;
			var realizedPnL = 0m;
			if (version >= ServerVersions.V3)
			{
				averagePrice = socket.ReadDecimal();
				unrealizedPnL = socket.ReadDecimal();
				realizedPnL = socket.ReadDecimal();
			}

			var portfolio = version >= ServerVersions.V4 ? socket.ReadStr() : null;

			if (version == ServerVersions.V6 && socket.ServerVersion == ServerVersions.V39)
				boardCode = socket.ReadBoardCode();

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

			SendOutMessage(new SecurityMessage
			{
				SecurityId = secId,
				Name = secName,
				SecurityType = type,
				ExpiryDate = expiryDate,
				Strike = strike,
				OptionType = optionType,
				Currency = currency,
				Multiplier = multiplier ?? 0,
				Class = secClass
			});

			if (portfolio.IsEmpty())
				return;

			SendOutMessage(
				this
					.CreatePositionChangeMessage(portfolio, secId)
						.Add(PositionChangeTypes.CurrentValue, position)
						.Add(PositionChangeTypes.CurrentPrice, marketPrice)
						.Add(PositionChangeTypes.AveragePrice, averagePrice)
						.Add(PositionChangeTypes.UnrealizedPnL, unrealizedPnL)
						.Add(PositionChangeTypes.RealizedPnL, realizedPnL));

			// TODO
			//pos.SetMarketValue(marketValue);
		}
		private void ReadTickVolume(IBSocket socket)
		{
			var requestId = socket.ReadInt();
			var volumeType = (FieldTypes)socket.ReadInt();
			var volume = socket.ReadInt();

			ProcessTick(requestId, volumeType, 0, volume);
		}
		private void ReadOpenOrder(IBSocket socket, ServerVersions version)
		{
			var transactionId = socket.ReadInt();

			var contractId = version >= ServerVersions.V17 ? socket.ReadInt() : -1;

			var secCode = socket.ReadStr();
			var type = socket.ReadSecurityType();
			var expiryDate = socket.ReadExpiry();
			var strike = socket.ReadDecimal();
			var optionType = socket.ReadOptionType();
			var multiplier = version >= ServerVersions.V32 ? socket.ReadMultiplier() : null;
			var boardCode = socket.ReadBoardCode();
			var currency = socket.ReadCurrency();
			secCode = version >= ServerVersions.V2 ? socket.ReadLocalCode(secCode) : null;
			var secClass = (version >= ServerVersions.V32) ? socket.ReadStr() : null;

			var ibCon = new IBOrderCondition();

			// read order fields
			var direction = socket.ReadOrderSide();
			var volume = socket.ReadDecimal();

			OrderTypes orderType;
			IBOrderCondition.ExtendedOrderTypes? extendedType;
			socket.ReadOrderType(out orderType, out extendedType);
			ibCon.ExtendedType = extendedType;

			var price = socket.ReadDecimal();
			ibCon.StopPrice = socket.ReadDecimal();
			var expiration = socket.ReadStr();
			ibCon.Oca.Group = socket.ReadStr();
			var portfolio = socket.ReadStr();
			ibCon.IsOpenOrClose = socket.ReadStr() == "O";
			ibCon.Origin = (IBOrderCondition.OrderOrigins)socket.ReadInt();
			var comment = socket.ReadStr();

			var clientId = version >= ServerVersions.V3 ? socket.ReadInt() : (int?)null;
			int? permId = null;

			if (version >= ServerVersions.V4)
			{
				permId = socket.ReadInt();

				if (version < ServerVersions.V18)
				{
					// will never happen
					/* order.m_ignoreRth = */
					socket.ReadBool();
				}
				else
					ibCon.OutsideRth = socket.ReadBool();

				ibCon.Hidden = socket.ReadBool();
				ibCon.SmartRouting.DiscretionaryAmount = socket.ReadDecimal();
			}

			if (version >= ServerVersions.V5)
				ibCon.GoodAfterTime = socket.ReadNullDateTime(IBSocketHelper.TimeFormat);

			if (version >= ServerVersions.V6)
			{
				// skip deprecated sharesAllocation field
				socket.ReadStr();
			}

			if (version >= ServerVersions.V7)
			{
				ibCon.FinancialAdvisor.Group = socket.ReadStr();
				ibCon.FinancialAdvisor.Allocation = socket.ReadFinancialAdvisor();
				ibCon.FinancialAdvisor.Percentage = socket.ReadStr();
				ibCon.FinancialAdvisor.Profile = socket.ReadStr();
			}

			var orderExpiryDate = version >= ServerVersions.V8 ? socket.ReadNullDateTime(IBSocketHelper.TimeFormat) : null;
			var visibleVolume = volume;

			if (version >= ServerVersions.V9)
			{
				ibCon.Agent = socket.ReadAgent();
				ibCon.PercentOffset = socket.ReadDecimal();
				ibCon.Clearing.SettlingFirm = socket.ReadStr();
				ibCon.ShortSale.Slot = (IBOrderCondition.ShortSaleSlots)socket.ReadInt();
				ibCon.ShortSale.Location = socket.ReadStr();

				if (socket.ServerVersion == ServerVersions.V51)
					socket.ReadInt(); //exempt code
				else if (version >= ServerVersions.V23)
					ibCon.ShortSale.ExemptCode = socket.ReadInt();

				ibCon.AuctionStrategy = (IBOrderCondition.AuctionStrategies)socket.ReadInt();
				ibCon.StartingPrice = socket.ReadDecimal();
				ibCon.StockRefPrice = socket.ReadDecimal();
				ibCon.Delta = socket.ReadDecimal();
				ibCon.StockRangeLower = socket.ReadDecimal();
				ibCon.StockRangeUpper = socket.ReadDecimal();
				visibleVolume = socket.ReadInt();

				if (version < ServerVersions.V18)
				{
					// will never happen
					/* order.m_rthOnly = */
					socket.ReadBool();
				}

				ibCon.BlockOrder = socket.ReadBool();
				ibCon.SweepToFill = socket.ReadBool();
				ibCon.AllOrNone = socket.ReadBool();
				ibCon.MinVolume = socket.ReadInt();
				ibCon.Oca.Type = (IBOrderCondition.OcaTypes)socket.ReadInt();
				ibCon.SmartRouting.ETradeOnly = socket.ReadBool();
				ibCon.SmartRouting.FirmQuoteOnly = socket.ReadBool();
				ibCon.SmartRouting.NbboPriceCap = socket.ReadDecimal();
			}

			if (version >= ServerVersions.V10)
			{
				ibCon.ParentId = socket.ReadInt();
				ibCon.TriggerMethod = (IBOrderCondition.TriggerMethods)socket.ReadInt();
			}

			if (version >= ServerVersions.V11)
			{
				ibCon.Volatility.Volatility = socket.ReadDecimal();
				ibCon.Volatility.VolatilityTimeFrame = socket.ReadVolatilityType();

				if (version == ServerVersions.V11)
				{
					if (!socket.ReadBool())
						ibCon.Volatility.ExtendedOrderType = IBOrderCondition.ExtendedOrderTypes.Empty;
					else
						ibCon.Volatility.OrderType = OrderTypes.Market;
				}
				else
				{
					OrderTypes volOrdertype;
					IBOrderCondition.ExtendedOrderTypes? volExtendedType;
					socket.ReadOrderType(out volOrdertype, out volExtendedType);
					ibCon.Volatility.OrderType = volOrdertype;
					ibCon.Volatility.ExtendedOrderType = volExtendedType;

					ibCon.Volatility.StopPrice = socket.ReadDecimal();

					if (volExtendedType != IBOrderCondition.ExtendedOrderTypes.Empty)
					{
						if (version >= ServerVersions.V27)
						{
							ibCon.Volatility.ConId = socket.ReadInt();
							ibCon.Volatility.SettlingFirm = socket.ReadStr();

							var portfolioName = socket.ReadStr();
							if (!portfolioName.IsEmpty())
								ibCon.Volatility.ClearingPortfolio = portfolioName;

							ibCon.Volatility.ClearingIntent = socket.ReadStr();
						}

						if (version >= ServerVersions.V31)
						{
							var isOpenOrCloseStr = socket.ReadStr();
							ibCon.Volatility.ShortSale.IsOpenOrClose = isOpenOrCloseStr == "?" ? (bool?)null : isOpenOrCloseStr.To<int>() == 1;
							ibCon.Volatility.IsShortSale = socket.ReadBool();
							ibCon.Volatility.ShortSale.Slot = (IBOrderCondition.ShortSaleSlots)socket.ReadInt();
							ibCon.Volatility.ShortSale.Location = socket.ReadStr();
						}
					}
				}

				ibCon.Volatility.ContinuousUpdate = socket.ReadBool();

				if (socket.ServerVersion == ServerVersions.V26)
				{
					ibCon.StockRangeLower = socket.ReadDecimal();
					ibCon.StockRangeUpper = socket.ReadDecimal();
				}

				ibCon.Volatility.IsAverageBestPrice = socket.ReadBool();
			}

			if (version >= ServerVersions.V13)
				ibCon.TrailStopPrice = socket.ReadDecimal();

			if (version >= ServerVersions.V30)
				ibCon.TrailStopVolumePercentage = socket.ReadNullDecimal();

			if (version >= ServerVersions.V14)
			{
				ibCon.Combo.BasisPoints = socket.ReadDecimal();
				ibCon.Combo.BasisPointsType = socket.ReadInt();
				ibCon.Combo.LegsDescription = socket.ReadStr();
			}

			if (version >= ServerVersions.V29)
			{
				var comboLegsCount = socket.ReadInt();
				if (comboLegsCount > 0)
				{
					//contract.m_comboLegs = new Vector(comboLegsCount);
					for (var i = 0; i < comboLegsCount; ++i)
					{
						//int conId = 
						socket.ReadInt();
						//int ratio = 
						socket.ReadInt();
						//String action = 
						socket.ReadStr();
						//String exchange = 
						socket.ReadStr();
						//int openClose = 
						socket.ReadInt();
						//int shortSaleSlot = 
						socket.ReadInt();
						//String designatedLocation = 
						socket.ReadStr();
						//int exemptCode = 
						socket.ReadInt();

						//ComboLeg comboLeg = new ComboLeg(conId, ratio, action, exchange, openClose,
						//		shortSaleSlot, designatedLocation, exemptCode);
						//contract.m_comboLegs.add(comboLeg);
					}
				}

				var orderComboLegsCount = socket.ReadInt();
				if (orderComboLegsCount > 0)
				{
					//order.m_orderComboLegs = new Vector(orderComboLegsCount);
					for (var i = 0; i < orderComboLegsCount; ++i)
					{
						//var comboPrice = 
						socket.ReadNullDecimal();
						//OrderComboLeg orderComboLeg = new OrderComboLeg(comboPrice);
						//order.m_orderComboLegs.add(orderComboLeg);
					}
				}
			}

			if (version >= ServerVersions.V26)
			{
				var smartComboRoutingParamsCount = socket.ReadInt();
				if (smartComboRoutingParamsCount > 0)
				{
					var @params = new List<Tuple<string, string>>();

					for (var i = 0; i < smartComboRoutingParamsCount; ++i)
						@params.Add(Tuple.Create(socket.ReadStr(), socket.ReadStr()));

					ibCon.SmartRouting.ComboParams = @params;
				}
			}

			if (version >= ServerVersions.V15)
			{
				if (version >= ServerVersions.V20)
				{
					ibCon.Scale.InitLevelSize = socket.ReadNullInt();
					ibCon.Scale.SubsLevelSize = socket.ReadNullInt();
				}
				else
				{
					/* int notSuppScaleNumComponents = */
					socket.ReadNullInt();
					ibCon.Scale.InitLevelSize = socket.ReadNullInt();
				}

				ibCon.Scale.PriceIncrement = socket.ReadNullDecimal();
			}

			if (version >= ServerVersions.V28 && ibCon.Scale.PriceIncrement > 0)
			{
				ibCon.Scale.PriceAdjustValue = socket.ReadNullDecimal();
				ibCon.Scale.PriceAdjustInterval = socket.ReadInt();
				ibCon.Scale.ProfitOffset = socket.ReadNullDecimal();
				ibCon.Scale.AutoReset = socket.ReadBool();
				ibCon.Scale.InitPosition = socket.ReadNullInt();
				ibCon.Scale.InitFillQty = socket.ReadNullInt();
				ibCon.Scale.RandomPercent = socket.ReadBool();
			}

			if (version >= ServerVersions.V24)
				socket.ReadHedge(ibCon);

			if (version >= ServerVersions.V25)
				ibCon.SmartRouting.OptOutSmartRouting = socket.ReadBool();

			if (version >= ServerVersions.V19)
			{
				var portfolioName = socket.ReadStr();

				if (!portfolioName.IsEmpty())
					ibCon.Clearing.ClearingPortfolio = portfolioName;

				ibCon.Clearing.Intent = socket.ReadIntent();
			}

			if (version >= ServerVersions.V22)
				ibCon.SmartRouting.NotHeld = socket.ReadBool();

			if (version >= ServerVersions.V20)
			{
				if (socket.ReadBool())
				{
					//UnderlyingComponent underComp = new UnderlyingComponent();
					//underComp.ContractId = 
					socket.ReadInt();
					//underComp.Delta = 
					socket.ReadDecimal();
					//underComp.Price = 
					socket.ReadDecimal();
					//contract.UnderlyingComponent = underComp;
				}
			}

			if (version >= ServerVersions.V21)
			{
				ibCon.Algo.Strategy = socket.ReadStr();

				if (!ibCon.Algo.Strategy.IsEmpty())
				{
					var algoParamsCount = socket.ReadInt();

					if (algoParamsCount > 0)
					{
						var algoParams = new List<Tuple<string, string>>();

						for (var i = 0; i < algoParamsCount; i++)
							algoParams.Add(Tuple.Create(socket.ReadStr(), socket.ReadStr()));

						ibCon.Algo.Params = algoParams;
					}
				}
			}

			//OrderState orderState = new OrderState();

			OrderStatus? status = null;

			if (version >= ServerVersions.V16)
			{
				socket.ReadStr();
				//order.WhatIf = !(string.IsNullOrEmpty(rstr) || rstr == "0");

				status = socket.ReadOrderStatus();
				//orderState.InitMargin = 
				socket.ReadStr();
				//orderState.MaintMargin = 
				socket.ReadStr();
				//orderState.EquityWithLoan = 
				socket.ReadStr();
				//orderState.IbCommission = 
				socket.ReadNullDecimal();
				//orderState.MinCommission = 
				socket.ReadNullDecimal();
				//orderState.MaxCommission = 
				socket.ReadNullDecimal();
				//orderState.CommissionCurrency = 
				socket.ReadStr();
				//orderState.WarningText = 
				socket.ReadStr();
			}

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

			SendOutMessage(new SecurityMessage
			{
				SecurityId = secId,
				ExpiryDate = expiryDate,
				Strike = strike,
				OptionType = optionType,
				Class = secClass,
				SecurityType = type,
				Currency = currency,
				Multiplier = multiplier ?? 0,
			});

			var orderMsg = new ExecutionMessage
			{
				ExecutionType = ExecutionTypes.Transaction,
				SecurityId = secId,
				OriginalTransactionId = transactionId,
				OrderType = orderType,
				Side = direction,
				OrderVolume = volume,
				OrderPrice = price,
				Condition = ibCon,
				ExpiryDate = orderExpiryDate,
				VisibleVolume = visibleVolume,
				PortfolioName = portfolio,
				Comment = comment,
				OrderStatus = status,
				OrderState = status?.ToOrderState(),
				HasOrderInfo = true,
			};

			if (orderMsg.OrderState == OrderStates.Active || orderMsg.OrderState == OrderStates.Done)
				orderMsg.OrderId = transactionId;

			switch (expiration)
			{
				case "DAY":
					orderMsg.TimeInForce = TimeInForce.PutInQueue;
					break;
				case "GTC":
					//orderMsg.ExpiryDate = DateTimeOffset.MaxValue;
					break;
				case "IOC":
					orderMsg.TimeInForce = TimeInForce.CancelBalance;
					break;
				case "FOK":
					orderMsg.TimeInForce = TimeInForce.MatchOrCancel;
					break;
				case "GTD":
					break;
				case "OPG":
					ibCon.IsMarketOnOpen = true;
					break;
				default:
					throw new InvalidOperationException(LocalizedStrings.Str2515Params.Put(expiration));
			}

			if (clientId != null)
				orderMsg.SetClientId(clientId.Value);

			if (permId != null)
				orderMsg.SetPermId(permId.Value);

			SendOutMessage(orderMsg);
		}
		private void ReadHistoricalData(IBSocket socket, ServerVersions version)
		{
			var requestId = socket.ReadInt();

			if (version >= ServerVersions.V2)
			{
				//Read Start Date String
				/*String startDateStr = */
				socket.ReadStr();
				/*String endDateStr   = */
				socket.ReadStr();
				//completedIndicator += ("-" + startDateStr + "-" + endDateStr);
			}

			var secId = GetSecurityId(requestId);

			var itemCount = socket.ReadInt();
			for (var i = 0; i < itemCount; i++)
			{
				//Comes in as seconds
				//2 - dates are returned as a long integer specifying the number of seconds since 1/1/1970 GMT.
				var time = socket.ReadLongDateTime();

				var open = socket.ReadDecimal();
				var high = socket.ReadDecimal();
				var low = socket.ReadDecimal();
				var close = socket.ReadDecimal();
				var volume = socket.ReadInt();
				var wap = socket.ReadDecimal();
				/* hasGaps */
				socket.ReadStr().To<bool>();

				var barCount = -1;

				if (version >= ServerVersions.V3)
					barCount = socket.ReadInt();

				SendOutMessage(new TimeFrameCandleMessage
				{
					OpenPrice = open,
					HighPrice = high,
					LowPrice = low,
					ClosePrice = close,
					TotalVolume = volume,
					OpenTime = time,
					TotalTicks = barCount,
					SecurityId = secId,
					OriginalTransactionId = requestId,
					State = CandleStates.Finished,
					IsFinished = i == (itemCount - 1)
				});
			}
		}