如何使用IBrokers获取R中已填充订单的数据?

时间:2017-03-19 23:31:13

标签: r quantitative-finance algorithmic-trading interactive-brokers ibrokers

我正在尝试获取历史交易的表现。有没有人知道是否有办法拉下类似的表,如下所示,但对于历史贸易日志?谢谢!

> tws <- twsConnect()
> ac <- reqAccountUpdates(tws)
> position <- twsPortfolioValue(ac) ##current portfolio holdings
> position
    local sectype marketValue averageCost       return position realizedPNL unrealizedPNL
1     ABC     STK      xxxxx     xxxxxxx  -0.006855236        9           0         -4.52
2     USD    CASH     xxxxxxx    xxxxxxxx -0.004634901     3733           0        -23.19

1 个答案:

答案 0 :(得分:0)

# This function will create 2 dataframes: one with account information, another with the live trades. You can always keep a log of the trades

IB.Account.Status <- function(tws, acctCode)
{
library(IBrokers)

cancelAccountUpdates(tws)
d <- reqAccountUpdates(conn = tws, acctCode, subscribe = TRUE)
assign("IB.account", data.frame(t(sapply(d[[1]],c)), stringsAsFactors = FALSE), envir = .GlobalEnv)

d2 <- d[[2]]
IB.contracts <- data.frame()
for(i in 1:length(d2))
{
 x <- bind_cols(data.frame(t(sapply(d2[[i]][1][[1]],c)), stringsAsFactors = FALSE),
 data.frame(t(sapply(d2[[i]][2][[1]],c)), stringsAsFactors = FALSE) )

IB.contracts <- bind_rows(IB.contracts, x)
rm(x, i)
}

IB.contracts <- IB.contracts[c("accountName", "conId", "symbol", "position", "marketPrice", "marketValue", "averageCost", "unrealizedPNL", "realizedPNL", "local", "currency", "exch", "primary", "sectype", "expiry", "strike", "right", "multiplier", "combo_legs_desc", "comboleg", "include_expired", "secIdType", "secId")]

cols.to.numeric <- c("strike", "right", "position", "marketPrice", "marketValue", "averageCost", "unrealizedPNL")

IB.contracts[cols.to.numeric] <- as.numeric(as.matrix(IB.contracts[cols.to.numeric]))

assign("IB.contracts", IB.contracts, envir = .GlobalEnv)
rm(d, d2, cols.to.numeric)

}