R IBrokers reqOpenOrders hangs



有人能建议如何正确使用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提示符。谢谢

我想我得到了。该功能需要在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)

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

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中几乎所有其他功能看起来都是如此,只是其中一些已经实现了。

我在包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)
}

相关内容

  • 没有找到相关文章

最新更新