使用reqMktDepth进行R交易

时间:2018-02-28 20:39:30

标签: r real-time trading ibrokers

我正在尝试使用R测试日内交易策略,并且我找到了IBrokers API包,它将订单发送到Interactive Brokers TWS platrform,这对我来说是完美的。不幸的是,我的编程技巧并不适合完成任务!

无论如何,我的策略是查看市场深度,以高于和低于市场价格的价格下单,这些价格取决于出价和询问的大小。

从我所学到的,到目前为止,我相信reqMktDepth函数会创建一个无限循环来更新出价并通过twsCALLBACK询问。

我尝试做的是创建一个名为callback.intraday的函数,它执行我的交易策略,然后调用twsCALLBACK,从我理解的应该使用reqMktDepth并在其中使用我的函数

以下是我的功能代码:

callback.intraday <- function(numoflots=50, file=f, lenghtofdepth=10, target=0.30, mintick=0.01){
  csvfile <- na.omit(read.delim(file=file, sep=" ", stringsAsFactors = FALSE, col.names=c("date", "time", "NA", "NA", "NA", "position", "operation", "bid.ask", "price", "size", "NA")))
  csvfile <- csvfile[1:(lenghtofdepth*2),]
  csvfile <- csvfile[order(csvfile$position),]

  #0 is ask, 1 is bid
  askdepth <- biddepth<- 0  
  for (i in 1:nrow(csvfile)){

    if(!csvfile$position[i]==0 && csvfile$bid.ask[i]==1 && askdepth<numoflots){
      askdepth <- askdepth+as.numeric(csvfile$size[i])
      buyprice <- as.numeric(csvfile$price[i])-mintick
    }

    if(!csvfile$position[i]==0 && csvfile$bid.ask[i]==0 && biddepth<numoflots){
      biddepth <- biddepth+as.numeric(csvfile$size[i])
      sellprice <- as.numeric(csvfile$price[i])+mintick
    }


  }


  #entering buyside
  #ids <- as.numeric(reqIds(tws))
  #entorder <- twsOrder(ids,"BUY", "1", "STPLMT", lmtPrice = buyprice, auxPrice = buyprice+2*mintick)
  #ids <- as.numeric(reqIds(tws))
  #tarorder <- twsOrder(ids,"SELL", "1", "LMT", lmtPrice = buyprice+target)
  #placeOrder(twsconn=tws, Contract=security, Order=entorder)
  #placeOrder(twsconn=tws, Contract=security, Order=tarorder)

  #entering sellside
  #ids <- as.numeric(reqIds(tws))
  #entorder <- twsOrder(ids,"SELL", "1", "STPLMT", lmtPrice = sellprice, auxPrice = sellprice+2*mintick)
  #ids <- as.numeric(reqIds(tws))
  #tarorder <- twsOrder(ids,"BUY", "1", "LMT", lmtPrice = sellprice-target)
  #placeOrder(twsconn=tws, Contract=security, Order=entorder)
  #placeOrder(twsconn=tws, Contract=security, Order=tarorder)

  twsCALLBACK(twsCon = tws)
}

我还没有测试过将订单发送到市场,因为我仍然坚持使用循环。

以下是我正在运行的代码并收到“未使用的参数”错误。

    require(IBrokers)
tws <- twsConnect(port=7496)
isConnected(tws)
symb <- "CL"
exchange <- "NYMEX"
expiry <- "201804"
f <- "C:/Users/augus/Dropbox/Trading/R/Trading/Intraday/depth.csv"
contract <- twsFuture(symbol=symb, exch=exchange, expiry=expiry)

reqMktDepth(tws, contract, file=f, CALLBACK = callback.intraday)

感谢您的帮助

奥古斯托

0 个答案:

没有答案