2

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

> 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
4

1 回答 1

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)

}
于 2019-06-27T22:53:43.177 回答