title: How to get open positions or close them - Interactive Brokers API
body: <p>Created shared delegate.</p>
  
  <pre><code>class Delegation
  {
    public delegate void IBError(Exception e);
    public static IBError Error;
  
    public delegate void IBNextId(int orderId);
    public static IBNextId NextId;
  
    public delegate void IBMessage(string message);
    public static IBMessage Message;
  }
  </code></pre>
  
  <p>Implemented wrapper for IB API.</p>
  
  <pre><code>public class IBWrapper : EWrapper
  {
    // ... some other handlers go here
  
    public virtual void error(Exception e)
    {
      Delegation.Error(e);
      Delegation.Message("ERROR: " + e.Message);
    }
  
    public virtual void tickPrice(int tickerId, int field, double price, int canAutoExecute)
    {
      Delegation.Message("TICK PRICE");
    }
  
    public virtual void position(string account, Contract contract, double pos, double avgCost)
    {
      Delegation.Message("POSITION");
    }
  }
  </code></pre>
  
  <p>Then use it.</p>
  
  <pre><code>public class Broker
  {
    public static string apiHost = "127.0.0.1";
    public static int apiPort = 7496;
  
    public static int Main(string[] args)
    {
      var api = new IBWrapper();
      var client = CreateSocket(api);
      var channel = new ChannelService();
  
      Delegation.Error += (e) =&gt; { Console.WriteLine(e.Message); };
      Delegation.Message += (message) =&gt; 
      {
          // This method should intercept ALL messages from IB API
          // but it does not work for positions 
          Console.WriteLine(message); 
      };
      Delegation.NextId += (orderId) =&gt; {
  
          var action = "CLOSE"; // This variable comes from external app
  
          if (action == "CLOSE")
          {
            // Option #2: subscribe to messages from IB before some action
  
            client.reqIds(-1);
            client.reqAllOpenOrders();
            client.reqAutoOpenOrders(true);
            client.reqOpenOrders();
            client.reqPositions();
            client.reqAccountUpdates(true, "XXXXXXXXX");
  
            //CancelOrders(client);
            ClosePositions(client);
            return;
          }
  
          order.Id = orderId;
          //SendOrder(socket, order);
          //SendCurrencyOrder(client, order);
  
        client.eDisconnect();
      };
  
      // Option #1: try to subscribe to messages from IB at the start
  
      client.reqIds(-1);
      client.reqAllOpenOrders();
      client.reqAutoOpenOrders(true);
      client.reqOpenOrders();
      client.reqPositions();
      client.reqAccountUpdates(true, "XXXXXXXXX");
  
      Console.ReadKey();
      return 0;
    }
  }
  </code></pre>
  
  <p><strong>Question:</strong> how to get list of open positions and close them? </p>
  
  <p>In some reason I can get message from IB API when I receive "NextOrderId", "OpenOrder", but cannot get notifications about account data and open positions...</p>
  
  <p><strong>Description from IB API docs:</strong> API programs always have at least two threads of execution. One thread is used for sending messages to TWS, and another thread is used for reading returned messages. The second thread uses the API EReader class to read from the socket and add messages to a queue. Everytime a new message is added to the message queue, a notification flag is triggered to let other threads now that there is a message waiting to be processed. In the two-thread design of an API program, the message queue is also processed by the first thread. In a three-thread design, an additional thread is created to perform this task. The thread responsible for the message queue will decode messages and invoke the appropriate functions in EWrapper.</p>
  
  <p><a href="https://interactivebrokers.github.io/tws-api/connection.html#ereader" rel="nofollow noreferrer">https://interactivebrokers.github.io/tws-api/connection.html#ereader</a></p>