Wednesday, April 14, 2010

R with Interactive Brokers' TWS or TWS gateway

1. Start Interactive Brokers' TWS or TWS gateway.
2. Start R and load Interactive Brokers module.
    >require(IBrokers)       or   >library(IBrokers)
3. Connect to Interactive Brokers' TWS.
    >tws<-twsConnect()
4. Create the contract
    >cont<-twsSTK("IBM")   # this is for stock
    >cont<-twsFUT("YM","ECBOT","201006")
5. Stock or future data can be requested by any of the following data:
    a) Use the following code to request for historical data:
        >data<-reqHistoricalData(tws,cont)
    b) Use the below code to request for market data:
        >data<-reqMktData(tws,cont)
        * when requesting market data the code will appear hanging as it is waiting for the market data feed. Need to spawn separate thread to handle the market data.
    c) Use the below code to request for market depth:
        >data<-reqMktDepth(tws,cont)
6. The data can be charted using chartSeries, plot ... etc.

No comments:

Post a Comment