Requesting real-time bars IB API
A simple example how to get real-time bars from the Interactive Brokers API, using package rib.
Load and attach the package first. We set option
warn
to 1, so that any warning is shown at once.
options(warn = 1) ## show warnings at once library("rib")
The main task is to define a wrapper that handles the incoming messages. Here, we simply print the contract, the open and the close.
wrap <- R6::R6Class("IBWrapCustom", class = FALSE, cloneable = FALSE, lock_class = TRUE, inherit = rib::IBWrap, public = list( Data = NULL, initialize = function() { self$Data <- new.env() self$Data$labels <- c("fgbl", "fesx") self$Data$RTbars <- list() }, error = function(id, errorCode, errorString, advancedOrderRejectJson) { ## errors and other messages are shown message(errorString) }, nextValidId = function(orderId) NULL, ## data is ignored managedAccounts = function(accountsList) NULL, ## data is ignored realtimeBar= function(reqId, time, open, high, low, close, volume, wap, count) { message(self$Data$labels[reqId], " | ", .POSIXct(time), " | ", open, " | ", close) } ) )
Create an instance of the wrapper.
wr <- wrap$new()
We define two contracts (see Finding the contract specification).
fgbl <- rib::IBContract( localSymbol = "FGBL 20231207 M", secType = "FUT", currency = "EUR", exchange = "EUREX") fesx <- rib::IBContract( localSymbol = "FSXE 20231215 M", secType = "FUT", currency = "EUR", exchange = "EUREX")
Now we have the ingredients. It remains to get the data. Create a client.
ic <- IBClient$new()
ic$connect(port = 7496, clientId = 1)
ic$checkMsg(wr)
server version: 180 timestamp: 20231130 19:39:30 CET Market data farm connection is OK:.... ## .... and more messages
Now the client requests real-time bars. As said initially, we simply print open and close information for the bars.
ic$reqRealTimeBars(tickerId = 1, contract = fgbl, barSize = 5, whatToShow = "MIDPOINT", useRTH = TRUE) ic$reqRealTimeBars(tickerId = 2, contract = fesx, barSize = 5, whatToShow = "MIDPOINT", useRTH = TRUE) repeat { Sys.sleep(2) ic$checkMsg(wr) }
fgbl | 2023-11-30 19:40:45 | 132.255 | 132.255 fesx | 2023-11-30 19:40:45 | 4392 | 4392 fgbl | 2023-11-30 19:40:50 | 132.255 | 132.255 fesx | 2023-11-30 19:40:50 | 4392 | 4392 fgbl | 2023-11-30 19:40:55 | 132.255 | 132.255 fesx | 2023-11-30 19:40:55 | 4392 | 4392 fgbl | 2023-11-30 19:41:00 | 132.255 | 132.255 fesx | 2023-11-30 19:41:00 | 4392 | 4392 fgbl | 2023-11-30 19:41:05 | 132.255 | 132.255 fesx | 2023-11-30 19:41:05 | 4392 | 4392 ....
Cancel bars for one contract.
ic$cancelRealTimeBars(tickerId = 2)
repeat {
Sys.sleep(2)
ic$checkMsg(wr)
}
fgbl | 2023-11-30 20:32:45 | 132.255 | 132.26 fgbl | 2023-11-30 20:32:50 | 132.26 | 132.26 fgbl | 2023-11-30 20:32:55 | 132.26 | 132.255 fgbl | 2023-11-30 20:33:00 | 132.255 | 132.265 fgbl | 2023-11-30 20:33:05 | 132.265 | 132.26 fgbl | 2023-11-30 20:33:10 | 132.26 | 132.255 fgbl | 2023-11-30 20:33:15 | 132.255 | 132.265 ....
ic$disconnect()