如何使用IBrokers在R中获取已执行订单的数据



我正在尝试获取我的历史交易的表现。有谁知道是否有办法拉出像我下面这样的类似表格,但用于历史交易日志?谢谢!

> 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
# 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)
}

相关内容

  • 没有找到相关文章

最新更新