0
我正在嘗試創建當前期權代碼的期權鏈(期權的每次罷工,每期到期)。並行請求歷史期權價格/ IBrokers最後已知價格(R)
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合同。
不幸的** reqRealTimeBars **似乎遭受** reqMktData()的同樣問題** 就我看不到市場結束時提供的答案。而如果市場尚未公開,我希望報告最新的已知價格。 – Jav
您是否嘗試過使用useRTH? reqHistoricalData(tws,AA [[1]] $ contract,whatToShow ='BID',barSize =「1min」,duration =「60S」,useRTH = 0) –