Example #1
0
        /// <summary>
        /// Gets the execution details matching the filter
        /// </summary>
        /// <returns>A list of executions matching the filter</returns>
        public List <IB.ExecDetailsEventArgs> GetExecutions(string symbol, IB.SecurityType?type, string exchange, DateTime?timeSince, IB.ActionSide?side)
        {
            var filter = new IB.ExecutionFilter
            {
                AcctCode     = _account,
                ClientId     = _clientID,
                Exchange     = exchange,
                SecurityType = type ?? IB.SecurityType.Undefined,
                Symbol       = symbol,
                Time         = timeSince ?? DateTime.MinValue,
                Side         = side ?? IB.ActionSide.Undefined
            };

            var details = new List <IB.ExecDetailsEventArgs>();

            using (var client = new IB.IBClient())
            {
                client.Connect(_host, _port, IncrementClientID());

                var manualResetEvent = new ManualResetEvent(false);

                int requestID = GetNextRequestID();

                // define our event handlers
                EventHandler <IB.ExecutionDataEndEventArgs> clientOnExecutionDataEnd = (sender, args) =>
                {
                    if (args.RequestId == requestID)
                    {
                        manualResetEvent.Set();
                    }
                };
                EventHandler <IB.ExecDetailsEventArgs> clientOnExecDetails = (sender, args) =>
                {
                    if (args.RequestId == requestID)
                    {
                        details.Add(args);
                    }
                };

                client.ExecDetails      += clientOnExecDetails;
                client.ExecutionDataEnd += clientOnExecutionDataEnd;

                // no need to be fancy with request id since that's all this client does is 1 request
                client.RequestExecutions(requestID, filter);

                if (!manualResetEvent.WaitOne(5000))
                {
                    throw new TimeoutException("InteractiveBrokersBrokerage.GetExecutions(): Operation took longer than 1 second.");
                }

                // remove our event handlers
                client.ExecDetails      -= clientOnExecDetails;
                client.ExecutionDataEnd -= clientOnExecutionDataEnd;
            }

            return(details);
        }
        /// <summary>
        /// Gets the execution details matching the filter
        /// </summary>
        /// <returns>A list of executions matching the filter</returns>
        public List<IB.ExecDetailsEventArgs> GetExecutions(string symbol, IB.SecurityType? type, string exchange, DateTime? timeSince, IB.ActionSide? side)
        {
            var filter = new IB.ExecutionFilter
            {
                AcctCode = _account,
                ClientId = _clientID,
                Exchange = exchange,
                SecurityType = type ?? IB.SecurityType.Undefined,
                Symbol = symbol,
                Time = timeSince ?? DateTime.MinValue,
                Side = side ?? IB.ActionSide.Undefined
            };

            var details = new List<IB.ExecDetailsEventArgs>();
            using (var client = new IB.IBClient())
            {
                client.Connect(_host, _port, IncrementClientID());

                var manualResetEvent = new ManualResetEvent(false);

                int requestID = GetNextRequestID();

                // define our event handlers
                EventHandler<IB.ExecutionDataEndEventArgs> clientOnExecutionDataEnd = (sender, args) =>
                {
                    if (args.RequestId == requestID) manualResetEvent.Set();
                };
                EventHandler<IB.ExecDetailsEventArgs> clientOnExecDetails = (sender, args) =>
                {
                    if (args.RequestId == requestID) details.Add(args);
                };

                client.ExecDetails += clientOnExecDetails;
                client.ExecutionDataEnd += clientOnExecutionDataEnd;

                // no need to be fancy with request id since that's all this client does is 1 request
                client.RequestExecutions(requestID, filter);

                if (!manualResetEvent.WaitOne(5000))
                {
                    throw new TimeoutException("InteractiveBrokersBrokerage.GetExecutions(): Operation took longer than 1 second.");
                }

                // remove our event handlers
                client.ExecDetails -= clientOnExecDetails;
                client.ExecutionDataEnd -= clientOnExecutionDataEnd;
            }

            return details;
        }
Example #3
0
        public bool Connect(ServiceConnectOptions connectOptions)
        {
            ClearError();

            if (_connected)
                return true;

            foreach (Symbol symbol in new List<Symbol>(watchedSymbols.Keys))
            {
                watchedSymbols[symbol] = null;
            }

            if (client == null)
            {
                client = new IBClient();
                client.ThrowExceptions = true;

                client.Error += client_Error;
                client.TickPrice += client_TickPrice;
                client.TickSize += client_TickSize;
                client.UpdateAccountValue += client_UpdateAccountValue;
                client.UpdatePortfolio += client_UpdatePortfolio;
                client.OrderStatus += client_OrderStatus;
                client.ExecDetails += client_ExecDetails;
                client.NextValidId += client_NextValidId;
                client.CurrentTime += client_CurrentTime;
            }

            int clientID = -1;
            bool brokerConnect = ((connectOptions & ServiceConnectOptions.Broker) == ServiceConnectOptions.Broker);

            if ((connectOptions & ServiceConnectOptions.Broker) == ServiceConnectOptions.Broker)
            {
                clientID = _clientIDBroker;
            }
            else if ((connectOptions & ServiceConnectOptions.LiveData) == ServiceConnectOptions.LiveData)
            {
                clientID = _clientIDLiveData;
            }
            else if ((connectOptions & ServiceConnectOptions.HistoricalData) == ServiceConnectOptions.HistoricalData)
            {
                clientID = _clientIDHist;
            }
            if (clientID < 0)
            {
                clientID = new Random().Next();
            }

            client.Connect(string.IsNullOrEmpty(ServerAddress) ? "127.0.0.1" : ServerAddress, (Port == 0) ? 7496 : Port, clientID);
            lock (_lockObject)
            {
                _connected = true;
            }
            if (brokerConnect)
            {
                lock (_lockObject)
                {
                    _connectWaitHandle = new ManualResetEvent(false);
                    _gettingReconnectData = true;
                    _hadError1102 = false;
                    foreach (string id in openOrders.Keys)
                    {
                        _potentiallyCancelledOrders[id] = null;
                    }
                }

                client.RequestAccountUpdates(true, accountCode);
                //client.ReqAllOpenOrders();
                client.RequestOpenOrders();

                ExecutionFilter filter = new ExecutionFilter();
                filter.ClientId = clientID;
                filter.Side = ActionSide.Buy;
                client.RequestExecutions(nextID++, filter);
                filter.Side = ActionSide.Sell;
                client.RequestExecutions(nextID++, filter);

                //	Request the current time so that when we get it, we know that (hopefully)
                //	we have gotten all the results from ReqOpenOrders and ReqExecutions
                client.RequestCurrentTime();

                if (!_connectWaitHandle.WaitOne(TimeSpan.FromSeconds(10.0), true))
                {
                    string msg = "Timed out waiting for TWS order and execution data to finish.";
                    Trace.WriteLine(msg);
                    Console.WriteLine(msg);
                }

                if (_potentiallyCancelledOrders.Count > 0)
                {
                    //	Wait a bit longer to check for errorCode 1102
                    Thread.Sleep(500);
                }

                lock (_lockObject)
                {

                    _gettingReconnectData = false;

                    if (!_hadError1102)
                    {
                        foreach (string orderID in _potentiallyCancelledOrders.Keys)
                        {
                            BrokerOrder order;

                            if (openOrders.TryGetValue(orderID, out order))
                            {
                                order.OrderState = BrokerOrderState.Cancelled;
                                OrderUpdatedDelegate tmp = OrderUpdated;
                                if (tmp != null)
                                {
                                    tmp(order, null, "Order cancelled while disconnected.");
                                }
                                openOrders.Remove(orderID);
                            }
                            else
                            {
                                int b = 0;
                            }
                        }
                    }
                    _potentiallyCancelledOrders.Clear();
                }
            }

            return true;
        }