1

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

4

2 回答 2

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

于 2016-01-12T15:15:18.767 回答
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)
}
于 2019-10-13T15:27:40.363 回答