4

I am trying to snap prices in R using the interactive brokers API for the latest price for a list of stocks (around 150). When I snap them for 2 stocks, it's almost instantaneous:

tickers<- c("YHOO","AAPL")
library("IBrokers")
  t_start<-Sys.time()
tws <- twsConnect()
test<-reqMktData(tws, lapply(tickers, twsSTK), tickGenerics="", snapshot=T)
twsDisconnect(tws)
  t_end<-Sys.time()
  t_end-t_start

However, when I start adding more records into the tickers vector, it starts getting incredibly slow. For example:

tickers<-c("YHOO","AAPL","COP","PEP","XOM","ORCL","SPG","EQR","CVX","JPM","AFL","GIS","VZ","KMB","WFC","ROST","MMC")

This becomes excruciatingly slow.

I cannot figure out why it's so slow based on exchange, or size of company, as these are all large cap, highly liquid, blue chip stocks.

Is anyone familiar with why this is so slow?

Thank you very much.

Trexion Kameha
  • 3,362
  • 10
  • 34
  • 60
  • 1
    Don't use `snapshot=T`. Use something like [this](http://www.mail-archive.com/r-sig-finance@stat.math.ethz.ch/msg00927.html). You can see an implementation [here](https://r-forge.r-project.org/scm/viewvc.php/pkg/twsInstrument/R/get_quote.R?view=markup&root=twsinstrument). See also: [here](http://stackoverflow.com/questions/26152138/ibrokers-twsfop-call-in-r) – GSee Dec 18 '14 at 19:45
  • Thanks GSee. I'm fairly new at this, so pardon my ignorance. It looks like reqHistoricalData is what I want, since it downloads the last 30 days of data, with the latest trading day. However, I am not sure how to pass in multiple tickers. This doesn't seem to work. Any thoughts? `tws <- twsConnect() tickers<- c("YHOO","AAPL","FB") reqHistoricalData(tws, lapply(tickers, twsSTK))` – Trexion Kameha Dec 24 '14 at 17:49
  • As you can see from `?reqHistoricalData`, the `Contract` argument takes a single contract, not a list of contracts. You'd have to loop over all the tickers and call `reqHistoricalData` on each one like this `lapply(tickers, reqHistoricalData, conn=tws)`. You might be interested in `twsInstrument::reqTBBOhistory` which will accept a vector of tickers. You can install `twsInstrument` like this `install.packages("twsInstrument", repos="http://r-forge.r-project.org")`, or like this `devtools::install_github("gsee/twsInstrument")` – GSee Dec 24 '14 at 18:13
  • Error in FUN(c("YHOO", "AAPL", "FB")[[1L]], ...) : twsContract required when i run the lapply. – Trexion Kameha Dec 24 '14 at 18:31
  • ok, so that was untested. Here's the idea (also untested): `lapply(tickers, function(x) Sys.sleep(10); reqHistoricalData(tws, twsSTK(x))`. I put Sys.sleep in there because otherwise you'll get a [pacing violation](https://www.interactivebrokers.com/en/software/api/apiguide/tables/historical_data_limitations.htm) as explained in the Note section of `?reqHistoricalData`. `twsInstrument::getBAT()` and `twsInstrument::reqTBBOhistory` have pausing built in. – GSee Dec 24 '14 at 20:00

0 Answers0