R IBrokers reqOpenOrders挂起

时间:2016-01-10 08:54:43

标签: r ibrokers

有人能够建议如何正确使用R IBrokers reqOpenOrders吗?

   > tws=twsConnect(clientId=66,host='localhost',port='7497')
   > reqOpenOrders(twsconn=tws)
    TWS Message: 2 -1 2104 Market data farm connection is OK:usopt 
    TWS Message: 2 -1 2104 Market data farm connection is OK:usfarm 
    TWS Message: 2 -1 2106 HMDS data farm connection is OK:ushmds 
    TWS OrderStatus: orderId=565 status=PreSubmitted filled=0 remaining=1 averageFillPrice=0 
    TWS OrderStatus: orderId=566 status=PreSubmitted filled=0 remaining=1 averageFillPrice=0 

我想获得一份未完成订单清单。上面的命令挂起,必须停止才能返回R提示符。感谢。

2 个答案:

答案 0 :(得分:1)

我想我明白了。该功能需要实现到IBrokers包的一些文件中。在processMsg.R中,我们需要将以下内容添加到if(curMsg == .twsIncomingMSG$OPEN_ORDER)部分:

if(curMsg == .twsIncomingMSG$OPEN_ORDER) {
    msg <- readBin(con, "character", 84)
    x = eWrapper$openOrder(curMsg, msg, timestamp, file, ...)
    return(x)

接下来,在openOrder中实现功能eWrapper.R,如下所示:

openOrder  <- function(curMsg, msg, timestamp, file,  ...) {
  x = e_open_order(msg)
  return(x)
}

然后在eventHandlers.R中,按如下方式更改e_open_order

`e_open_order` <- function(msg) {
  contents = msg
...
  return(eoo)
}

这个事件处理程序很好地将TWS返回消息中的数据引导到适当的结构,twsContract,twsOrder和twsOrderState。然后,我创建了以下函数:

gs_GetOpenOrders = function(twscon){

  # Check if connected to TWS
  if(!is.twsConnection(twscon))
    stop('requires twsConnection object')
  else
    con = twscon[[1]]

  # Send message requesting open orders
  ver = "1"
  writeBin(c(.twsOutgoingMSG$REQ_OPEN_ORDERS,ver),con)

  # Receive message with content of open orders
  ewr  = eWrapper()
  socketSelect(list(con),FALSE,NULL)
  msg = list()
  k = 0
  while(TRUE) {
    curmsg = readBin(con, character(), 1)
    if(length(curmsg)==0)
      break
    if (curmsg==.twsIncomingMSG$OPEN_ORDER){
      k = k+1
      msg[[k]] = processMsg(curmsg,con,ewr)
    }
    else
      processMsg(curmsg,con,ewr)
  }

  return(msg)
}

结果是列表变量msg。列表的每个元素依次是一个列表,其中包含打开的订单数据到结构twsContract,twsOrder和twsOrderState。从那里可以简单地以任何所需的方式获取,显示和使用数据。对于IBrokers中的几乎所有其他功能来说看起来也是如此,只是其中一些已经实现了。

答案 1 :(得分:0)

我在软件包IBrokers_0.9中创建了一个受reqAccountUpdates.R启发的函数,它返回未结订单清单。

.reqOpenOrders <- function(twsconn) {
  if( !is.twsConnection(twsconn))
    stop('requires twsConnection object')

  con <- twsconn[[1]]

  VERSION <- "1"

  writeBin(c(.twsOutgoingMSG$REQ_OPEN_ORDERS,VERSION), con)
}

reqopenorders_cb <- function(twsconn) {
  .reqOpenOrders(twsconn)

  open_orders=list()
  con <- twsconn[[1]]
  eW  <- eWrapper()

  while(TRUE) {
    socketSelect(list(con), FALSE, NULL)
    curMsg <- readBin(con, character(), 1L)

    if(curMsg == .twsIncomingMSG$OPEN_ORDER){
      open_orders[[length(open_orders)+1]]=processMsg(curMsg, con, eW,
                                                      timestamp=NULL,file="")
    } else {
      processMsg(curMsg, con, eW,timestamp=NULL,file="")
    }
    if(curMsg == .twsIncomingMSG$OPEN_ORDER_END)
      break
  }
  return(open_orders)
}