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