Skip to content

ibrokers - callback - example from Jeff Ryan's slides

3 messages · Stephen Choularton, Jeff Ryan

#
I'm trying to make this work (its based on an example from Jeff Ryan's 
slides):

library(IBrokers)


myCALLBACK <-
function(twsCon, eWrapper, timestamp, file, playback = 1, ...) {
     twsOC <- twsConnect(2) # our order connection
     ocWrapper <- eWrapper(TRUE)
     traded <- FALSE
     while (TRUE) {
         cons <- socketSelect(list(con, twsOC[[1]]), FALSE, 0.01)
         if(cons[1]) { #data
             curMsg <- readBin(con, character(), 1)
             if (!is.null(timestamp)) {
                 processMsg(curMsg, con, eWrapper, format(Sys..time(), 
timestamp), file, ...)
             } else {
                 processMsg(curMsg, con, eWrapper, timestamp, file, ...)
             }
         } else if(cons[2]) {
             curMsg <- readBin(twsOC[[1]], character(), 1)
             if (!is.null(timestamp)) {
                 processMsg(curMsg, twsOC[[1]], ocWrapper, 
format(Sys..time(), timestamp), file, ...)
             } else {
                 processMsg(curMsg, twsOC[[1]], ocWrapper, timestamp, 
file, ...)
             }
         } # TRADE LOGIC HERE
         curBID <- as.numeric(eWrapper$.Data$data[[1]][3])
         if(!traded && !is.na(curBID) && curBID > 141.00) {

             print("this is the order line")
             # IBrokers:::.placeOrder(twsOC, 
twsEquity("CBA","ASX","AUD"), twsOrder(1053, "BUY", "0", "MKT"))
             traded <- TRUE
         }
     }
}

con = twsConnect(1)



reqMktData(con, twsEquity("GOOG"), CALLBACK=myCALLBACK)

but I get:

Error in socketSelect(list(con, twsOC[[1]]), FALSE, 0.01) :
   invalid connection

Does anyone know what I am doing wrong? Or does anyone have a working 
example?

my  sessionInfo() is
R version 2.11.1 (2010-05-31)
i386-pc-mingw32

locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] IBrokers_0.2-9 xts_0.7-5      zoo_1.6-4

loaded via a namespace (and not attached):
[1] grid_2.11.1    lattice_0.18-8
#
Sorry I don't have the time to walk you through this, but for starters you can just remove the second connection from the mix. 

The general placement of the logic should be correct though. 

Jeff

Jeffrey Ryan    |    Founder    |    jeffrey.ryan at lemnica.com

www.lemnica.com
On Dec 4, 2010, at 4:07 AM, Stephen Choularton <stephen at organicfoodmarkets.com.au> wrote:

            
#
Note also that you need to upgrade your IBrokers package to the current CRAN release. 

Best,
Jeff

Jeffrey Ryan    |    Founder    |    jeffrey.ryan at lemnica.com

www.lemnica.com
On Dec 4, 2010, at 4:07 AM, Stephen Choularton <stephen at organicfoodmarkets.com.au> wrote: