Exemplo n.º 1
0
 public TWSOpenOrderEventArgs(TWSClient client, int orderId, IBOrder order, IBContract contract)
     : base(client)
 {
     OrderId  = orderId;
     Order    = order;
     Contract = contract;
 }
Exemplo n.º 2
0
 internal OrderRecord(IBOrder order, IBContract contract)
 {
     Order     = order;
     Contract  = contract;
     CumQty    = 0;
     LeavesQty = order.TotalQuantity;
     AvgPx     = 0;
 }
Exemplo n.º 3
0
 internal OrderRecord(IBOrder order, IBContract contract)
 {
     Order = order;
     Contract = contract;
     CumQty = 0;
     LeavesQty = order.TotalQuantity;
     AvgPx = 0;
 }
Exemplo n.º 4
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
          });
        }
      }
    }
Exemplo n.º 5
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();
    }
Exemplo n.º 6
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;
      }
    }
Exemplo n.º 7
0
    private void ProcessOpenOrder()
    {
      // read version
      var version = _enc.DecodeInt();
      var order = new IBOrder { OrderId = _enc.DecodeInt() };

      // read contract fields
      var contract = new IBContract {
        ContractId = version >= 17 ? _enc.DecodeInt() : 0,
        Symbol = _enc.DecodeString(),
        SecurityType = _enc.DecodeEnum<IBSecurityType>(),
        Expiry = DecodeIBExpiry(_enc),
        Strike = _enc.DecodeDouble(),
        Right = _enc.DecodeString(),
        Exchange = _enc.DecodeString(),
        Currency = _enc.DecodeString(),
        LocalSymbol = (version >= 2) ? _enc.DecodeString() : null
      };

      // read other order fields
      order.Action = _enc.DecodeEnum<IBAction>();
      order.TotalQuantity = _enc.DecodeInt();
      order.OrderType = _enc.DecodeEnum<IBOrderType>();
      order.LimitPrice = version < 29 ? _enc.DecodeDouble() : _enc.DecodeDoubleMax();
      order.AuxPrice = version < 30 ? _enc.DecodeDouble() : _enc.DecodeDoubleMax();

      order.Tif = _enc.DecodeEnum<IBTimeInForce>();
      order.OcaGroup = _enc.DecodeString();
      order.Account = _enc.DecodeString();
      order.OpenClose = _enc.DecodeString();
      order.Origin = _enc.DecodeEnum<IBOrderOrigin>();
      order.OrderRef = _enc.DecodeString();

      if (version >= 3)
        order.ClientId = _enc.DecodeInt();

      if (version >= 4) {
        order.PermId = _enc.DecodeInt();
        if (version < 18)
          order.IgnoreRth = _enc.DecodeInt() == 1;
        else
          order.OutsideRth = _enc.DecodeInt() == 1;

        order.Hidden = _enc.DecodeBool();
        order.DiscretionaryAmt = _enc.DecodeDouble();
      }

      if (version >= 5)
        order.GoodAfterTime = _enc.DecodeString();

      if (version >= 6)
        order.SharesAllocation = _enc.DecodeString();

      if (version >= 7) {
        order.FaGroup = _enc.DecodeString();
        order.FaMethod = _enc.DecodeEnum<IBFinancialAdvisorAllocationMethod>();
        order.FaPercentage = _enc.DecodeString();
        order.FaProfile = _enc.DecodeString();
      }

      if (version >= 8)
        order.GoodTillDate = _enc.DecodeString();

      if (version >= 9) {
        order.Rule80A = _enc.DecodeEnum<IBAgentDescription>();
        order.PercentOffset = _enc.DecodeDouble();
        order.SettlingFirm = _enc.DecodeString();
        order.ShortSaleSlot = _enc.DecodeInt();
        order.DesignatedLocation = _enc.DecodeString();
        if (ServerInfo.Version == 51)
          _enc.DecodeInt(); // exemptCode
        else if (version >= 23)
          order.ExemptCode = _enc.DecodeInt();

        order.AuctionStrategy = _enc.DecodeInt();
        order.StartingPrice = _enc.DecodeDouble();
        order.StockRefPrice = _enc.DecodeDouble();
        order.Delta = _enc.DecodeDouble();
        order.StockRangeLower = _enc.DecodeDouble();
        order.StockRangeUpper = _enc.DecodeDouble();
        order.DisplaySize = _enc.DecodeInt();
        if (version < 18)
          order.RthOnly = _enc.DecodeBool();
        order.BlockOrder = _enc.DecodeBool();
        order.SweepToFill = _enc.DecodeBool();
        order.AllOrNone = _enc.DecodeBool();
        order.MinQty = _enc.DecodeInt();
        order.OcaType = _enc.DecodeEnum<IBOcaType>();
        order.ETradeOnly = _enc.DecodeBool();
        order.FirmQuoteOnly = _enc.DecodeBool();
        order.NbboPriceCap = _enc.DecodeDouble();
      }

      if (version >= 10) {
        order.ParentId = _enc.DecodeInt();
        order.TriggerMethod = _enc.DecodeInt();
      }

      if (version >= 11) {
        order.Volatility = _enc.DecodeDouble();
        order.VolatilityType = _enc.DecodeEnum<IBVolatilityType>();
        if (version == 11) {
          var receivedInt = _enc.DecodeInt();
          order.DeltaNeutralOrderType = ((receivedInt == 0) ? IBOrderType.None : IBOrderType.Market);
        }
        else {
          // version 12 and up

          order.DeltaNeutralOrderType = _enc.DecodeEnum<IBOrderType>();
          order.DeltaNeutralAuxPrice = _enc.DecodeDoubleMax();

          if (version >= 27 && order.DeltaNeutralOrderType != IBOrderType.Empty) {
            order.DeltaNeutralContractId = _enc.DecodeInt();
            order.DeltaNeutralSettlingFirm = _enc.DecodeString();
            order.DeltaNeutralClearingAccount = _enc.DecodeString();
            order.DeltaNeutralClearingIntent = _enc.DecodeString();
          }

          if (version >= 31 && order.DeltaNeutralOrderType != IBOrderType.Empty) {
            order.DeltaNeutralOpenClose = _enc.DecodeString();
            order.DeltaNeutralShortSale = _enc.DecodeBool();
            order.DeltaNeutralShortSaleSlot = _enc.DecodeInt();
            order.DeltaNeutralDesignatedLocation = _enc.DecodeString();
          }
        }
        order.ContinuousUpdate = _enc.DecodeInt();
        if (ServerInfo.Version == 26) {
          order.StockRangeLower = _enc.DecodeDouble();
          order.StockRangeUpper = _enc.DecodeDouble();
        }
        order.ReferencePriceType = _enc.DecodeInt();
      }

      if (version >= 13)
        order.TrailStopPrice = _enc.DecodeDoubleMax();

      if (version >= 30)
        order.TrailingPercent = _enc.DecodeDoubleMax();

      if (version >= 14) {
        order.BasisPoints = _enc.DecodeDouble();
        order.BasisPointsType = _enc.DecodeInt();
        contract.ComboLegsDescription = _enc.DecodeString();
      }

      if (version >= 29) {
        var comboLegsCount = _enc.DecodeInt();
        if (comboLegsCount > 0) {
          contract.ComboLegs = new List<IBComboLeg>(comboLegsCount);
          for (var i = 0; i < comboLegsCount; ++i)
            contract.ComboLegs.Add(new IBComboLeg {
              ContractId = _enc.DecodeInt(),
              Ratio = _enc.DecodeInt(),
              Action = _enc.DecodeEnum<IBAction>(),
              Exchange = _enc.DecodeString(),
              OpenClose = _enc.DecodeEnum<IBComboOpenClose>(),
              ShortSaleSlot = _enc.DecodeEnum<IBShortSaleSlot>(),
              DesignatedLocation = _enc.DecodeString(),
              ExemptCode = _enc.DecodeInt(),
            });
        }

        var orderComboLegsCount = _enc.DecodeInt();
        if (orderComboLegsCount > 0) {
          order.OrderComboLegs = new List<IBOrderComboLeg>(orderComboLegsCount);
          for (var i = 0; i < orderComboLegsCount; ++i)
            order.OrderComboLegs.Add(new IBOrderComboLeg { Price = _enc.DecodeDoubleMax() });
        }
      }

      if (version >= 26) {
        var smartComboRoutingParamsCount = _enc.DecodeInt();
        if (smartComboRoutingParamsCount > 0) {
          order.SmartComboRoutingParams = new List<IBTagValue>(smartComboRoutingParamsCount);
          for (var i = 0; i < smartComboRoutingParamsCount; ++i)
            order.SmartComboRoutingParams.Add(new IBTagValue {
                Tag = _enc.DecodeString(),
                Value = _enc.DecodeString()
              });
        }
      }

      if (version >= 15)
      {
        if (version >= 20) {
          order.ScaleInitLevelSize = _enc.DecodeIntMax();
          order.ScaleSubsLevelSize = _enc.DecodeIntMax();
        }
        else {
          /* int notSuppScaleNumComponents = */
          _enc.DecodeIntMax();
          order.ScaleInitLevelSize = _enc.DecodeIntMax();
        }
        order.ScalePriceIncrement = _enc.DecodeDoubleMax();
      }

      if (version >= 28 && order.ScalePriceIncrement > 0.0 && order.ScalePriceIncrement != Double.MaxValue) {
        order.ScalePriceAdjustValue = _enc.DecodeDoubleMax();
        order.ScalePriceAdjustInterval = _enc.DecodeIntMax();
        order.ScaleProfitOffset = _enc.DecodeDoubleMax();
        order.ScaleAutoReset = _enc.DecodeBool();
        order.ScaleInitPosition = _enc.DecodeIntMax();
        order.ScaleInitFillQty = _enc.DecodeIntMax();
        order.ScaleRandomPercent = _enc.DecodeBool();
      }

      if (version >= 24)
      {
        order.HedgeType = _enc.DecodeString();
        if (!String.IsNullOrEmpty(order.HedgeType))
          order.HedgeParam = _enc.DecodeString();
      }

      if (version >= 25)
        order.OptOutSmartRouting = _enc.DecodeBool();

      if (version >= 19) {
        order.ClearingAccount = _enc.DecodeString();
        order.ClearingIntent = _enc.DecodeString();
      }

      if (version >= 22)
        order.NotHeld = _enc.DecodeBool();

      if (version >= 20)
      {
        if (_enc.DecodeBool()) {
          contract.UnderlyingComponent = new IBUnderlyinhComponent {
            ContractId = _enc.DecodeInt(),
            Delta = _enc.DecodeDouble(),
            Price = _enc.DecodeDouble()
          };
        }
      }

      if (version >= 21)
      {
        order.AlgoStrategy = _enc.DecodeString();
        if (!String.IsNullOrEmpty(order.AlgoStrategy))
        {
          var algoParamsCount = _enc.DecodeInt();
          if (algoParamsCount > 0) {
            order.AlgoParams = new List<IBTagValue>(algoParamsCount);
            for (var i = 0; i < algoParamsCount; ++i)
              order.AlgoParams.Add(new IBTagValue {
                Tag = _enc.DecodeString(),
                Value = _enc.DecodeString(),
              });
          }
        }
      }

      var orderState = new IBOrderState();

      if (version >= 16) {
        order.WhatIf = _enc.DecodeBool();

        orderState.Status = _enc.DecodeEnum<IBOrderStatus>();
        orderState.InitMargin = _enc.DecodeString();
        orderState.MaintMargin = _enc.DecodeString();
        orderState.EquityWithLoan = _enc.DecodeString();
        orderState.Commission = _enc.DecodeDoubleMax();
        orderState.MinCommission = _enc.DecodeDoubleMax();
        orderState.MaxCommission = _enc.DecodeDoubleMax();
        orderState.CommissionCurrency = _enc.DecodeString();
        orderState.WarningText = _enc.DecodeString();
      }

      OnOpenOrder(order.OrderId, order, contract, orderState);
    }
Exemplo n.º 8
0
 public FOrder()
 {
     this._orderBusiness = new BOrder();
 }
Exemplo n.º 9
0
 public TWSOpenOrderEventArgs(TWSClient client, int orderId, IBOrder order, IBContract contract)
     : base(client)
 {
     OrderId = orderId;
     Order = order;
     Contract = contract;
 }
Exemplo n.º 10
0
        private void ProcessOpenOrder()
        {
            IBOrder order = new IBOrder();

            // read version
            int version = _enc.DecodeInt();
            // read order id
            order.OrderId = _enc.DecodeInt();

            // read contract fields
            IBContract contract = new IBContract();
            contract.Symbol = _enc.DecodeString();
            contract.SecType = _enc.DecodeSecType();
            contract.Expiry = DateTime.ParseExact(_enc.DecodeString(), IB_EXPIRY_DATE_FORMAT, CultureInfo.InvariantCulture);
            contract.Strike = _enc.DecodeDouble();
            contract.Right = _enc.DecodeString();
            contract.Exchange = _enc.DecodeString();
            contract.Currency = _enc.DecodeString();
            contract.LocalSymbol = (version >= 2) ? _enc.DecodeString() : null;

            // read other order fields
            order.Action = _enc.DecodeAction();
            order.TotalQuantity = _enc.DecodeInt();
            order.OrderType = _enc.DecodeOrderType();
            order.LmtPrice = _enc.DecodeDouble();
            order.AuxPrice = _enc.DecodeDouble();
            order.Tif = _enc.DecodeTif();
            order.OcaGroup = _enc.DecodeString();
            order.Account = _enc.DecodeString();
            order.OpenClose = _enc.DecodeString();
            order.Origin = _enc.DecodeInt();
            order.OrderRef = _enc.DecodeString();

            if (version >= 3)
                order.ClientId = _enc.DecodeInt();

            if (version >= 4) {
                order.PermId = _enc.DecodeInt();
                order.IgnoreRth = _enc.DecodeInt() == 1;
                order.Hidden = _enc.DecodeInt() == 1;
                order.DiscretionaryAmt = _enc.DecodeDouble();
            }

            if (version >= 5)
                order.GoodAfterTime = _enc.DecodeString();

            if (version >= 6)
                order.SharesAllocation = _enc.DecodeString();

            if (version >= 7) {
                order.FaGroup = _enc.DecodeString();
                order.FaMethod = _enc.DecodeString();
                order.FaPercentage = _enc.DecodeString();
                order.FaProfile = _enc.DecodeString();
            }

            if (version >= 8)
                order.GoodTillDate = _enc.DecodeString();

            if (version >= 9) {
                order.Rule80A = _enc.DecodeString();
                order.PercentOffset = _enc.DecodeDouble();
                order.SettlingFirm = _enc.DecodeString();
                order.ShortSaleSlot = _enc.DecodeInt();
                order.DesignatedLocation = _enc.DecodeString();
                order.AuctionStrategy = _enc.DecodeInt();
                order.StartingPrice = _enc.DecodeDouble();
                order.StockRefPrice = _enc.DecodeDouble();
                order.Delta = _enc.DecodeDouble();
                order.StockRangeLower = _enc.DecodeDouble();
                order.StockRangeUpper = _enc.DecodeDouble();
                order.DisplaySize = _enc.DecodeInt();
                order.RthOnly = _enc.DecodeBool();
                order.BlockOrder = _enc.DecodeBool();
                order.SweepToFill = _enc.DecodeBool();
                order.AllOrNone = _enc.DecodeBool();
                order.MinQty = _enc.DecodeInt();
                order.OcaType = _enc.DecodeInt();
                order.ETradeOnly = _enc.DecodeBool();
                order.FirmQuoteOnly = _enc.DecodeBool();
                order.NbboPriceCap = _enc.DecodeDouble();
            }

            if (version >= 10) {
                order.ParentId = _enc.DecodeInt();
                order.TriggerMethod = _enc.DecodeInt();
            }

            if (version >= 11) {
                order.Volatility = _enc.DecodeDouble();
                order.VolatilityType = _enc.DecodeInt();
                if (version == 11) {
                    int receivedInt = _enc.DecodeInt();
                    order.DeltaNeutralOrderType = ((receivedInt == 0) ? IBOrderType.NONE : IBOrderType.MKT);
                }
                else {
                    // version 12 and up
                    order.DeltaNeutralOrderType = _enc.DecodeOrderType();
                    order.DeltaNeutralAuxPrice = _enc.DecodeDouble();
                }
                order.ContinuousUpdate = _enc.DecodeInt();
                if (ServerInfo.Version == 26) {
                    order.StockRangeLower = _enc.DecodeDouble();
                    order.StockRangeUpper = _enc.DecodeDouble();
                }
                order.ReferencePriceType = _enc.DecodeInt();
            }

            if (version >= 13)
                order.TrailStopPrice = _enc.DecodeDouble();

            if (version >= 14)
            {
                order.BasisPoints = _enc.DecodeDouble();
                order.BasisPointsType = _enc.DecodeInt();
                contract.ComboLegsDescrip = _enc.DecodeString();
            }

            OnOpenOrder(order.OrderId, order, contract);
        }
Exemplo n.º 11
0
 protected void OnOpenOrder(int orderId, IBOrder order, IBContract contract)
 {
     if (OpenOrder != null)
         OpenOrder(this, new TWSOpenOrderEventArgs(this, orderId, order, contract));
 }
Exemplo n.º 12
0
        public virtual int RequestPlaceOrder(IBContract contract, IBOrder order)
        {
            lock (this) {
                if (!IsConnected) {
                    OnError(TWSErrors.NOT_CONNECTED);
                    return -1;
                }

                int reqVersion = 20;
                int orderId = NextValidId;
                try {
                    _enc.Encode(Messages.Server.PLACE_ORDER);
                    _enc.Encode(reqVersion);
                    _enc.Encode(orderId);
                    _enc.Encode(contract.Symbol);
                    _enc.Encode(contract.SecType.ToString());
                    _enc.Encode(contract.Expiry.ToString(IB_EXPIRY_DATE_FORMAT));
                    _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.PrimaryExch);
                    _enc.Encode(contract.Currency);
                    if (ServerInfo.Version >= 2)
                        _enc.Encode(contract.LocalSymbol);
                    _enc.Encode(order.Action);
                    _enc.Encode(order.TotalQuantity);
                    _enc.Encode(order.OrderType);
                    _enc.Encode(order.LmtPrice);
                    _enc.Encode(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);
                        _enc.Encode(order.IgnoreRth);
                    }
                    if (ServerInfo.Version >= 7)
                        _enc.Encode(order.Hidden);
                    if ((ServerInfo.Version >= 8) && (contract.SecType == IBSecType.BAG)) {
                        _enc.Encode(contract.ComboLegs.Count);
                        foreach (IBComboLeg leg in contract.ComboLegs) {
                            _enc.Encode(leg.ConId);
                            _enc.Encode(leg.Ratio);
                            _enc.Encode(leg.Action);
                            _enc.Encode(leg.Exchange);
                            _enc.Encode(leg.OpenClose);
                        }
                    }
                    if (ServerInfo.Version >= 9)
                        _enc.Encode(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 >= 19) {
                        _enc.Encode(order.OcaType);
                        _enc.Encode(order.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);
                        double stockRangeLower = ((ServerInfo.Version == 26) && (order.OrderType == IBOrderType.VOL)) ?
                            Double.MaxValue : order.StockRangeLower;
                        double stockRangeUpper = ((ServerInfo.Version == 26) && (order.OrderType == IBOrderType.VOL)) ?
                            Double.MaxValue : order.StockRangeUpper;
                        this._enc.EncodeMax(stockRangeLower);
                        this._enc.EncodeMax(stockRangeUpper);
                        if (ServerInfo.Version >= 22) {
                            _enc.Encode(order.OverridePercentageConstraints);
                        }
                        if (ServerInfo.Version >= 26) {
                            _enc.EncodeMax(order.Volatility);
                            _enc.EncodeMax(order.VolatilityType);
                            if (ServerInfo.Version < 28) {
                                _enc.Encode(order.DeltaNeutralOrderType == IBOrderType.MKT);
                            }
                            else {
                                _enc.Encode(order.DeltaNeutralOrderType);
                                this._enc.EncodeMax(order.DeltaNeutralAuxPrice);
                            }
                            this._enc.Encode(order.ContinuousUpdate);
                            if (ServerInfo.Version == 26) {
                                if (order.OrderType == IBOrderType.VOL) {
                                    _enc.EncodeMax(order.StockRangeLower);
                                    _enc.EncodeMax(order.StockRangeUpper);
                                }
                                else {
                                    _enc.EncodeMax(Double.MaxValue);
                                    _enc.EncodeMax(Double.MaxValue);
                                }
                            }
                            _enc.EncodeMax(order.ReferencePriceType);
                        }
                    }

                }
                catch (Exception e) {
                    OnError(TWSErrors.FAIL_SEND_ORDER);
                    OnError(e.Message);
                    orderId = -1;
                    Disconnect();
                }

                _orderRecords.Add(orderId, new OrderRecord(order, contract));
                return orderId;
            }
        }