【发布时间】:2016-02-11 14:21:22
【问题描述】:
我正在尝试为股票代码创建 当前 期权链(每次行使价、每次到期的期权)。
library(IBrokers)
tws <- twsConnect()
# Lets say only Call prices
AA <- reqContractDetails(tws, twsOption(local="", right="C", symbol="AAPL"))
使用 snapshot 的原生实现太慢了:
reqMktData(tws, AA[1:2], snapshot = TRUE)
每个合约大约等待 11 sec(当前合约数量为 626)
另一种实现:
snapShot <- function (twsCon, eWrapper, timestamp, file, playback = 1, ...)
{
if (missing(eWrapper))
eWrapper <- eWrapper()
names(eWrapper$.Data$data) <- eWrapper$.Data$symbols
con <- twsCon[[1]]
if (inherits(twsCon, "twsPlayback")) {
sys.time <- NULL
while (TRUE) {
if (!is.null(timestamp)) {
last.time <- sys.time
sys.time <- as.POSIXct(strptime(paste(readBin(con,
character(), 2), collapse = " "), timestamp))
if (!is.null(last.time)) {
Sys.sleep((sys.time - last.time) * playback)
}
curMsg <- .Internal(readBin(con, "character",
1L, NA_integer_, TRUE, FALSE))
if (length(curMsg) < 1)
next
processMsg(curMsg, con, eWrapper, format(sys.time,
timestamp), file, ...)
}
else {
curMsg <- readBin(con, character(), 1)
if (length(curMsg) < 1)
next
processMsg(curMsg, con, eWrapper, timestamp,
file, ...)
if (curMsg == .twsIncomingMSG$REAL_TIME_BARS)
Sys.sleep(5 * playback)
}
}
}
else {
evalWithTimeout(
while (TRUE) {
socketSelect(list(con), FALSE, NULL)
curMsg <- .Internal(readBin(con, "character", 1L,
NA_integer_, TRUE, FALSE))
if (!is.null(timestamp)) {
processMsg(curMsg, con, eWrapper, format(Sys.time(),
timestamp), file, ...)
}
else {
processMsg(curMsg, con, eWrapper, timestamp,
file, ...)
}
if (!any(sapply(eWrapper$.Data$data, is.na)))
return(do.call(rbind, lapply(eWrapper$.Data$data,
as.data.frame)))
}, timeout=5, onTimeout="warning")
}
}
reqMktData(tws, AA[1:20], eventWrapper=eWrapper.data(20),CALLBACK=snapShot)
它避免了等待(11 秒)。
但如果没有实时数据或市场关闭,这将不起作用。
因此,即使市场关闭,我也只想获得最后一个已知价格。
这是我的伪解决方案:
reqHistoricalData(tws, AA[[1]]$contract, whatToShow='BID', barSize = "1 min", duration = "60 S")
有没有办法让这个解决方案并行化,这样它会要求几个合约的历史价格?
目前每个合约的花费约为 2.3 seconds,而之前的解决方案能够在花费相同的时间获得 20-30 个合约。
【问题讨论】:
标签: r concurrent-programming algorithmic-trading stockquotes ibrokers