Exemple #1
0
 public TWSClientErrorEventArgs(TWSClient client, int tickerId, IBContract contract, TWSError error)
     : base(client)
 {
     RequestId = tickerId;
     Error = error;
     Contract = contract;
 }
Exemple #2
0
        private void RegisterContractList(IList <IBSimplefiedContract> list, Grid grid)
        {
            var i = 1;

            foreach (var c in list)
            {
                var contract = new IBContract
                {
                    Currency     = c.Currency,
                    Symbol       = c.Symbol,
                    Exchange     = c.Exchange,
                    SecurityType = c.SecurityType,
                    Expiry       = c.Expiry,
                    Multiplier   = c.Multiplier.ToString(),
                    Strike       = c.Strike,
                    Right        = c.PutOrCall
                };

                _client.RequestMarketData(contract, null);
                _symbolDataMap.Add(contract, new InstrumentDataRecord()
                {
                    Grid = grid, Row = i
                });
                i++;
            }
        }
Exemple #3
0
 public TWSExecDetailsEventArgs(TWSClient client, int orderId, IBContract contract, IBExecution execution)
     : base(client)
 {
     OrderId   = orderId;
     Contract  = contract;
     Execution = execution;
 }
Exemple #4
0
        private void ProcessMarketDepthRequest()
        {
            try {
                var reqVersion = _enc.DecodeInt();
                var reqId      = _enc.DecodeInt();
                int numRows    = 0;

                var contract = new IBContract();

                contract.Symbol  = _enc.DecodeString();
                contract.SecType = _enc.DecodeSecType();
                contract.Expiry  = _enc.DecodeExpiryDate();
                contract.Strike  = _enc.DecodeDouble();
                contract.Right   = _enc.DecodeString();
                if (ServerInfo.Version >= 15)
                {
                    contract.Multiplier = _enc.DecodeInt();
                }
                contract.Exchange    = _enc.DecodeString();
                contract.Currency    = _enc.DecodeString();
                contract.LocalSymbol = _enc.DecodeString();
                if (ServerInfo.Version >= 19)
                {
                    numRows = _enc.DecodeInt();
                }
                OnMarketDepthRequest(reqId, contract, numRows);
            }
            catch (Exception e) {
                OnError(TWSErrors.FAIL_SEND_REQMKTDEPTH);
                OnError(e.Message);
                Disconnect();
            }
        }
Exemple #5
0
 public TWSOpenOrderEventArgs(TWSClient client, int orderId, IBOrder order, IBContract contract)
     : base(client)
 {
     OrderId  = orderId;
     Order    = order;
     Contract = contract;
 }
Exemple #6
0
        private void ProcessContractDataRequest()
        {
            try {
                // send req mkt data msg
                var reqVersion = _enc.DecodeInt();

                var contract = new IBContract();

                contract.Symbol  = _enc.DecodeString();
                contract.SecType = _enc.DecodeSecType();
                contract.Expiry  = _enc.DecodeExpiryDate();
                contract.Strike  = _enc.DecodeDouble();
                contract.Right   = _enc.DecodeString();
                if (ServerInfo.Version >= 15)
                {
                    contract.Multiplier = _enc.DecodeInt();
                }
                contract.Exchange    = _enc.DecodeString();
                contract.Currency    = _enc.DecodeString();
                contract.LocalSymbol = _enc.DecodeString();
                if (ServerInfo.Version >= 31)
                {
                    contract.IncludeExpired = _enc.DecodeBool();
                }
                OnContractDataRequest(contract);
            }
            catch (Exception e) {
                OnError(TWSErrors.FAIL_SEND_REQCONTRACT);
                OnError(e.Message);
                Disconnect();
            }
        }
Exemple #7
0
 private void OnContractDataRequest(IBContract contract)
 {
     if (Server != null)
     {
         Server.OnContractDetailsRequest(this, contract);
     }
 }
Exemple #8
0
 internal OrderRecord(IBOrder order, IBContract contract)
 {
     Order     = order;
     Contract  = contract;
     CumQty    = 0;
     LeavesQty = order.TotalQuantity;
     AvgPx     = 0;
 }
        void OnMarketDataRequest(int reqId, IBContract contract)
        {
            Server?.OnMarketDataRequest(this, reqId, contract);

            MarketDataRequest?.Invoke(this, new TWSMarketDataRequestEventArgs(this, reqId, contract));

            _marketDataSubscriptions.Add(reqId, contract);
        }
Exemple #10
0
 internal OrderRecord(IBOrder order, IBContract contract)
 {
     Order = order;
     Contract = contract;
     CumQty = 0;
     LeavesQty = order.TotalQuantity;
     AvgPx = 0;
 }
Exemple #11
0
        private void OnMarketDepthRequest(int reqId, IBContract contract, int numRows)
        {
            if (Server != null)
            {
                Server.OnMarketDepthRequest(this, reqId, contract, numRows);
            }

            if (MarketDepthRequest != null)
            {
                MarketDepthRequest(this, new TWSMarketDepthRequestEventArgs(this, reqId, contract, numRows));
            }
        }
        void OnMarketDataCancel(int reqId)
        {
            IBContract contract = null;

            if (_marketDataSubscriptions.TryGetValue(reqId, out contract))
            {
                _marketDataSubscriptions.Remove(reqId);
            }

            Server?.OnMarketDataCancel(this, reqId, contract);

            MarketDataCancel?.Invoke(this, new TWSMarketDataCancelEventArgs(this, reqId, contract));
        }
Exemple #13
0
 public TWSUpdatePortfolioEventArgs(TWSClient client, IBContract contract, int position,
                                    double marketPrice, double marketValue, double averageCost,
                                    double unrealizedPNL, double realizedPNL, string accountName)
     : base(client)
 {
     Contract      = contract;
     Position      = position;
     MarketPrice   = marketPrice;
     MarketValue   = marketValue;
     AverageCost   = averageCost;
     UnrealizedPnL = unrealizedPNL;
     RealizedPnL   = realizedPNL;
     AccountName   = accountName;
 }
Exemple #14
0
        private void OnMarketDataRequest(int reqId, IBContract contract)
        {
            if (Server != null)
            {
                Server.OnMarketDataRequest(this, reqId, contract);
            }

            if (MarketDataRequest != null)
            {
                MarketDataRequest(this, new TWSMarketDataRequestEventArgs(this, reqId, contract));
            }

            _marketDataSubscriptions.Add(reqId, contract);
        }
Exemple #15
0
        private void OnMarketDataCancel(int reqId)
        {
            IBContract contract = null;

            if (_marketDataSubscriptions.TryGetValue(reqId, out contract))
            {
                _marketDataSubscriptions.Remove(reqId);
            }

            if (Server != null)
            {
                Server.OnMarketDataCancel(this, reqId, contract);
            }

            if (MarketDataCancel != null)
            {
                MarketDataCancel(this, new TWSMarketDataCancelEventArgs(this, reqId, contract));
            }
        }
Exemple #16
0
 public virtual void OnContractDetailsRequest(TWSServerClientHandler client, IBContract contract) {}
Exemple #17
0
 public TWSMarketDepthRequestEventArgs(TWSServerClientState clientState, int reqId, IBContract contract, int numRows)
     : base(clientState, reqId, contract)
 {
     numRows = numRows;
 }
 public TWSMarketDataSnapshot(IBContract contract, int reqId)
 {
     Contract  = contract;
     RequestId = reqId;
 }
Exemple #19
0
 public virtual void OnMarketDataRequest(TWSServerClientHandler client, int reqId, IBContract contract)
 {
   if (MarketDataRequest != null)
     MarketDataRequest(this, new TWSMarketDataRequestEventArgs(client, reqId, contract));
 }
Exemple #20
0
    protected void OnOpenOrder(int orderId, IBOrder order, IBContract contract, IBOrderState orderState)
    {
      if (OpenOrder != null)
        OpenOrder(this, new TWSOpenOrderEventArgs(this) {
          OrderId = orderId,
          Order = order,
          Contract = contract
        });

      if (OrderChanged != null) {
        OrderRecord or;
        if (_orderRecords.TryGetValue(orderId, out or))
        {
          OrderChanged(this, new TWSOrderChangedEventArgs(this, or) {
            ChangeType = IBOrderChangeType.OpenOrder,
            ReportedContract = contract,
            OpenOrder = order,
            OpenOrderState = orderState
          });
        }
      }
    }
Exemple #21
0
    protected void OnExecutionDetails(int orderId, IBContract contract, IBExecutionDetails execution)
    {
      if (ExecutionDetails != null)
        ExecutionDetails(this, new TWSExecutionDetailsEventArgs(this) {
          OrderId = orderId,
          Contract = contract,
          Execution = execution
        });

      if (OrderChanged != null) {
        OrderRecord or;
        if (_orderRecords.TryGetValue(orderId, out or)) {
          OrderChanged(this, new TWSOrderChangedEventArgs(this, or) {
            ChangeType = IBOrderChangeType.ExecutionDetails,
            ReportedContract = contract,
            ExecutionDetails =  execution,
          });
        }
      }
    }
Exemple #22
0
    private void ProcessExecutionData()
    {
      var version = _enc.DecodeInt();
      var reqId = -1;
      if (version >= 7)
        reqId = _enc.DecodeInt();

      var orderId = _enc.DecodeInt();
      var contract = new IBContract
        {
          ContractId = version >= 5 ? _enc.DecodeInt() : 0,
          Symbol = _enc.DecodeString(),
          SecurityType = _enc.DecodeEnum<IBSecurityType>(),
          Expiry = DecodeIBExpiry(_enc),
          Strike = _enc.DecodeDouble(),
          Right = _enc.DecodeString()
        };
      if (version >= 9)
        contract.Multiplier = _enc.DecodeString();

      contract.Exchange = _enc.DecodeString();
      contract.Currency = _enc.DecodeString();
      contract.LocalSymbol = _enc.DecodeString();
      var execution = new IBExecutionDetails {
          OrderId = orderId,
          ExecId = _enc.DecodeString(),
          Time = _enc.DecodeString(),
          AcctNumber = _enc.DecodeString(),
          Exchange = _enc.DecodeString(),
          Side = _enc.DecodeEnum<IBExecutionSide>(),
          Shares = _enc.DecodeInt(),
          Price = _enc.DecodeDouble(),
          PermId = version >= 2 ? _enc.DecodeInt() : 0,
          ClientId = version >= 3 ? _enc.DecodeInt() : 0,
          Liquidation = version >= 4 ? _enc.DecodeInt() : 0,
          CumQty = version >= 6 ? _enc.DecodeInt() : 0,
          AveragePrice = version >= 6 ? _enc.DecodeDouble() : 0,
          OrderRef = version >= 8 ? _enc.DecodeString() : null,
          EvRule = version >= 9 ? _enc.DecodeString() : null,
          EvMultiplier = version >= 9 ? _enc.DecodeDouble() : 0
        };

      OnExecutionDetails(reqId, contract, execution);
    }
Exemple #23
0
 public virtual void OnMarketDataRequest(TWSServerClientHandler client, int reqId, IBContract contract)
 {
     MarketDataRequest?.Invoke(this, new TWSMarketDataRequestEventArgs(client, reqId, contract));
 }
Exemple #24
0
 public virtual void OnContractDetailsRequest(TWSServerClientState client, IBContract contract)
 {
 }
Exemple #25
0
 public virtual void OnMarketDepthRequest(TWSServerClientState clientState, int reqId, IBContract contract, int numRows)
 {
     if (MarketDepthRequest != null)
     {
         MarketDepthRequest(this, new TWSMarketDepthRequestEventArgs(clientState, reqId, contract, numRows));
     }
 }
Exemple #26
0
 public virtual void OnMarketDepthCancel(TWSServerClientState client, int reqId, IBContract contract)
 {
     if (MarketDataCancel != null)
     {
         MarketDataCancel(this, new TWSMarketDataCancelEventArgs(client, reqId, contract));
     }
 }
Exemple #27
0
 public virtual void OnMarketDataRequest(TWSServerClientState client, int reqId, IBContract contract)
 {
     if (MarketDataRequest != null)
     {
         MarketDataRequest(this, new TWSMarketDataRequestEventArgs(client, reqId, contract));
     }
 }
        void OnMarketDepthRequest(int reqId, IBContract contract, int numRows)
        {
            Server?.OnMarketDepthRequest(this, reqId, contract, numRows);

            MarketDepthRequest?.Invoke(this, new TWSMarketDepthRequestEventArgs(this, reqId, contract, numRows));
        }
Exemple #29
0
 public TWSClientErrorEventArgs(TWSClient client, int tickerId, IBContract contract, TWSError error) : base(client)
 {
     RequestId = tickerId;
     Error     = error;
     Contract  = contract;
 }
Exemple #30
0
    /// <summary>
    /// Places an order for the requested contract through TWS
    /// </summary>
    /// <param name="contract">The contract.</param>
    /// <param name="order">The order.</param>
    /// <returns>the order id of the newly generated order</returns>
    /// <exception cref="Daemaged.IBNet.Client.NotConnectedException"></exception>
    public virtual int PlaceOrder(IBContract contract, IBOrder order)
    {
      lock (_socketLock) {
        if (!IsConnected)
          throw new NotConnectedException();

        CheckServerCompatability(contract, order);

        var orderId = NextValidId;

        var reqVersion = ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_NOT_HELD ? 27 : 39;

        try {
          _enc.Encode(ServerMessage.PlaceOrder);
          _enc.Encode(reqVersion);
          _enc.Encode(orderId);
          // send contract fields
          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_PLACE_ORDER_CONID)
            _enc.Encode(contract.ContractId);

          _enc.Encode(contract.Symbol);
          _enc.Encode(contract.SecurityType);
          _enc.Encode(contract.Expiry.HasValue ? contract.Expiry.Value.ToString(IB_EXPIRY_DATE_FORMAT) : String.Empty);
          _enc.Encode(contract.Strike);
          _enc.Encode(contract.Right);
          if (ServerInfo.Version >= 15)
            _enc.Encode(contract.Multiplier);
          _enc.Encode(contract.Exchange);
          if (ServerInfo.Version >= 14)
            _enc.Encode(contract.PrimaryExchange);
          _enc.Encode(contract.Currency);
          if (ServerInfo.Version >= 2)
            _enc.Encode(contract.LocalSymbol);
          if (ServerInfo.Version > TWSServerInfo.MIN_SERVER_VER_SEC_ID_TYPE) {
            _enc.Encode(contract.SecurityIdType);
            _enc.Encode(contract.SecurityId);
          }

          _enc.Encode(order.Action);
          _enc.Encode(order.TotalQuantity);
          _enc.Encode(order.OrderType);

          if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_ORDER_COMBO_LEGS_PRICE)
            _enc.Encode(order.LimitPrice == Double.MaxValue ? 0 : order.LimitPrice);
          else
            _enc.EncodeMax(order.LimitPrice);

          if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_TRAILING_PERCENT)
            _enc.Encode(order.AuxPrice == Double.MaxValue ? 0 : order.AuxPrice);
          else
            _enc.EncodeMax(order.AuxPrice);

          _enc.Encode(order.Tif);
          _enc.Encode(order.OcaGroup);
          _enc.Encode(order.Account);
          _enc.Encode(order.OpenClose);
          _enc.Encode(order.Origin);
          _enc.Encode(order.OrderRef);
          _enc.Encode(order.Transmit);
          if (ServerInfo.Version >= 4)
            _enc.Encode(order.ParentId);
          if (ServerInfo.Version >= 5) {
            _enc.Encode(order.BlockOrder);
            _enc.Encode(order.SweepToFill);
            _enc.Encode(order.DisplaySize);
            _enc.Encode(order.TriggerMethod);
            if (ServerInfo.Version < 38)
              _enc.Encode(false); // Deprecated order.IgnoreRth
            else
              _enc.Encode(order.OutsideRth);
          }
          if (ServerInfo.Version >= 7)
            _enc.Encode(order.Hidden);

          if ((ServerInfo.Version >= 8) && (contract.SecurityType == IBSecurityType.Bag)) {
            _enc.Encode(contract.ComboLegs.Count);
            foreach (var leg in contract.ComboLegs) {
              _enc.Encode(leg.ContractId);
              _enc.Encode(leg.Ratio);
              _enc.Encode(leg.Action);
              _enc.Encode(leg.Exchange);
              _enc.Encode(leg.OpenClose);

              if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_SSHORT_COMBO_LEGS) {
                _enc.Encode(leg.ShortSaleSlot);
                _enc.Encode(leg.DesignatedLocation);
              }
              if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_SSHORTX_OLD)
                _enc.Encode(leg.ExemptCode);
            }
          }

          // Send order combo legs for BAG requests
          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_ORDER_COMBO_LEGS_PRICE && contract.SecurityType == IBSecurityType.Bag) {
            if (order.OrderComboLegs == null)
              _enc.Encode(0);
            else {
              _enc.Encode(order.OrderComboLegs.Count);
              foreach (var l in order.OrderComboLegs)
                _enc.EncodeMax(l.Price);
            }
          }

          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_SMART_COMBO_ROUTING_PARAMS && contract.SecurityType == IBSecurityType.Bag) {
            if (order.SmartComboRoutingParams == null || order.SmartComboRoutingParams.Count == 0)
              _enc.Encode(0);
            else {
              _enc.Encode(order.SmartComboRoutingParams.Count);
              foreach (var tv in order.SmartComboRoutingParams) {
                _enc.Encode(tv.Tag);
                _enc.Encode(tv.Value);
              }
            }
          }

          if (ServerInfo.Version >= 9)
            _enc.Encode(String.Empty); // Deprecated order.SharesAllocation
          if (ServerInfo.Version >= 10)
            _enc.Encode(order.DiscretionaryAmt);
          if (ServerInfo.Version >= 11)
            _enc.Encode(order.GoodAfterTime);
          if (ServerInfo.Version >= 12)
            _enc.Encode(order.GoodTillDate);
          if (ServerInfo.Version >= 13) {
            _enc.Encode(order.FaGroup);
            _enc.Encode(order.FaMethod);
            _enc.Encode(order.FaPercentage);
            _enc.Encode(order.FaProfile);
          }
          if (ServerInfo.Version >= 18) {
            _enc.Encode(order.ShortSaleSlot);
            _enc.Encode(order.DesignatedLocation);
          }

          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_SSHORTX_OLD)
            _enc.Encode(order.ExemptCode);

          if (ServerInfo.Version >= 19) {
            _enc.Encode(order.OcaType);
            if (ServerInfo.Version < 38)
              _enc.Encode(false); // Deprecated order.m_rthOnly

            _enc.Encode(order.Rule80A);
            _enc.Encode(order.SettlingFirm);
            _enc.Encode(order.AllOrNone);
            _enc.EncodeMax(order.MinQty);
            _enc.EncodeMax(order.PercentOffset);
            _enc.Encode(order.ETradeOnly);
            _enc.Encode(order.FirmQuoteOnly);
            _enc.EncodeMax(order.NbboPriceCap);
            _enc.EncodeMax(order.AuctionStrategy);
            _enc.EncodeMax(order.StartingPrice);
            _enc.EncodeMax(order.StockRefPrice);
            _enc.EncodeMax(order.Delta);
            var stockRangeLower = ((ServerInfo.Version == 26) && (order.OrderType == IBOrderType.Volatility))
                                       ? Double.MaxValue
                                       : order.StockRangeLower;
            var stockRangeUpper = ((ServerInfo.Version == 26) && (order.OrderType == IBOrderType.Volatility))
                                       ? Double.MaxValue
                                       : order.StockRangeUpper;
            _enc.EncodeMax(stockRangeLower);
            _enc.EncodeMax(stockRangeUpper);
            if (ServerInfo.Version >= 22) {
              _enc.Encode(order.OverridePercentageConstraints);
            }
            if (ServerInfo.Version >= 26) {
              _enc.EncodeMax(order.Volatility);
              _enc.Encode(order.VolatilityType);
              if (ServerInfo.Version < 28) {
                _enc.Encode(order.DeltaNeutralOrderType == IBOrderType.Market);
              }
              else {
                _enc.Encode(order.DeltaNeutralOrderType);
                _enc.EncodeMax(order.DeltaNeutralAuxPrice);

                if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_DELTA_NEUTRAL_CONID && order.DeltaNeutralOrderType != IBOrderType.Empty) {
                  _enc.Encode(order.DeltaNeutralContractId);
                  _enc.Encode(order.DeltaNeutralSettlingFirm);
                  _enc.Encode(order.DeltaNeutralClearingAccount);
                  _enc.Encode(order.DeltaNeutralClearingIntent);
                }

                if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_DELTA_NEUTRAL_OPEN_CLOSE && order.DeltaNeutralOrderType != IBOrderType.Empty) {
                  _enc.Encode(order.DeltaNeutralOpenClose);
                  _enc.Encode(order.DeltaNeutralShortSale);
                  _enc.Encode(order.DeltaNeutralShortSaleSlot);
                  _enc.Encode(order.DeltaNeutralDesignatedLocation);
                }
              }
              _enc.Encode(order.ContinuousUpdate);
              if (ServerInfo.Version == 26) {
                if (order.OrderType == IBOrderType.Volatility) {
                  _enc.EncodeMax(order.StockRangeLower);
                  _enc.EncodeMax(order.StockRangeUpper);
                }
                else {
                  _enc.EncodeMax(Double.MaxValue);
                  _enc.EncodeMax(Double.MaxValue);
                }
              }
              _enc.EncodeMax(order.ReferencePriceType);
            }
          }

          if (ServerInfo.Version >= 30) { // TRAIL_STOP_LIMIT stop price
              _enc.EncodeMax( order.TrailStopPrice);
          }

          if( ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_TRAILING_PERCENT){
              _enc.EncodeMax( order.TrailingPercent);
          }

          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_SCALE_ORDERS) {
        	  if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_SCALE_ORDERS2) {
        	   _enc.EncodeMax(order.ScaleInitLevelSize);
        	   _enc.EncodeMax(order.ScaleSubsLevelSize);
        	  }
        	  else {
        	   _enc.Encode("");
        	   _enc.EncodeMax(order.ScaleInitLevelSize);
        	  }
        	  _enc.EncodeMax(order.ScalePriceIncrement);
          }

          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_SCALE_ORDERS3 && order.ScalePriceIncrement > 0.0 && order.ScalePriceIncrement != Double.MaxValue) {
              _enc.EncodeMax(order.ScalePriceAdjustValue);
              _enc.EncodeMax(order.ScalePriceAdjustInterval);
              _enc.EncodeMax(order.ScaleProfitOffset);
              _enc.Encode(order.ScaleAutoReset);
              _enc.EncodeMax(order.ScaleInitPosition);
              _enc.EncodeMax(order.ScaleInitFillQty);
              _enc.Encode(order.ScaleRandomPercent);
          }

          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_HEDGE_ORDERS) {
        	  _enc.Encode(order.HedgeType);
        	  if (!String.IsNullOrEmpty(order.HedgeType)) {
        	   _enc.Encode(order.HedgeParam);
        	  }
          }

          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_OPT_OUT_SMART_ROUTING) {
              _enc.Encode(order.OptOutSmartRouting);
          }

          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_PTA_ORDERS) {
        	  _enc.Encode(order.ClearingAccount);
        	  _enc.Encode(order.ClearingIntent);
          }

          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_NOT_HELD)
        	  _enc.Encode(order.NotHeld);

          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_UNDER_COMP) {
        	  if (contract.UnderlyingComponent != null) {
        	   var uc = contract.UnderlyingComponent;
        	   _enc.Encode( true);
        	   _enc.Encode(uc.ContractId);
        	   _enc.Encode(uc.Delta);
        	   _enc.Encode(uc.Price);
        	  }
        	  else {
        	   _enc.Encode(false);
        	  }
          }

          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_ALGO_ORDERS) {
        	  _enc.Encode( order.AlgoStrategy ?? String.Empty);
        	  if (!String.IsNullOrEmpty(order.AlgoStrategy)) {
        	   if (order.AlgoParams == null || order.AlgoParams.Count == 0)
               _enc.Encode(0);
             else {
        	     _enc.Encode(order.AlgoParams.Count);
        		   foreach (var tv in order.AlgoParams) {
                 _enc.Encode(tv.Tag);
        			   _enc.Encode(tv.Value);
        		   }
        	   }
        	  }
          }

          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_WHAT_IF_ORDERS)
        	  _enc.Encode(order.WhatIf);
        }
        catch (Exception) {
          Disconnect();
          throw;
        }

        order.OrderId = orderId;
        _orderRecords.Add(orderId, new OrderRecord {
          OrderId = orderId,
          Order = order,
          Contract = contract,
        });
        return orderId;
      }
    }
Exemple #31
0
 public virtual void OnMarketDepthRequest(TWSServerClientHandler clientState, int reqId, IBContract contract,
                                          int numRows)
 {
     MarketDepthRequest?.Invoke(this, new TWSMarketDepthRequestEventArgs(clientState, reqId, contract, numRows));
 }
Exemple #32
0
    private void CheckServerCompatability(IBContract contract, IBOrder order)
    {
      //Scale Orders Minimum Version is 35
      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_SCALE_ORDERS)
        if (order.ScaleInitLevelSize != Int32.MaxValue || order.ScalePriceIncrement != Double.MaxValue)
          throw new TWSOutdatedException();

      //Minimum Sell Short Combo Leg Order is 35
      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_SSHORT_COMBO_LEGS)
        if (contract.ComboLegs.Count != 0)
          if (contract.ComboLegs.Any(t => t.ShortSaleSlot != 0 || (!string.IsNullOrEmpty(t.DesignatedLocation))))
            throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_WHAT_IF_ORDERS)
        if (order.WhatIf)
          throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_UNDER_COMP)
        if (contract.UnderlyingComponent != null)
          throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_SCALE_ORDERS2)
        if (order.ScaleSubsLevelSize != Int32.MaxValue)
          throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_ALGO_ORDERS)
        if (!string.IsNullOrEmpty(order.AlgoStrategy))
          throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_NOT_HELD)
        if (order.NotHeld)
          throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_SEC_ID_TYPE)
        if (contract.SecurityIdType != IBSecurityIdType.None || !string.IsNullOrEmpty(contract.SecurityId))
          throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_PLACE_ORDER_CONID)
        if (contract.ContractId > 0)
          throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_SSHORTX)
        if (order.ExemptCode != -1)
          throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_SSHORTX)
        if (contract.ComboLegs.Count > 0)
          if (contract.ComboLegs.Any(comboLeg => comboLeg.ExemptCode != -1))
            throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_HEDGE_ORDERS)
        if (!String.IsNullOrEmpty(order.HedgeType))
          throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_OPT_OUT_SMART_ROUTING)
        if (order.OptOutSmartRouting)
          throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_DELTA_NEUTRAL_CONID)
        if (order.DeltaNeutralContractId > 0 ||
            !String.IsNullOrEmpty(order.DeltaNeutralSettlingFirm) ||
            !String.IsNullOrEmpty(order.DeltaNeutralClearingAccount) ||
            !String.IsNullOrEmpty(order.DeltaNeutralClearingIntent))
          throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_DELTA_NEUTRAL_OPEN_CLOSE)
        if (!String.IsNullOrEmpty(order.DeltaNeutralOpenClose) ||
            order.DeltaNeutralShortSale || order.DeltaNeutralShortSaleSlot > 0 || !String.IsNullOrEmpty(order.DeltaNeutralDesignatedLocation))
          throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_SCALE_ORDERS3)
        if (order.ScalePriceIncrement > 0 && order.ScalePriceIncrement != Double.MaxValue)
          if (order.ScalePriceAdjustValue != Double.MaxValue ||
              order.ScalePriceAdjustInterval != Int32.MaxValue ||
              order.ScaleProfitOffset != Double.MaxValue ||
              order.ScaleAutoReset ||
              order.ScaleInitPosition != Int32.MaxValue ||
              order.ScaleInitFillQty != Int32.MaxValue ||
              order.ScaleRandomPercent)
            throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_ORDER_COMBO_LEGS_PRICE && contract.SecurityType == IBSecurityType.Bag)
        if (order.OrderComboLegs.Any(c => c.Price != Double.MaxValue))
          throw new TWSOutdatedException();

      if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_TRAILING_PERCENT)
        if (order.TrailingPercent != Double.MaxValue)
          throw new TWSOutdatedException();
    }
Exemple #33
0
 private void DumpContract(IBContract c)
 {
     Debug.WriteLine(String.Format("{0} {1} {2} {3} {4} {5} {6}", c.Symbol, c.SecurityType, c.Expiry, c.Strike, c.Right,
                                   c.Exchange, c.Currency));
 }
Exemple #34
0
    public virtual void ExerciseOptions(int reqId,
      IBContract contract,
      int exerciseAction,
      int exerciseQuantity,
      string account,
      int overrideOrder)
    {
      lock (_socketLock) {
        // not connected?
        if (!IsConnected)
          throw new NotConnectedException();

        const int reqVersion = 1;

        try {
          if (ServerInfo.Version < 21) {
            OnError(TWSErrors.UPDATE_TWS);
            return;
          }

          _enc.Encode(ServerMessage.ExerciseOptions);
          _enc.Encode(reqVersion);
          _enc.Encode(reqId);
          _enc.Encode(contract.Symbol);
          _enc.Encode(contract.SecurityType);
          _enc.Encode(contract.Expiry.HasValue ? contract.Expiry.Value.ToString(IB_EXPIRY_DATE_FORMAT) : String.Empty);
          _enc.Encode(contract.Strike);
          _enc.Encode(contract.Right);
          _enc.Encode(contract.Multiplier);
          _enc.Encode(contract.Exchange);
          _enc.Encode(contract.Currency);
          _enc.Encode(contract.LocalSymbol);
          _enc.Encode(exerciseAction);
          _enc.Encode(exerciseQuantity);
          _enc.Encode(account);
          _enc.Encode(overrideOrder);
        } catch (Exception) {
          Disconnect();
          throw;
        }
      }
    }
Exemple #35
0
 protected void OnUpdatePortfolio(IBContract contract, int position, double marketPrice, double marketValue,
                                  double averageCost, double unrealizedPNL, double realizedPNL, string accountName)
 {
   if (UpdatePortfolio != null)
     UpdatePortfolio(this, new TWSUpdatePortfolioEventArgs(this) {
       Contract = contract,
       Position = position,
       MarketPrice = marketPrice,
       MarketValue = marketValue,
       AverageCost = averageCost,
       UnrealizedPnL = unrealizedPNL,
       RealizedPnL = realizedPNL,
       AccountName = accountName,
   });
 }
 public TWSMarketDataCancelEventArgs(TWSServerClientHandler clientState, int reqId, IBContract contract)
     : base(clientState)
 {
     Contract = contract;
     ReqId    = reqId;
 }
Exemple #37
0
    public async Task<IList<IBContractDetails>> GetContractDetailsAsync(IBContract c)
    {
      var id = -1;
      var results = new List<IBContractDetails>();
      var completed = new ProgressiveTaskCompletionSource<List<IBContractDetails>> {Value = results};

      id = NextValidId;
      _asyncCalls.Add(id, completed);
      RequestContractDetails(c, id);
      await completed.Task;
      _asyncCalls.Remove(id);
      return results;
    }
    private void ProcessMarketDepthRequest()
    {
      try {
        int reqVersion = _enc.DecodeInt();
        int reqId = _enc.DecodeInt();
        int numRows = 0;

        var contract = new IBContract {
                                        Symbol = _enc.DecodeString(),
                                        SecurityType = _enc.DecodeEnum<IBSecurityType>(),
                                        Expiry = _enc.DecodeExpiryDate(),
                                        Strike = _enc.DecodeDouble(),
                                        Right = _enc.DecodeString()
                                      };

        if (ServerInfo.Version >= 15)
          contract.Multiplier = _enc.DecodeString();
        contract.Exchange = _enc.DecodeString();
        contract.Currency = _enc.DecodeString();
        contract.LocalSymbol = _enc.DecodeString();
        if (ServerInfo.Version >= 19)
          numRows = _enc.DecodeInt();
        OnMarketDepthRequest(reqId, contract, numRows);
      }
      catch (Exception e) {
        OnError(TWSErrors.FAIL_SEND_REQMKTDEPTH);
        OnError(e.Message);
        Disconnect();
      }
    }
Exemple #39
0
        private void ProcessMarketDataRequest()
        {
            int reqId = -1;

            try {
                int reqVersion = _enc.DecodeInt();
                reqId = _enc.DecodeInt();
                var contract = new IBContract {
                    Symbol       = _enc.DecodeString(),
                    SecurityType = _enc.DecodeEnum <IBSecurityType>(),
                    Expiry       = _enc.DecodeExpiryDate(),
                    Strike       = _enc.DecodeDouble(),
                    Right        = _enc.DecodeString()
                };
                if (ServerInfo.Version >= 15)
                {
                    contract.Multiplier = _enc.DecodeString();
                }
                contract.Exchange = _enc.DecodeString();
                if (ServerInfo.Version >= 14)
                {
                    contract.PrimaryExchange = _enc.DecodeString();
                }
                contract.Currency = _enc.DecodeString();
                if (ServerInfo.Version >= 2)
                {
                    contract.LocalSymbol = _enc.DecodeString();
                }
                if (ServerInfo.Version >= 8 && (contract.SecurityType == IBSecurityType.Bag))
                {
                    int comboLegCount = _enc.DecodeInt();
                    for (int i = 0; i < comboLegCount; i++)
                    {
                        var leg = new IBComboLeg {
                            ContractId = _enc.DecodeInt(),
                            Ratio      = _enc.DecodeInt(),
                            Action     = _enc.DecodeEnum <IBAction>(),
                            Exchange   = _enc.DecodeString()
                        };
                        contract.ComboLegs.Add(leg);
                    }
                }

                if (ServerInfo.Version >= 31)
                {
                    string genericTickList = _enc.DecodeString();
                    if (!string.IsNullOrEmpty(genericTickList))
                    {
                        var list = new List <IBGenericTickType>();
                        foreach (string s in genericTickList.Split(','))
                        {
                            list.Add((IBGenericTickType)Enum.Parse(typeof(IBGenericTickType), s));
                        }
                    }
                }

                OnMarketDataRequest(reqId, contract);
            }
            catch (Exception e) {
                OnError(reqId, TWSErrors.FAIL_SEND_REQMKT);
                OnError(e.Message);
                Disconnect();
            }
        }
    private void ProcessContractDataRequest()
    {
      try {
        // send req mkt data msg
        int reqVersion = _enc.DecodeInt();

        var contract = new IBContract {
                                        Symbol = _enc.DecodeString(),
                                        SecurityType = _enc.DecodeEnum<IBSecurityType>(),
                                        Expiry = _enc.DecodeExpiryDate(),
                                        Strike = _enc.DecodeDouble(),
                                        Right = _enc.DecodeString()
                                      };
        if (ServerInfo.Version >= 15) {
          contract.Multiplier = _enc.DecodeString();
        }
        contract.Exchange = _enc.DecodeString();
        contract.Currency = _enc.DecodeString();
        contract.LocalSymbol = _enc.DecodeString();
        if (ServerInfo.Version >= 31) {
          contract.IncludeExpired = _enc.DecodeBool();
        }
        OnContractDataRequest(contract);
      }
      catch (Exception e) {
        OnError(TWSErrors.FAIL_SEND_REQCONTRACT);
        OnError(e.Message);
        Disconnect();
      }
    }
Exemple #41
0
 public virtual void OnMarketDepthCancel(TWSServerClientHandler client, int reqId, IBContract contract)
 {
   if (MarketDataCancel != null)
     MarketDataCancel(this, new TWSMarketDataCancelEventArgs(client, reqId, contract));
 }
    private void OnMarketDataRequest(int reqId, IBContract contract)
    {
      if (Server != null)
        Server.OnMarketDataRequest(this, reqId, contract);

      if (MarketDataRequest != null)
        MarketDataRequest(this, new TWSMarketDataRequestEventArgs(this, reqId, contract));

      _marketDataSubscriptions.Add(reqId, contract);
    }
Exemple #43
0
 public virtual void OnMarketDepthRequest(TWSServerClientHandler clientState, int reqId, IBContract contract,
                                          int numRows)
 {
   if (MarketDepthRequest != null)
     MarketDepthRequest(this, new TWSMarketDepthRequestEventArgs(clientState, reqId, contract, numRows));
 }
 public TWSMarketDepthRequestEventArgs(TWSServerClientHandler clientState, int reqId, IBContract contract,
                                       int numRows)
     : base(clientState, reqId, contract)
 {
     numRows = numRows;
 }
Exemple #45
0
 public TWSMarketDataRequestEventArgs(TWSServerClientState clientState, int reqId, IBContract contract)
     : base(clientState)
 {
     Contract = contract;
     ReqId = reqId;
 }
Exemple #46
0
    public virtual void RequestRealTimeBars(int reqId, IBContract contract,
                                            int barSize, string whatToShow, bool useRTH)
    {
      lock (_socketLock) {
        // not connected?
        if (!IsConnected)
          throw new NotConnectedException();
        if (ServerInfo.Version < 34)
          throw new TWSOutdatedException();

        const int reqVersion = 1;

        try {
          // send req mkt data msg
          _enc.Encode(ServerMessage.RequestRealTimeBars);
          _enc.Encode(reqVersion);
          _enc.Encode(reqId);

          _enc.Encode(contract.Symbol);
          _enc.Encode(contract.SecurityType);
          _enc.Encode(contract.Expiry.HasValue ? contract.Expiry.Value.ToString(IB_EXPIRY_DATE_FORMAT) : String.Empty);
          _enc.Encode(contract.Strike);
          _enc.Encode(contract.Right);
          _enc.Encode(contract.Multiplier);
          _enc.Encode(contract.Exchange);
          _enc.Encode(contract.PrimaryExchange);
          _enc.Encode(contract.Currency);
          _enc.Encode(contract.LocalSymbol);
          _enc.Encode(barSize);
          _enc.Encode(whatToShow);
          _enc.Encode(useRTH);
        } catch (Exception e) {
          Disconnect();
          throw;
        }
      }
    }
Exemple #47
0
        private void ProcessMarketDataRequest()
        {
            int reqId = -1;

            try {
                int reqVersion = _enc.DecodeInt();
                reqId = _enc.DecodeInt();

                var contract = new IBContract();
                contract.Symbol  = _enc.DecodeString();
                contract.SecType = _enc.DecodeSecType();
                contract.Expiry  = _enc.DecodeExpiryDate();
                contract.Strike  = _enc.DecodeDouble();
                contract.Right   = _enc.DecodeString();
                if (ServerInfo.Version >= 15)
                {
                    contract.Multiplier = _enc.DecodeInt();
                }
                contract.Exchange = _enc.DecodeString();
                if (ServerInfo.Version >= 14)
                {
                    contract.PrimaryExch = _enc.DecodeString();
                }
                contract.Currency = _enc.DecodeString();
                if (ServerInfo.Version >= 2)
                {
                    contract.LocalSymbol = _enc.DecodeString();
                }
                if (ServerInfo.Version >= 8 && (contract.SecType == IBSecType.BAG))
                {
                    int comboLegCount = _enc.DecodeInt();
                    for (var i = 0; i < comboLegCount; i++)
                    {
                        IBComboLeg leg = new IBComboLeg();
                        leg.ConId    = _enc.DecodeInt();
                        leg.Ratio    = _enc.DecodeInt();
                        leg.Action   = _enc.DecodeAction();
                        leg.Exchange = _enc.DecodeString();
                        contract.ComboLegs.Add(leg);
                    }
                }

                if (ServerInfo.Version >= 31)
                {
                    string genericTickList = _enc.DecodeString();
                    if (genericTickList != null && genericTickList.Length > 0)
                    {
                        var list = new List <IBGenericTickType>();
                        foreach (var s in genericTickList.Split(','))
                        {
                            list.Add((IBGenericTickType)Enum.Parse(typeof(IBGenericTickType), s));
                        }
                    }
                }

                OnMarketDataRequest(reqId, contract);
            }
            catch (Exception e) {
                OnError(reqId, TWSErrors.FAIL_SEND_REQMKT);
                OnError(e.Message);
                Disconnect();
            }
        }
Exemple #48
0
    public virtual int RequestMarketDepth(IBContract contract, int numRows)
    {
      lock (_socketLock) {
        if (!IsConnected)
          throw new NotConnectedException();

        if (ServerInfo.Version < 6)
          throw new TWSOutdatedException();

        const int reqVersion = 3;
        var reqId = NextValidId;
        try {
          _enc.Encode(ServerMessage.RequestMarketDepth);
          _enc.Encode(reqVersion);
          _enc.Encode(reqId);
          _enc.Encode(contract.Symbol);
          _enc.Encode(contract.SecurityType);
          _enc.Encode(contract.Expiry.HasValue ? contract.Expiry.Value.ToString(IB_EXPIRY_DATE_FORMAT) : String.Empty);
          _enc.Encode(contract.Strike);
          _enc.Encode(contract.Right);
          if (ServerInfo.Version >= 15)
            _enc.Encode(contract.Multiplier);
          _enc.Encode(contract.Exchange);
          _enc.Encode(contract.Currency);
          _enc.Encode(contract.LocalSymbol);
          if (ServerInfo.Version >= 19)
            _enc.Encode(numRows);
        }
        catch (Exception) {
          Disconnect();
          throw;
        }
        return reqId;
      }
    }
Exemple #49
0
 public virtual void OnMarketDepthCancel(TWSServerClientHandler client, int reqId, IBContract contract)
 {
     MarketDataCancel?.Invoke(this, new TWSMarketDataCancelEventArgs(client, reqId, contract));
 }
Exemple #50
0
    /// <summary>
    /// Request Full Contract Details for the specified partial contract through the <see cref="ContractDetails"/> event
    /// </summary>
    /// <param name="contract">The partial contract details</param>
    /// <param name="requestId">Optional request id</param>
    /// <returns>the request id</returns>
    /// <exception cref="NotConnectedException"></exception>
    /// <exception cref="TWSOutdatedException"></exception>
    public virtual int RequestContractDetails(IBContract contract, int requestId = 0)
    {
      lock (_socketLock) {
        // not connected?
        if (!IsConnected)
          throw new NotConnectedException();

        // This feature is only available for versions of TWS >=4
        if (ServerInfo.Version < 4)
          throw new TWSOutdatedException();
        if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_SEC_ID_TYPE)
          if (contract.SecurityIdType != IBSecurityIdType.None || !String.IsNullOrEmpty(contract.SecurityId))
            throw new TWSOutdatedException();

        const int reqVersion = 6;

        try {
          // send req mkt data msg
          _enc.Encode(ServerMessage.RequestContractData);
          _enc.Encode(reqVersion);

          if (requestId == 0)
            requestId = NextValidId;

          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_CONTRACT_DATA_CHAIN) {
            _enc.Encode(requestId);
          }
          // send contract fields
          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_CONTRACT_CONID)
            _enc.Encode(contract.ContractId);
          _enc.Encode(contract.Symbol);
          _enc.Encode(contract.SecurityType);
          _enc.Encode(contract.Expiry.HasValue ? contract.Expiry.Value.ToString(IB_EXPIRY_DATE_FORMAT) : String.Empty);
          _enc.Encode(contract.Strike);
          _enc.Encode(contract.Right);
          if (ServerInfo.Version >= 15) {
            _enc.Encode(contract.Multiplier);
          }
          _enc.Encode(contract.Exchange);
          _enc.Encode(contract.Currency);
          _enc.Encode(contract.LocalSymbol);
          if (ServerInfo.Version >= 31)
            _enc.Encode(contract.IncludeExpired);
          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_SEC_ID_TYPE) {
            _enc.Encode(contract.SecurityIdType);
            _enc.Encode(contract.SecurityId);
          }
          return requestId;
        } catch (Exception) {
          Disconnect();
          throw;
        }
      }
    }
Exemple #51
0
    public virtual int RequestHistoricalData(IBContract contract, string endDateTime,
                                             string durationStr, int barSizeSetting,
                                             string whatToShow, int useRTH, int formatDate)
    {
      lock (_socketLock) {
        // not connected?
        if (!IsConnected)
          throw new NotConnectedException();

        const int reqVersion = 4;
        var requestId = NextValidId;

        try {
          if (ServerInfo.Version < 16)
            throw new TWSOutdatedException();

          _enc.Encode(ServerMessage.RequestHistoricalData);
          _enc.Encode(reqVersion);
          _enc.Encode(requestId);
          _enc.Encode(contract.Symbol);
          _enc.Encode(contract.SecurityType);
          _enc.Encode(contract.Expiry.HasValue ? contract.Expiry.Value.ToString(IB_EXPIRY_DATE_FORMAT) : String.Empty);
          _enc.Encode(contract.Strike);
          _enc.Encode(contract.Right);
          _enc.Encode(contract.Multiplier);
          _enc.Encode(contract.Exchange);
          _enc.Encode(contract.PrimaryExchange);
          _enc.Encode(contract.Currency);
          _enc.Encode(contract.LocalSymbol);
          if (ServerInfo.Version >= 31)
            _enc.Encode(contract.IncludeExpired ? 1 : 0);
          if (ServerInfo.Version >= 20) {
            _enc.Encode(endDateTime);
            _enc.Encode(barSizeSetting);
          }
          _enc.Encode(durationStr);
          _enc.Encode(useRTH);
          _enc.Encode(whatToShow);
          if (ServerInfo.Version > 16) {
            _enc.Encode(formatDate);
          }
          if (IBSecurityType.Bag == contract.SecurityType) {
            if (contract.ComboLegs == null || contract.ComboLegs.Count == 0)
              _enc.Encode(0);
            else {
              _enc.Encode(contract.ComboLegs.Count);

              foreach (var comboLeg in contract.ComboLegs) {
                _enc.Encode(comboLeg.ContractId);
                _enc.Encode(comboLeg.Ratio);
                _enc.Encode(comboLeg.Action);
                _enc.Encode(comboLeg.Exchange);
              }
            }
          }
        }
        catch (Exception) {
          Disconnect();
          throw;
        }
        return requestId;
      }
    }
 void OnContractDataRequest(IBContract contract)
 {
     Server?.OnContractDetailsRequest(this, contract);
 }
Exemple #53
0
 public TWSMarketDataSnapshot(IBContract contract)
 {
     Contract = contract;
 }
Exemple #54
0
    public async Task<int> RequestMarketDataAsync(IBContract contract, IList<IBGenericTickType> tickList = null, bool snapshot = false)
    {
      var completion = new ProgressiveTaskCompletionSource<object>();
      var id = NextValidId;
      _asyncCalls.Add(id, completion);
      RequestMarketData(contract, tickList, snapshot, id);

      int timeout = 1000;
      if (await Task.WhenAny(completion.Task, Task.Delay(timeout)) == completion.Task) {
        if (completion.Task.IsFaulted)
          throw completion.Task.Exception;
      }

      // We might be here because there was no market-data or error within the timeout
      // At any rate, we consider this to be a success
      // IB is shit, this is the best we can do
      _asyncCalls.Remove(id);
      return id;
    }
    private void ProcessMarketDataRequest()
    {
      int reqId = -1;
      try {
        int reqVersion = _enc.DecodeInt();
        reqId = _enc.DecodeInt();
        var contract = new IBContract {
                                        Symbol = _enc.DecodeString(),
                                        SecurityType = _enc.DecodeEnum<IBSecurityType>(),
                                        Expiry = _enc.DecodeExpiryDate(),
                                        Strike = _enc.DecodeDouble(),
                                        Right = _enc.DecodeString()
                                      };
        if (ServerInfo.Version >= 15)
          contract.Multiplier = _enc.DecodeString();
        contract.Exchange = _enc.DecodeString();
        if (ServerInfo.Version >= 14)
          contract.PrimaryExchange = _enc.DecodeString();
        contract.Currency = _enc.DecodeString();
        if (ServerInfo.Version >= 2)
          contract.LocalSymbol = _enc.DecodeString();
        if (ServerInfo.Version >= 8 && (contract.SecurityType == IBSecurityType.Bag)) {
          int comboLegCount = _enc.DecodeInt();
          for (int i = 0; i < comboLegCount; i++) {
            var leg = new IBComboLeg {
                                       ContractId = _enc.DecodeInt(),
                                       Ratio = _enc.DecodeInt(),
                                       Action = _enc.DecodeEnum<IBAction>(),
                                       Exchange = _enc.DecodeString()
                                     };
            contract.ComboLegs.Add(leg);
          }
        }

        if (ServerInfo.Version >= 31) {
          string genericTickList = _enc.DecodeString();
          if (!string.IsNullOrEmpty(genericTickList)) {
            var list = new List<IBGenericTickType>();
            foreach (string s in genericTickList.Split(','))
              list.Add((IBGenericTickType) Enum.Parse(typeof (IBGenericTickType), s));
          }
        }

        OnMarketDataRequest(reqId, contract);
      }
      catch (Exception e) {
        OnError(reqId, TWSErrors.FAIL_SEND_REQMKT);
        OnError(e.Message);
        Disconnect();
      }
    }
Exemple #56
0
    public virtual int RequestMarketData(IBContract contract, IList<IBGenericTickType> genericTickList = null, bool snapshot = false, int reqId = 0)
    {
      lock (_socketLock) {
        if (!IsConnected)
          throw new NotConnectedException();

        if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_SNAPSHOT_MKT_DATA && snapshot)
          throw new TWSOutdatedException();

        if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_UNDER_COMP)
          if (contract.UnderlyingComponent != null)
            throw new TWSOutdatedException();

        if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_REQ_MKT_DATA_CONID)
          if (contract.ContractId > 0)
            throw new TWSOutdatedException();

        const int reqVersion = 9;
        if (reqId == 0)
          reqId = NextValidId;

        try {
          _enc.Encode(ServerMessage.RequestMarketData);
          _enc.Encode(reqVersion);
          _enc.Encode(reqId);
          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_REQ_MKT_DATA_CONID)
            _enc.Encode(contract.ContractId);

          _enc.Encode(contract.Symbol);
          _enc.Encode(contract.SecurityType);
          _enc.Encode(contract.Expiry.HasValue ? contract.Expiry.Value.ToString(IB_EXPIRY_DATE_FORMAT) : String.Empty);
          _enc.Encode(contract.Strike);
          _enc.Encode(contract.Right);
          if (ServerInfo.Version >= 15)
            _enc.Encode(contract.Multiplier);
          _enc.Encode(contract.Exchange);
          if (ServerInfo.Version >= 14)
            _enc.Encode(contract.PrimaryExchange);
          _enc.Encode(contract.Currency);
          if (ServerInfo.Version >= 2)
            _enc.Encode(contract.LocalSymbol);
          if (ServerInfo.Version >= 8 && (contract.SecurityType == IBSecurityType.Bag)) {
            if (contract.ComboLegs == null || contract.ComboLegs.Count == 0)
              _enc.Encode(0);
            else {
              _enc.Encode(contract.ComboLegs.Count);
              foreach (var leg in contract.ComboLegs) {
                _enc.Encode(leg.ContractId);
                _enc.Encode(leg.Ratio);
                _enc.Encode(leg.Action);
                _enc.Encode(leg.Exchange);
              }
            }
          }
          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_UNDER_COMP)
          {
            if (contract.UnderlyingComponent != null) {
              _enc.Encode(true);
              _enc.Encode(contract.UnderlyingComponent.ContractId);
              _enc.Encode(contract.UnderlyingComponent.Delta);
              _enc.Encode(contract.UnderlyingComponent.Price);
            }
            else
              _enc.Encode(false);
            }

          if (ServerInfo.Version >= 31) {
            var sb = new StringBuilder();
            if (genericTickList != null) {
              foreach (var tick in genericTickList)
                sb.Append((int) tick).Append(',');
              sb.Remove(sb.Length - 2, 1);
            }
            _enc.Encode(sb.ToString());
          }

          // If we got to here without choking on something
          // we update the request registry
          _marketDataRecords.Add(reqId, new TWSMarketDataSnapshot(contract, reqId));

          if (ServerInfo.Version >= TWSServerInfo.MIN_SERVER_VER_SNAPSHOT_MKT_DATA)
            _enc.Encode(snapshot);

          _enc.Flush();

          return reqId;
        }
        catch (Exception e) {
          Disconnect();
          throw;
        }
      }
    }
 private void OnContractDataRequest(IBContract contract)
 {
   if (Server != null)
     Server.OnContractDetailsRequest(this, contract);
 }
Exemple #58
0
    public void RequestFundamentalData(int reqId, IBContract contract, String reportType)
    {
      lock (_socketLock) {
        if (!IsConnected)
          throw new NotConnectedException();

        if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_FUNDAMENTAL_DATA)
          throw new TWSOutdatedException();

        const int VERSION = 1;

        try {
          // send req fund data msg
          _enc.Encode(ServerMessage.RequestFundamentalData);
          _enc.Encode(VERSION);
          _enc.Encode(reqId);

          // send contract fields
          _enc.Encode(contract.Symbol);
          _enc.Encode(contract.SecurityType);
          _enc.Encode(contract.Exchange);
          _enc.Encode(contract.PrimaryExchange);
          _enc.Encode(contract.Currency);
          _enc.Encode(contract.LocalSymbol);

          _enc.Encode(reportType);
        } catch (Exception) {
          Disconnect();
          throw;
        }
      }
    }
    private void OnMarketDepthRequest(int reqId, IBContract contract, int numRows)
    {
      if (Server != null)
        Server.OnMarketDepthRequest(this, reqId, contract, numRows);

      if (MarketDepthRequest != null)
        MarketDepthRequest(this, new TWSMarketDepthRequestEventArgs(this, reqId, contract, numRows));
    }
Exemple #60
0
    public void CalculateOptionPrice(int reqId, IBContract contract, double volatility, double underPrice)
    {
      lock (_socketLock) {
        if (!IsConnected)
          throw new NotConnectedException();

        if (ServerInfo.Version < TWSServerInfo.MIN_SERVER_VER_REQ_CALC_OPTION_PRICE)
          throw new TWSOutdatedException();

        const int reqVersion = 1;

        try {
          // send calculate option price msg
          _enc.Encode(ServerMessage.RequestCalcOptionPrice);
          _enc.Encode(reqVersion);
          _enc.Encode(reqId);

          // send contract fields
          _enc.Encode(contract.ContractId);
          _enc.Encode(contract.Symbol);
          _enc.Encode(contract.SecurityType);
          _enc.Encode(contract.Expiry.HasValue ? contract.Expiry.Value.ToString(IB_EXPIRY_DATE_FORMAT) : String.Empty);
          _enc.Encode(contract.Strike);
          _enc.Encode(contract.Right);
          _enc.Encode(contract.Multiplier);
          _enc.Encode(contract.Exchange);
          _enc.Encode(contract.PrimaryExchange);
          _enc.Encode(contract.Currency);
          _enc.Encode(contract.LocalSymbol);

          _enc.Encode(volatility);
          _enc.Encode(underPrice);
        } catch (Exception) {
          Disconnect();
          throw;
        }
      }
    }