如何获得未平仓头寸或关闭它们 - Interactive Brokers API

时间:2017-11-24 00:49:13

标签: c# interactive-brokers

创建共享委托。

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;
}

为IB API实现了包装器。

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");
  }
}

然后使用它。

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) => { Console.WriteLine(e.Message); };
    Delegation.Message += (message) => 
    {
        // This method should intercept ALL messages from IB API
        // but it does not work for positions 
        Console.WriteLine(message); 
    };
    Delegation.NextId += (orderId) => {

        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;
  }
}

问题:如何获取未结头寸清单并关闭它们?

在某些原因,当我收到“NextOrderId”,“OpenOrder”时,我可以从IB API收到消息,但无法收到有关帐户数据和未结头寸的通知......

来自IB API文档的说明: API程序始终至少有两个执行线程。一个线程用于向TWS发送消息,另一个线程用于读取返回的消息。第二个线程使用API​​ EReader类从套接字读取并将消息添加到队列。每次向消息队列添加新消息时,都会触发通知标志,让其他线程现在有消息等待处理。在API程序的双线程设计中,消息队列也由第一个线程处理。在三线程设计中,创建了一个额外的线程来执行此任务。负责消息队列的线程将解码消息并在EWrapper中调用适当的函数。

https://interactivebrokers.github.io/tws-api/connection.html#ereader

0 个答案:

没有答案