├── inst └── proto │ ├── TagValue.proto │ ├── OrderBound.proto │ ├── Error.proto │ ├── CompletedOrder.proto │ ├── OpenOrder.proto │ ├── OrderCancel.proto │ ├── SingleField.proto │ ├── OrderStatus.proto │ ├── PlaceOrderRequest.proto │ ├── OrderCondition.proto │ ├── SecDefOptParam.proto │ ├── RealTimeBars.proto │ ├── PnL.proto │ ├── MarketDepth.proto │ ├── MiscData.proto │ ├── MarketData.proto │ ├── Scanner.proto │ ├── News.proto │ ├── Contract.proto │ ├── Execution.proto │ ├── OrderState.proto │ ├── MiscRequests.proto │ ├── Account.proto │ ├── TickData.proto │ ├── HistoricalData.proto │ ├── ContractDetails.proto │ └── Order.proto ├── R ├── zzz.R ├── constants.R ├── factory.R ├── enums.R ├── protoutils.R ├── codes.R ├── IBWrap.R ├── structs.R ├── IBClient.R └── decode.R ├── NEWS.md ├── NAMESPACE ├── DESCRIPTION ├── man ├── enums.Rd ├── rib-package.Rd ├── structs.Rd ├── factory.Rd ├── IBClient.Rd └── IBWrap.Rd ├── README.md ├── examples └── IBWrapSimple.R └── LICENSE /inst/proto/TagValue.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | message TagValue { 6 | optional string key = 1; 7 | optional string value = 2; 8 | } 9 | -------------------------------------------------------------------------------- /R/zzz.R: -------------------------------------------------------------------------------- 1 | .onLoad <- function(libname, pkgname) { 2 | 3 | # ProtoBuf 4 | RProtoBuf::readProtoFiles2(protoPath=system.file("proto", package=pkgname, lib.loc=libname)) 5 | 6 | options("RProtoBuf.int64AsString" = TRUE) 7 | } 8 | -------------------------------------------------------------------------------- /inst/proto/OrderBound.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | message OrderBound { 6 | optional int64 permId = 1; 7 | optional int32 clientId = 2; 8 | optional int32 orderId = 3; 9 | } 10 | -------------------------------------------------------------------------------- /inst/proto/Error.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | message Error { 6 | optional int32 id = 1; 7 | optional int64 errorTime = 2; 8 | optional int32 errorCode = 3; 9 | optional string errorString = 4; 10 | optional string advancedOrderRejectJson = 5; 11 | } 12 | -------------------------------------------------------------------------------- /inst/proto/CompletedOrder.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "Contract.proto"; 6 | import "Order.proto"; 7 | import "OrderState.proto"; 8 | 9 | message CompletedOrder { 10 | optional Contract contract = 1; 11 | optional Order order = 2; 12 | optional OrderState orderState = 3; 13 | } 14 | -------------------------------------------------------------------------------- /inst/proto/OpenOrder.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "Contract.proto"; 6 | import "Order.proto"; 7 | import "OrderState.proto"; 8 | 9 | message OpenOrder { 10 | optional int32 orderId = 1; 11 | optional Contract contract = 2; 12 | optional Order order = 3; 13 | optional OrderState orderState = 4; 14 | } 15 | -------------------------------------------------------------------------------- /NEWS.md: -------------------------------------------------------------------------------- 1 | # rib 0.25.3 2 | 3 | * Update to API v199 4 | 5 | # rib 0.23.1 6 | 7 | * Update to API v193 8 | 9 | # rib 0.20.0 10 | 11 | * Update to API v184 12 | 13 | # rib 0.19.3 14 | 15 | * Update to API v179 16 | 17 | # rib 0.19.0 18 | 19 | * Update to API v177 20 | * Drop support for API < v176 21 | * Bugs fixes 22 | 23 | # rib 0.18.2 24 | 25 | * Submission to CRAN 26 | -------------------------------------------------------------------------------- /inst/proto/OrderCancel.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | message OrderCancel { 6 | optional string manualOrderCancelTime = 1; 7 | optional string extOperator = 2; 8 | optional int32 manualOrderIndicator = 3; 9 | } 10 | 11 | message CancelOrderRequest { 12 | optional int32 orderId = 1; 13 | optional OrderCancel orderCancel = 2; 14 | } 15 | 16 | message GlobalCancelRequest { 17 | optional OrderCancel orderCancel = 1; 18 | } 19 | -------------------------------------------------------------------------------- /inst/proto/SingleField.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | message SingleInt32 { 6 | optional int32 value = 1; 7 | } 8 | 9 | message SingleInt64 { 10 | optional int64 value = 1; 11 | } 12 | 13 | message SingleBool { 14 | optional bool value = 1; 15 | } 16 | 17 | message SingleString { 18 | optional string value = 1; 19 | } 20 | 21 | message StringData { 22 | optional int32 reqId = 1; 23 | optional string data = 2; 24 | } 25 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | importFrom(R6, R6Class) 2 | 3 | # Main classes 4 | export(IBClient) 5 | export(IBWrap) 6 | 7 | # Helpers 8 | export(IBContract) 9 | export(IBOrder) 10 | export(fCondition) 11 | export(map_enum2int) 12 | export(map_int2enum) 13 | 14 | # Structs 15 | export(ComboLeg) 16 | export(Contract) 17 | export(DeltaNeutralContract) 18 | export(ExecutionFilter) 19 | export(Order) 20 | export(OrderCancel) 21 | export(ScannerSubscription) 22 | export(SoftDollarTier) 23 | export(WshEventData) 24 | -------------------------------------------------------------------------------- /inst/proto/OrderStatus.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | message OrderStatus { 6 | optional int32 orderId = 1; 7 | optional string status = 2; 8 | optional string filled = 3; 9 | optional string remaining = 4; 10 | optional double avgFillPrice = 5; 11 | optional int64 permId = 6; 12 | optional int32 parentId = 7; 13 | optional double lastFillPrice = 8; 14 | optional int32 clientId = 9; 15 | optional string whyHeld = 10; 16 | optional double mktCapPrice = 11; 17 | } 18 | -------------------------------------------------------------------------------- /inst/proto/PlaceOrderRequest.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "Contract.proto"; 6 | import "Order.proto"; 7 | 8 | message AttachedOrders { 9 | optional int32 slOrderId = 1; 10 | optional string slOrderType = 2; 11 | optional int32 ptOrderId = 3; 12 | optional string ptOrderType = 4; 13 | } 14 | 15 | message PlaceOrderRequest { 16 | optional int32 orderId = 1; 17 | optional Contract contract = 2; 18 | optional Order order = 3; 19 | optional AttachedOrders attachedOrders = 4; 20 | } 21 | -------------------------------------------------------------------------------- /inst/proto/OrderCondition.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | message OrderCondition { 6 | optional int32 type = 1; 7 | optional bool isConjunction = 2; 8 | optional bool isMore = 3; 9 | optional int32 conId = 4; 10 | optional string exchange = 5; 11 | optional string symbol = 6; 12 | optional string secType = 7; 13 | optional int32 percent = 8; 14 | optional double changePercent = 9; 15 | optional double price = 10; 16 | optional int32 triggerMethod = 11; 17 | optional string time = 12; 18 | optional int32 volume = 13; 19 | } 20 | -------------------------------------------------------------------------------- /inst/proto/SecDefOptParam.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | message SecDefOptParamsRequest { 6 | optional int32 reqId = 1; 7 | optional string underlyingSymbol = 2; 8 | optional string futFopExchange = 3; 9 | optional string underlyingSecType = 4; 10 | optional int32 underlyingConId = 5; 11 | } 12 | 13 | message SecDefOptParameter { 14 | optional int32 reqId = 1; 15 | optional string exchange = 2; 16 | optional int32 underlyingConId = 3; 17 | optional string tradingClass = 4; 18 | optional string multiplier = 5; 19 | repeated string expirations = 6; 20 | repeated double strikes = 7; 21 | } 22 | -------------------------------------------------------------------------------- /R/constants.R: -------------------------------------------------------------------------------- 1 | # 2 | # Some constants 3 | # 4 | API_SIGN <- writeBin("API", raw()) # "API\0" (the null termination is added automatically by writeBin() 5 | 6 | HEADER_LEN <- 4L 7 | MAX_MSG_LEN <- 0xFFFFFFL # 16Mb - 1b 8 | 9 | RAWID_LEN <- 4L 10 | PROTOBUF_MSG_ID <- 200L 11 | 12 | # Server Versions 13 | MIN_SERVER_VER_ADD_Z_SUFFIX_TO_UTC_DATE_TIME <- 214L 14 | MIN_SERVER_VER_CANCEL_CONTRACT_DATA <- 215L 15 | MIN_SERVER_VER_ADDITIONAL_ORDER_PARAMS_1 <- 216L 16 | MIN_SERVER_VER_ADDITIONAL_ORDER_PARAMS_2 <- 217L 17 | MIN_SERVER_VER_ATTACHED_ORDERS <- 218L 18 | 19 | 20 | MIN_CLIENT_VER <- 213L 21 | MAX_CLIENT_VER <- MIN_SERVER_VER_ATTACHED_ORDERS 22 | -------------------------------------------------------------------------------- /inst/proto/RealTimeBars.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "Contract.proto"; 6 | import "TagValue.proto"; 7 | 8 | message RealTimeBarsRequest { 9 | optional int32 reqId = 1; 10 | optional Contract contract = 2; 11 | optional int32 barSize = 3; 12 | optional string whatToShow = 4; 13 | optional bool useRTH = 5; 14 | repeated TagValue realTimeBarsOptions = 6; 15 | } 16 | 17 | message RealTimeBarTick { 18 | optional int32 reqId = 1; 19 | optional int64 time = 2; 20 | optional double open = 3; 21 | optional double high = 4; 22 | optional double low = 5; 23 | optional double close = 6; 24 | optional string volume = 7; 25 | optional string wap = 8; 26 | optional int32 count = 9; 27 | } 28 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: rib 2 | Title: An Implementation of 'Interactive Brokers' API 3 | Version: 0.30.2 4 | Authors@R: person("Luca", "Billi", email = "noreply.section+dev@gmail.com", role = c("aut", "cre")) 5 | Description: Allows interaction with 'Interactive Brokers' 'Trader Workstation' 6 | . 7 | Handles the connection over the network and the exchange of messages. 8 | Data is encoded and decoded between user and wire formats. 9 | Data structures and functionality closely mirror the official implementations. 10 | Depends: 11 | R (>= 3.4) 12 | Imports: 13 | R6 (>= 2.4), 14 | RProtoBuf 15 | License: GPL-3 16 | Encoding: UTF-8 17 | URL: https://github.com/lbilli/rib 18 | BugReports: https://github.com/lbilli/rib/issues 19 | -------------------------------------------------------------------------------- /inst/proto/PnL.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | message PnLRequest { 6 | optional int32 reqId = 1; 7 | optional string account = 2; 8 | optional string modelCode = 3; 9 | } 10 | 11 | message PnL { 12 | optional int32 reqId = 1; 13 | optional double dailyPnL = 2; 14 | optional double unrealizedPnL = 3; 15 | optional double realizedPnL = 4; 16 | } 17 | 18 | message PnLSingleRequest { 19 | optional int32 reqId = 1; 20 | optional string account = 2; 21 | optional string modelCode = 3; 22 | optional int32 conId = 4; 23 | } 24 | 25 | message PnLSingle { 26 | optional int32 reqId = 1; 27 | optional string position = 2; 28 | optional double dailyPnL = 3; 29 | optional double unrealizedPnL = 4; 30 | optional double realizedPnL = 5; 31 | optional double value = 6; 32 | } 33 | -------------------------------------------------------------------------------- /man/enums.Rd: -------------------------------------------------------------------------------- 1 | \name{enums} 2 | \title{Enumerated Types} 3 | \alias{map_enum2int} 4 | \alias{map_int2enum} 5 | 6 | \description{ 7 | Enumerated types are used in few places across the API. 8 | These are types that can have only a limited set of named 9 | constant values. 10 | 11 | These functions facilitate the conversion between integer value 12 | and string representation. 13 | } 14 | 15 | \usage{ 16 | map_enum2int(enum, name) 17 | 18 | map_int2enum(enum, value) 19 | } 20 | 21 | \arguments{ 22 | \item{enum}{name of the enumeration type: \emph{e.g.} \code{"Condition"}, 23 | \code{"FaDataType"}, \code{"MarketData"}, \code{"PriceTrigger"}.} 24 | 25 | \item{name}{string representation of \code{value}.} 26 | 27 | \item{value}{integer representation of \code{name}.} 28 | } 29 | 30 | \value{ 31 | \code{map_enum2int} returns the corresponding \code{value}. 32 | 33 | \code{map_int2enum} returns the corresponding \code{name}. 34 | } 35 | 36 | \examples{ 37 | map_enum2int("MarketData", "DELAYED") # -> 3 38 | 39 | map_int2enum("MarketData", 3) # -> "DELAYED" 40 | } 41 | -------------------------------------------------------------------------------- /man/rib-package.Rd: -------------------------------------------------------------------------------- 1 | \name{rib-package} 2 | \alias{rib-package} 3 | \alias{rib} 4 | \docType{package} 5 | 6 | \title{An Implementation of 'Interactive Brokers' API} 7 | 8 | \description{ 9 | \pkg{rib} allows programs to interact with 'Interactive Brokers' (IB) 10 | 'Trader Workstation' (TWS). 11 | It establishes a connection over the network and manages 12 | the exchange of messages between client and server. 13 | Data is encoded and decoded between user and wire formats 14 | following closely the official implementations. 15 | } 16 | 17 | \details{ 18 | The package design mirrors the implementations that 19 | 'Interactive Brokers' makes available for other languages, 20 | such as C++, C#, Java and Python. 21 | 22 | The official IB documentation is therefore the most valuable reference regarding 23 | the API functionality and usage. 24 | } 25 | 26 | \seealso{ 27 | \url{https://github.com/lbilli/rib} 28 | 29 | Report bugs at \url{https://github.com/lbilli/rib/issues} 30 | 31 | The official 32 | \href{https://interactivebrokers.github.io/tws-api/}{IB API documentation}. 33 | } 34 | 35 | \keyword{internal} 36 | -------------------------------------------------------------------------------- /man/structs.Rd: -------------------------------------------------------------------------------- 1 | \name{structs} 2 | \title{Data Structures} 3 | \alias{ComboLeg} 4 | \alias{Contract} 5 | \alias{DeltaNeutralContract} 6 | \alias{ExecutionFilter} 7 | \alias{Order} 8 | \alias{OrderCancel} 9 | \alias{ScannerSubscription} 10 | \alias{SoftDollarTier} 11 | \alias{WshEventData} 12 | \docType{data} 13 | 14 | \description{ 15 | The data structures used by the API are implemented as \R named lists, 16 | possibly nested. 17 | Templates filled with default values are defined within the package. 18 | In order to instantiate them, no elaborate contructor is required but 19 | a simple copy will do. 20 | 21 | Still, \link[=IBContract]{helper functions} are available for \code{Contract} and \code{Order}. 22 | } 23 | 24 | \usage{ 25 | ComboLeg 26 | 27 | Contract 28 | 29 | DeltaNeutralContract 30 | 31 | ExecutionFilter 32 | 33 | Order 34 | 35 | OrderCancel 36 | 37 | ScannerSubscription 38 | 39 | SoftDollarTier 40 | 41 | WshEventData 42 | } 43 | 44 | \seealso{ 45 | \code{\link{IBContract}}, \code{\link{IBOrder}}. 46 | } 47 | 48 | \examples{ 49 | stock <- Contract 50 | 51 | stock$symbol <- "GOOG" 52 | stock$secType <- "STK" 53 | stock$exchange <- "SMART" 54 | stock$currency <- "USD" 55 | } 56 | -------------------------------------------------------------------------------- /R/factory.R: -------------------------------------------------------------------------------- 1 | # 2 | # Helper functions to generate IB structs 3 | # 4 | 5 | setfields <- function(s, ...) 6 | { 7 | args <- list(...) 8 | 9 | k <- names(args) 10 | 11 | stopifnot(!is.null(k)) 12 | 13 | idx <- match(k, names(s)) 14 | 15 | stopifnot(!is.na(idx)) 16 | 17 | s[idx] <- args 18 | 19 | s 20 | } 21 | 22 | IBContract <- function(...) setfields(Contract, ...) 23 | 24 | IBOrder <- function(...) setfields(Order, ...) 25 | 26 | # 27 | # Generate Condition structs 28 | # 29 | fCondition <- function(type) 30 | { 31 | stopifnot(is.character(type)) 32 | 33 | res <- switch(type, 34 | Price= list(isMore= FALSE, price= 0, conId= 0L, exchange= "", triggerMethod= 0L), 35 | Time= list(isMore= FALSE, time= ""), 36 | Margin= list(isMore= FALSE, percent= 0L), 37 | Execution= list(secType= "", exchange= "", symbol= ""), 38 | Volume= list(isMore= FALSE, volume= 0L, conId= 0L, exchange= ""), 39 | PercentChange= list(isMore= FALSE, changePercent= NA_real_, conId= 0L, exchange= ""), 40 | stop("unknown Condition type")) 41 | 42 | c(type=type, conjunction="o", res) 43 | } 44 | -------------------------------------------------------------------------------- /inst/proto/MarketDepth.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "Contract.proto"; 6 | import "TagValue.proto"; 7 | 8 | message MarketDepthRequest { 9 | optional int32 reqId = 1; 10 | optional Contract contract = 2; 11 | optional int32 numRows = 3; 12 | optional bool isSmartDepth = 4; 13 | repeated TagValue mktDepthOptions = 5; 14 | } 15 | 16 | message CancelMarketDepth { 17 | optional int32 reqId = 1; 18 | optional bool isSmartDepth = 2; 19 | } 20 | 21 | message MarketDepthData { 22 | optional int32 position = 1; 23 | optional int32 operation = 2; 24 | optional int32 side = 3; 25 | optional double price = 4; 26 | optional string size = 5; 27 | optional string marketMaker = 6; 28 | optional bool isSmartDepth = 7; 29 | } 30 | 31 | message MarketDepth { 32 | optional int32 reqId = 1; 33 | optional MarketDepthData marketDepthData = 2; 34 | } 35 | 36 | message DepthMarketDataDescription { 37 | optional string exchange = 1; 38 | optional string secType = 2; 39 | optional string listingExch = 3; 40 | optional string serviceDataType = 4; 41 | optional int32 aggGroup = 5; 42 | } 43 | 44 | message MarketDepthExchanges { 45 | repeated DepthMarketDataDescription depthMktDataDescriptions = 1; 46 | } 47 | -------------------------------------------------------------------------------- /inst/proto/MiscData.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "Contract.proto"; 6 | 7 | message FamilyCode { 8 | optional string accountId = 1; 9 | optional string familyCode = 2; 10 | } 11 | 12 | message FamilyCodes { 13 | repeated FamilyCode familyCodes = 1; 14 | } 15 | 16 | message PriceIncrement { 17 | optional double lowEdge = 1; 18 | optional double increment = 2; 19 | } 20 | 21 | message MarketRule { 22 | optional int32 marketRuleId = 1; 23 | repeated PriceIncrement priceIncrements = 2; 24 | } 25 | 26 | message Reroute { 27 | optional int32 reqId = 1; 28 | optional int32 conId = 2; 29 | optional string exchange = 3; 30 | } 31 | 32 | message SmartComponent { 33 | optional int32 bit = 1; 34 | optional string exchange = 2; 35 | optional string exchangeLetter = 3; 36 | } 37 | 38 | message SmartComponents { 39 | optional int32 reqId = 1; 40 | repeated SmartComponent map = 2; 41 | } 42 | 43 | message SoftDollarTier { 44 | optional string name = 1; 45 | optional string val = 2; 46 | optional string displayName = 3; 47 | } 48 | 49 | message SoftDollarTiers { 50 | optional int32 reqId = 1; 51 | repeated SoftDollarTier tiers = 2; 52 | } 53 | 54 | message ContractDescription { 55 | optional Contract contract = 1; 56 | repeated string derivativeSecTypes = 2; 57 | } 58 | 59 | message SymbolSamples { 60 | optional int32 reqId = 1; 61 | repeated ContractDescription contractDescriptions = 2; 62 | } 63 | 64 | message VerifyCompleted { 65 | optional bool isSuccessful = 1; 66 | optional string errorText = 2; 67 | } 68 | -------------------------------------------------------------------------------- /man/factory.Rd: -------------------------------------------------------------------------------- 1 | \name{factory} 2 | \title{Helpers} 3 | \alias{IBContract} 4 | \alias{IBOrder} 5 | \alias{fCondition} 6 | 7 | \description{ 8 | Helper functions that simplify the customization of common data structures. 9 | } 10 | 11 | \usage{ 12 | IBContract(\dots) 13 | 14 | IBOrder(\dots) 15 | 16 | fCondition(type) 17 | } 18 | 19 | \arguments{ 20 | \item{\dots}{Any combination of named arguments whose names are valid for 21 | \code{Contract} or \code{Order} respectively.} 22 | 23 | \item{type}{Type of condition: one of \code{"Price"}, \code{"Time"}, 24 | \code{"Margin"}, \code{"Execution"}, \code{"Volume"} or 25 | \code{"PercentChange"}.} 26 | } 27 | 28 | \details{ 29 | The same result is achieved by making a copy of the respective structures 30 | and explicitly reassigning values to the desired fields. 31 | The two approaches can be complementary. 32 | } 33 | 34 | \value{ 35 | \code{IBContract} returns a \code{Contract}. 36 | 37 | \code{IBOrder} returns an \code{Order}. 38 | 39 | \code{fCondition} returns a \code{Condition}. 40 | } 41 | 42 | \seealso{ 43 | \code{\link{Contract}}, \code{\link{Order}}. 44 | } 45 | 46 | \examples{ 47 | stock <- IBContract(symbol="GOOG", secType="STK", exchange="SMART", currency="USD") 48 | 49 | # Equivalent to 50 | stock <- Contract 51 | stock$symbol <- "GOOG" 52 | stock$secType <- "STK" 53 | stock$exchange <- "SMART" 54 | stock$currency <- "USD" 55 | 56 | order <- IBOrder(action="BUY", totalQuantity=10, orderType="LMT", lmtPrice=99) 57 | 58 | condition <- fCondition("Time") 59 | condition$is_more <- TRUE 60 | condition$value <- "20221114-12:00" 61 | } 62 | -------------------------------------------------------------------------------- /inst/proto/MarketData.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "Contract.proto"; 6 | import "TagValue.proto"; 7 | 8 | message MarketDataRequest { 9 | optional int32 reqId = 1; 10 | optional Contract contract = 2; 11 | optional string genericTicks = 3; 12 | optional bool snapshot = 4; 13 | optional bool regulatorySnapshot = 5; 14 | repeated TagValue mktDataOptions = 6; 15 | } 16 | 17 | message TickPrice { 18 | optional int32 reqId = 1; 19 | optional int32 tickType = 2; 20 | optional double price = 3; 21 | optional string size = 4; 22 | optional int32 attrMask = 5; 23 | } 24 | 25 | message TickGeneric { 26 | optional int32 reqId = 1; 27 | optional int32 tickType = 2; 28 | optional double value = 3; 29 | } 30 | 31 | message TickString { 32 | optional int32 reqId = 1; 33 | optional int32 tickType = 2; 34 | optional string value = 3; 35 | } 36 | 37 | message TickOptionComputation { 38 | optional int32 reqId = 1; 39 | optional int32 tickType = 2; 40 | optional int32 tickAttrib = 3; 41 | optional double impliedVol = 4; 42 | optional double delta = 5; 43 | optional double optPrice = 6; 44 | optional double pvDividend = 7; 45 | optional double gamma = 8; 46 | optional double vega = 9; 47 | optional double theta = 10; 48 | optional double undPrice = 11; 49 | } 50 | 51 | message MarketDataType { 52 | optional int32 reqId = 1; 53 | optional int32 marketDataType = 2; 54 | } 55 | 56 | message TickReqParams { 57 | optional int32 reqId = 1; 58 | optional string minTick = 2; 59 | optional string bboExchange = 3; 60 | optional int32 snapshotPermissions = 4; 61 | } 62 | -------------------------------------------------------------------------------- /inst/proto/Scanner.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "Contract.proto"; 6 | import "TagValue.proto"; 7 | 8 | message ScannerSubscription { 9 | optional int32 numberOfRows = 1; 10 | optional string instrument = 2; 11 | optional string locationCode = 3; 12 | optional string scanCode = 4; 13 | optional double abovePrice = 5; 14 | optional double belowPrice = 6; 15 | optional int64 aboveVolume = 7; 16 | optional double marketCapAbove = 8; 17 | optional double marketCapBelow = 9; 18 | optional string moodyRatingAbove = 10; 19 | optional string moodyRatingBelow = 11; 20 | optional string spRatingAbove = 12; 21 | optional string spRatingBelow = 13; 22 | optional string maturityDateAbove = 14; 23 | optional string maturityDateBelow = 15; 24 | optional double couponRateAbove = 16; 25 | optional double couponRateBelow = 17; 26 | optional bool excludeConvertible = 18; 27 | optional int64 averageOptionVolumeAbove = 19; 28 | optional string scannerSettingPairs = 20; 29 | optional string stockTypeFilter = 21; 30 | repeated TagValue scannerSubscriptionFilterOptions = 22; 31 | repeated TagValue scannerSubscriptionOptions = 23; 32 | } 33 | 34 | message ScannerSubscriptionRequest { 35 | optional int32 reqId = 1; 36 | optional ScannerSubscription subscription = 2; 37 | } 38 | 39 | message ScannerDataElement { 40 | optional int32 rank = 1; 41 | optional Contract contract = 2; 42 | optional string marketName = 3; 43 | optional string distance = 4; 44 | optional string benchmark = 5; 45 | optional string projection = 6; 46 | optional string comboKey = 7; 47 | } 48 | 49 | message ScannerData { 50 | optional int32 reqId = 1; 51 | repeated ScannerDataElement data = 2; 52 | } 53 | -------------------------------------------------------------------------------- /inst/proto/News.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "TagValue.proto"; 6 | 7 | message NewsBulletin { 8 | optional int32 msgId = 1; 9 | optional int32 msgType = 2; 10 | optional string newsMessage = 3; 11 | optional string originExch = 4; 12 | } 13 | 14 | message NewsArticleRequest { 15 | optional int32 reqId = 1; 16 | optional string providerCode = 2; 17 | optional string articleId = 3; 18 | repeated TagValue newsArticleOptions = 4; 19 | } 20 | 21 | message NewsArticle { 22 | optional int32 reqId = 1; 23 | optional int32 articleType = 2; 24 | optional string articleText = 3; 25 | } 26 | 27 | message NewsProvider { 28 | optional string providerCode = 1; 29 | optional string providerName = 2; 30 | } 31 | 32 | message NewsProviders { 33 | repeated NewsProvider newsProviders = 1; 34 | } 35 | 36 | message HistoricalNewsRequest { 37 | optional int32 reqId = 1; 38 | optional int32 conId = 2; 39 | optional string providerCodes = 3; 40 | optional string startDateTime = 4; 41 | optional string endDateTime = 5; 42 | optional int32 totalResults = 6; 43 | repeated TagValue historicalNewsOptions = 7; 44 | } 45 | 46 | message HistoricalNews { 47 | optional int32 reqId = 1; 48 | optional string time = 2; 49 | optional string providerCode = 3; 50 | optional string articleId = 4; 51 | optional string headline = 5; 52 | } 53 | 54 | message HistoricalNewsEnd { 55 | optional int32 reqId = 1; 56 | optional bool hasMore = 2; 57 | } 58 | 59 | message TickNews { 60 | optional int32 reqId = 1; 61 | optional int64 timestamp = 2; 62 | optional string providerCode = 3; 63 | optional string articleId = 4; 64 | optional string headline = 5; 65 | optional string extraData = 6; 66 | } 67 | -------------------------------------------------------------------------------- /inst/proto/Contract.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "ContractDetails.proto"; 6 | 7 | message ComboLeg { 8 | optional int32 conId = 1; 9 | optional int32 ratio = 2; 10 | optional string action = 3; 11 | optional string exchange = 4; 12 | optional int32 openClose = 5; 13 | optional int32 shortSaleSlot = 6; 14 | optional string designatedLocation = 7; 15 | optional int32 exemptCode = 8; 16 | optional double perLegPrice = 9; 17 | } 18 | 19 | message DeltaNeutralContract { 20 | optional int32 conId = 1; 21 | optional double delta = 2; 22 | optional double price = 3; 23 | } 24 | 25 | message Contract { 26 | optional int32 conId = 1; 27 | optional string symbol = 2; 28 | optional string secType = 3; 29 | optional string lastTradeDateOrContractMonth = 4; 30 | optional double strike = 5; 31 | optional string right = 6; 32 | optional double multiplier = 7; 33 | optional string exchange = 8; 34 | optional string primaryExchange = 9; 35 | optional string currency = 10; 36 | optional string localSymbol = 11; 37 | optional string tradingClass = 12; 38 | optional string secIdType = 13; 39 | optional string secId = 14; 40 | optional string description = 15; 41 | optional string issuerId = 16; 42 | optional DeltaNeutralContract deltaNeutralContract = 17; 43 | optional bool includeExpired = 18; 44 | optional string comboLegsDescrip = 19; 45 | repeated ComboLeg comboLegs = 20; 46 | optional string lastTradeDate = 21; 47 | } 48 | 49 | message ContractDataRequest { 50 | optional int32 reqId = 1; 51 | optional Contract contract = 2; 52 | } 53 | 54 | message ContractData { 55 | optional int32 reqId = 1; 56 | optional Contract contract = 2; 57 | optional ContractDetails contractDetails = 3; 58 | } 59 | -------------------------------------------------------------------------------- /inst/proto/Execution.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "Contract.proto"; 6 | 7 | message ExecutionFilter { 8 | optional int32 clientId = 1; 9 | optional string acctCode = 2; 10 | optional string time = 3; 11 | optional string symbol = 4; 12 | optional string secType = 5; 13 | optional string exchange = 6; 14 | optional string side = 7; 15 | optional int32 lastNDays = 8; 16 | repeated int32 specificDates = 9; 17 | } 18 | 19 | message ExecutionRequest { 20 | optional int32 reqId = 1; 21 | optional ExecutionFilter filter = 2; 22 | } 23 | 24 | message Execution { 25 | optional int32 orderId = 1; 26 | optional string execId = 2; 27 | optional string time = 3; 28 | optional string acctNumber = 4; 29 | optional string exchange = 5; 30 | optional string side = 6; 31 | optional string shares = 7; 32 | optional double price = 8; 33 | optional int64 permId = 9; 34 | optional int32 clientId = 10; 35 | optional bool liquidation = 11; 36 | optional string cumQty = 12; 37 | optional double avgPrice = 13; 38 | optional string orderRef = 14; 39 | optional string evRule = 15; 40 | optional double evMultiplier = 16; 41 | optional string modelCode = 17; 42 | optional int32 lastLiquidity = 18; 43 | optional bool pendingPriceRevision = 19; 44 | optional string submitter = 20; 45 | optional int32 optExerciseOrLapseType = 21; 46 | } 47 | 48 | message ExecutionDetails { 49 | optional int32 reqId = 1; 50 | optional Contract contract = 2; 51 | optional Execution execution = 3; 52 | } 53 | 54 | message CommissionReport { 55 | optional string execId = 1; 56 | optional double commission = 2; 57 | optional string currency = 3; 58 | optional double realizedPNL = 4; 59 | optional double yield = 5; 60 | optional string yieldRedemptionDate = 6; 61 | } 62 | -------------------------------------------------------------------------------- /inst/proto/OrderState.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | message OrderAllocation { 6 | optional string account = 1; 7 | optional string position = 2; 8 | optional string positionDesired = 3; 9 | optional string positionAfter = 4; 10 | optional string desiredAllocQty = 5; 11 | optional string allowedAllocQty = 6; 12 | optional bool isMonetary = 7; 13 | } 14 | 15 | message OrderState { 16 | optional string status = 1; 17 | optional double initMarginBefore = 2; 18 | optional double maintMarginBefore = 3; 19 | optional double equityWithLoanBefore = 4; 20 | optional double initMarginChange = 5; 21 | optional double maintMarginChange = 6; 22 | optional double equityWithLoanChange = 7; 23 | optional double initMarginAfter = 8; 24 | optional double maintMarginAfter = 9; 25 | optional double equityWithLoanAfter = 10; 26 | 27 | optional double commission = 11; 28 | optional double minCommission = 12; 29 | optional double maxCommission = 13; 30 | optional string commissionCurrency = 14; 31 | optional string marginCurrency = 15; 32 | 33 | optional double initMarginBeforeOutsideRTH = 16; 34 | optional double maintMarginBeforeOutsideRTH = 17; 35 | optional double equityWithLoanBeforeOutsideRTH = 18; 36 | optional double initMarginChangeOutsideRTH = 19; 37 | optional double maintMarginChangeOutsideRTH = 20; 38 | optional double equityWithLoanChangeOutsideRTH = 21; 39 | optional double initMarginAfterOutsideRTH = 22; 40 | optional double maintMarginAfterOutsideRTH = 23; 41 | optional double equityWithLoanAfterOutsideRTH = 24; 42 | 43 | optional string suggestedSize = 25; 44 | optional string rejectReason = 26; 45 | repeated OrderAllocation orderAllocations = 27; 46 | optional string warningText = 28; 47 | optional string completedTime = 29; 48 | optional string completedStatus = 30; 49 | } 50 | -------------------------------------------------------------------------------- /inst/proto/MiscRequests.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "Contract.proto"; 6 | import "TagValue.proto"; 7 | 8 | message CalculateImpliedVolatilityRequest { 9 | optional int32 reqId = 1; 10 | optional Contract contract = 2; 11 | optional double optionPrice = 3; 12 | optional double underPrice = 4; 13 | repeated TagValue miscOptions = 5; 14 | } 15 | 16 | message CalculateOptionPriceRequest { 17 | optional int32 reqId = 1; 18 | optional Contract contract = 2; 19 | optional double volatility = 3; 20 | optional double underPrice = 4; 21 | repeated TagValue miscOptions = 5; 22 | } 23 | 24 | message ExerciseOptionsRequest { 25 | optional int32 reqId = 1; 26 | optional Contract contract = 2; 27 | optional int32 exerciseAction = 3; 28 | optional int32 exerciseQuantity = 4; 29 | optional string account = 5; 30 | optional bool override = 6; 31 | optional string manualOrderTime = 7; 32 | optional string customerAccount = 8; 33 | optional bool professionalCustomer = 9; 34 | } 35 | 36 | message FAReplace { 37 | optional int32 reqId = 1; 38 | optional int32 faDataType = 2; 39 | optional string xml = 3; 40 | } 41 | 42 | message FundamentalDataRequest { 43 | optional int32 reqId = 1; 44 | optional Contract contract = 2; 45 | optional string reportType = 3; 46 | repeated TagValue fundamentalDataOptions = 4; 47 | } 48 | 49 | message SubscribeToGroupEventsRequest { 50 | optional int32 reqId = 1; 51 | optional int32 groupId = 2; 52 | } 53 | 54 | message VerifyRequest { 55 | optional string apiName = 1; 56 | optional string apiVersion = 2; 57 | } 58 | 59 | message WshEventDataRequest { 60 | optional int32 reqId = 1; 61 | optional int32 conId = 2; 62 | optional string filter = 3; 63 | optional bool fillWatchlist = 4; 64 | optional bool fillPortfolio = 5; 65 | optional bool fillCompetitors = 6; 66 | optional string startDate = 7; 67 | optional string endDate = 8; 68 | optional int32 totalLimit = 9; 69 | } 70 | -------------------------------------------------------------------------------- /R/enums.R: -------------------------------------------------------------------------------- 1 | # 2 | # IB enums 3 | # 4 | IBEnum <- list( 5 | LegOpenClose= c(SAME= 0L, 6 | OPEN= 1L, 7 | CLOSE= 2L, 8 | UNKNOWN= 3L), 9 | 10 | FaDataType= c(GROUPS= 1L, 11 | ALIASES= 3L), 12 | 13 | MarketData= c(REALTIME= 1L, 14 | FROZEN= 2L, 15 | DELAYED= 3L, 16 | DELAYED_FROZEN= 4L), 17 | 18 | Origin= c(CUSTOMER= 0L, 19 | FIRM= 1L, 20 | UNKNOWN= 2L), 21 | 22 | AuctionStrategy= c(UNSET= 0L, 23 | MATCH= 1L, 24 | IMPROVEMENT= 2L, 25 | TRANSPARENT= 3L), 26 | 27 | Condition= c(Price= 1L, 28 | Time= 3L, 29 | Margin= 4L, 30 | Execution= 5L, 31 | Volume= 6L, 32 | PercentChange= 7L), 33 | 34 | PriceTrigger= c(Default= 0L, 35 | DoubleBidAsk= 1L, 36 | Last= 2L, 37 | DoubleLast= 3L, 38 | BidAsk= 4L, 39 | LastBidAsk= 7L, 40 | MidPoint= 8L) 41 | ) 42 | 43 | # 44 | # Map IB enums <-> int 45 | # 46 | map_enum2int <- function(enum, name) 47 | { 48 | stopifnot(is.character(enum), 49 | is.character(name)) 50 | 51 | res <- IBEnum[[enum]] 52 | 53 | stopifnot(!is.null(res)) 54 | 55 | res <- res[name] 56 | 57 | stopifnot(!is.na(res)) 58 | 59 | res 60 | } 61 | 62 | map_int2enum <- function(enum, value) 63 | { 64 | stopifnot(is.character(enum)) 65 | 66 | res <- IBEnum[[enum]] 67 | 68 | stopifnot(!is.null(res)) 69 | 70 | idx <- res == value 71 | 72 | stopifnot(any(idx)) 73 | 74 | names(res)[idx] 75 | } 76 | -------------------------------------------------------------------------------- /inst/proto/Account.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "Contract.proto"; 6 | 7 | message AccountDataRequest { 8 | optional bool subscribe = 1; 9 | optional string acctCode = 2; 10 | } 11 | 12 | message AccountSummaryRequest { 13 | optional int32 reqId = 1; 14 | optional string group = 2; 15 | optional string tags = 3; 16 | } 17 | 18 | message PositionsMultiRequest { 19 | optional int32 reqId = 1; 20 | optional string account = 2; 21 | optional string modelCode = 3; 22 | } 23 | 24 | message AccountUpdatesMultiRequest { 25 | optional int32 reqId = 1; 26 | optional string account = 2; 27 | optional string modelCode = 3; 28 | optional bool ledgerAndNLV = 4; 29 | } 30 | 31 | message AccountValue { 32 | optional string key = 1; 33 | optional string value = 2; 34 | optional string currency = 3; 35 | optional string accountName = 4; 36 | } 37 | 38 | message PortfolioValue { 39 | optional Contract contract = 1; 40 | optional string position = 2; 41 | optional double marketPrice = 3; 42 | optional double marketValue = 4; 43 | optional double averageCost = 5; 44 | optional double unrealizedPNL = 6; 45 | optional double realizedPNL = 7; 46 | optional string accountName = 8; 47 | } 48 | 49 | message Position { 50 | optional string account = 1; 51 | optional Contract contract = 2; 52 | optional string position = 3; 53 | optional double avgCost = 4; 54 | } 55 | 56 | message AccountSummary { 57 | optional int32 reqId = 1; 58 | optional string account = 2; 59 | optional string tag = 3; 60 | optional string value = 4; 61 | optional string currency = 5; 62 | } 63 | 64 | message PositionMulti { 65 | optional int32 reqId = 1; 66 | optional string account = 2; 67 | optional Contract contract = 3; 68 | optional string position = 4; 69 | optional double avgCost = 5; 70 | optional string modelCode = 6; 71 | } 72 | 73 | message AccountUpdateMulti { 74 | optional int32 reqId = 1; 75 | optional string account = 2; 76 | optional string modelCode = 3; 77 | optional string key = 4; 78 | optional string value = 5; 79 | optional string currency = 6; 80 | } 81 | -------------------------------------------------------------------------------- /man/IBClient.Rd: -------------------------------------------------------------------------------- 1 | \name{IBClient} 2 | \alias{IBClient} 3 | \docType{class} 4 | 5 | \title{Client Connection Class} 6 | 7 | \description{ 8 | This is the main class that manages the connection with the 9 | 'Trader Workstation', sends requests and handles responses. 10 | } 11 | 12 | \section{Methods}{ 13 | \itemize{ 14 | 15 | \item \code{IBClient$new()}: creates a new instance. 16 | 17 | \item \code{$connect(host="localhost", port, clientId, connectOptions="")}: 18 | connects to \code{host:port} and performs the initial 19 | handshake using client identifier \code{clientId} and additional 20 | options \code{connectOptions}. 21 | 22 | \item \code{$checkMsg(wrap, timeout=0.2)}: waits for and process server messages. 23 | When available, messages are decoded and handed over to the appropriate 24 | callback defined in \code{wrap}, which must be an instance of a child of 25 | \code{IBWrap}. 26 | If \code{wrap} is missing, messages are read and immediately discarded. 27 | Returns the number of messages processed. 28 | 29 | This methods \bold{blocks} up to \code{timeout} seconds. 30 | \bold{Needs to be called regularly}. 31 | 32 | \item \code{$disconnect()}: terminates the connection. 33 | } 34 | 35 | This class is modeled after the class \code{EClient} from the official IB API 36 | implementations. 37 | In addition to the methods shown above, several others exist that are used to send 38 | requests to the server. 39 | 40 | Refer to the official documentation for a comprehensive list of the possible 41 | requests, including their signatures and descriptions. 42 | } 43 | 44 | \seealso{ 45 | \code{\link{IBWrap}}. 46 | 47 | \href{https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClient.html}{\code{EClient}} 48 | definition from the official documentation. 49 | } 50 | 51 | 52 | \examples{ 53 | \dontrun{ 54 | # Instantiate a wrapper 55 | wrap <- IBWrapSimple$new() 56 | 57 | # Create a client and connect to a server 58 | ic <- IBClient$new() 59 | ic$connect(port=4002, clientId=1) 60 | 61 | # Make a request 62 | stock <- IBContract(symbol="GOOG", secType="STK", exchange="SMART", currency="USD") 63 | ic$reqContractDetails(11, stock) 64 | 65 | # Process responses 66 | ic$checkMsg(wrap) 67 | 68 | # Disconnect 69 | ic$disconnect() 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /man/IBWrap.Rd: -------------------------------------------------------------------------------- 1 | \name{IBWrap} 2 | \alias{IBWrap} 3 | \docType{class} 4 | 5 | \title{Callbacks Wrapper Class} 6 | 7 | \description{ 8 | As the communication with the server is asynchronous, 9 | the way to control how inbound messages are processed is via 10 | callback functions. 11 | The class \code{IBWrap} is merely a container for these functions. 12 | 13 | Being a base class, its methods are just stubs whose only action is 14 | to raise a warning when called. 15 | 16 | Customized functionality is provided by defining a child class 17 | of \code{IBWrap} and overriding the appropriate methods to perform 18 | the desired tasks. 19 | 20 | These methods are never called directly by the user program, rather 21 | they are implicitly invoked within \code{IBClient$checkMsg()} 22 | when it processes the server responses. 23 | } 24 | 25 | \details{ 26 | \code{IBWrap} is modeled after \code{EWrapper} from the official 27 | IB API implementations. 28 | 29 | The official documentation provides a comprehensive list and description 30 | of the available methods, their signatures and usage. 31 | 32 | The customization process follows this template: 33 | \preformatted{ 34 | # Class derivation: 35 | IBWrapSimple <- R6::R6Class("IBWrapSimple", 36 | class= FALSE, 37 | cloneable= FALSE, 38 | lock_class= TRUE, 39 | 40 | inherit= IBWrap, 41 | 42 | public= list( 43 | 44 | # Customized methods: 45 | error= function(id, errorCode, errorString, advancedOrderRejectJson){ 46 | 47 | # Code to handle error messages 48 | }, 49 | 50 | nextValidId= function(orderId) { 51 | 52 | # Code to handle the next order ID 53 | }, 54 | 55 | contractDetails= function(reqId, contractDetails) { 56 | 57 | # Code to handle Contract description 58 | }, 59 | # etc. 60 | ) 61 | ) 62 | 63 | # Class instantiation: 64 | wrap <- IBWrapSimple$new() 65 | 66 | # Use when processing server messages by a client: 67 | ic <- IBClient$new() 68 | 69 | ic$checkMsg(wrap) 70 | } 71 | 72 | } 73 | 74 | \seealso{ 75 | \code{\link{IBClient}}. 76 | 77 | \href{https://interactivebrokers.github.io/tws-api/interfaceIBApi_1_1EWrapper.html}{\code{EWrapper}} 78 | definition from the official documentation. 79 | } 80 | -------------------------------------------------------------------------------- /inst/proto/TickData.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "Contract.proto"; 6 | import "TagValue.proto"; 7 | 8 | message TickAttribBidAsk { 9 | optional bool bidPastLow = 1; 10 | optional bool askPastHigh = 2; 11 | } 12 | 13 | message TickAttribLast { 14 | optional bool pastLimit = 1; 15 | optional bool unreported = 2; 16 | } 17 | 18 | // HistoricalTicks 19 | 20 | message HistoricalTicksRequest { 21 | optional int32 reqId = 1; 22 | optional Contract contract = 2; 23 | optional string startDateTime = 3; 24 | optional string endDateTime = 4; 25 | optional int32 numberOfTicks = 5; 26 | optional string whatToShow = 6; 27 | optional bool useRTH = 7; 28 | optional bool ignoreSize = 8; 29 | repeated TagValue miscOptions = 9; 30 | } 31 | 32 | message Tick { 33 | optional int64 time = 1; 34 | optional double price = 2; 35 | optional string size = 3; 36 | } 37 | 38 | message HistoricalTicks { 39 | optional int32 reqId = 1; 40 | repeated Tick ticks = 2; 41 | optional bool done = 3; 42 | } 43 | 44 | message TickBidAsk { 45 | optional int64 time = 1; 46 | optional TickAttribBidAsk attribs = 2; 47 | optional double bidPrice = 3; 48 | optional double askPrice = 4; 49 | optional string bidSize = 5; 50 | optional string askSize = 6; 51 | } 52 | 53 | message HistoricalTicksBidAsk { 54 | optional int32 reqId = 1; 55 | repeated TickBidAsk ticks = 2; 56 | optional bool done = 3; 57 | } 58 | 59 | message TickLast { 60 | optional int64 time = 1; 61 | optional TickAttribLast attribs = 2; 62 | optional double price = 3; 63 | optional string size = 4; 64 | optional string exchange = 5; 65 | optional string specialConditions = 6; 66 | } 67 | 68 | message HistoricalTicksLast { 69 | optional int32 reqId = 1; 70 | repeated TickLast ticks = 2; 71 | optional bool done = 3; 72 | } 73 | 74 | // TickByTick 75 | 76 | message TickByTickRequest { 77 | optional int32 reqId = 1; 78 | optional Contract contract = 2; 79 | optional string tickType = 3; 80 | optional int32 numberOfTicks = 4; 81 | optional bool ignoreSize = 5; 82 | } 83 | 84 | message TickByTickData { 85 | optional int32 reqId = 1; 86 | optional int32 tickType = 2; 87 | oneof tick { 88 | TickLast tickLast = 3; 89 | TickBidAsk tickBidAsk = 4; 90 | Tick tickMidPoint = 5; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /inst/proto/HistoricalData.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "Contract.proto"; 6 | import "TagValue.proto"; 7 | 8 | // HistoricalData 9 | 10 | message HistoricalDataRequest { 11 | optional int32 reqId = 1; 12 | optional Contract contract = 2; 13 | optional string endDateTime = 3; 14 | optional string duration = 5; 15 | optional string barSizeSetting = 4; 16 | optional string whatToShow = 7; 17 | optional bool useRTH = 6; 18 | optional int32 formatDate = 8; 19 | optional bool keepUpToDate = 9; 20 | repeated TagValue chartOptions = 10; 21 | } 22 | 23 | message Bar { 24 | optional string time = 1; 25 | optional double open = 2; 26 | optional double high = 3; 27 | optional double low = 4; 28 | optional double close = 5; 29 | optional string volume = 6; 30 | optional string wap = 7; 31 | optional int32 count = 8; 32 | } 33 | 34 | message HistoricalData { 35 | optional int32 reqId = 1; 36 | repeated Bar bars = 2; 37 | } 38 | 39 | message HistoricalDataUpdate { 40 | optional int32 reqId = 1; 41 | optional Bar bar = 2; 42 | } 43 | 44 | message HistoricalDataEnd { 45 | optional int32 reqId = 1; 46 | optional string startDate = 2; 47 | optional string endDate = 3; 48 | } 49 | 50 | // HeadTimestamp 51 | 52 | message HeadTimestampRequest { 53 | optional int32 reqId = 1; 54 | optional Contract contract = 2; 55 | optional bool useRTH = 3; 56 | optional string whatToShow = 4; 57 | optional int32 formatDate = 5; 58 | } 59 | 60 | // HistogramData 61 | 62 | message HistogramDataRequest { 63 | optional int32 reqId = 1; 64 | optional Contract contract = 2; 65 | optional bool useRTH = 3; 66 | optional string timePeriod = 4; 67 | } 68 | 69 | message HistogramDataEntry { 70 | optional double price = 1; 71 | optional string size = 2; 72 | } 73 | 74 | message HistogramData { 75 | optional int32 reqId = 1; 76 | repeated HistogramDataEntry data = 2; 77 | } 78 | 79 | // HistoricalSchedule 80 | 81 | message HistoricalSession { 82 | optional string startDateTime = 1; 83 | optional string endDateTime = 2; 84 | optional string refDate = 3; 85 | } 86 | 87 | message HistoricalSchedule { 88 | optional int32 reqId = 1; 89 | optional string startDateTime = 2; 90 | optional string endDateTime = 3; 91 | optional string timeZone = 4; 92 | repeated HistoricalSession sessions = 5; 93 | } 94 | -------------------------------------------------------------------------------- /inst/proto/ContractDetails.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "TagValue.proto"; 6 | 7 | message IneligibilityReason { 8 | optional string id = 1; 9 | optional string description = 2; 10 | } 11 | 12 | message ContractDetails { 13 | optional string marketName = 1; 14 | optional string minTick = 2; 15 | optional string orderTypes = 3; 16 | optional string validExchanges = 4; 17 | optional int32 priceMagnifier = 5; 18 | optional int32 underConId = 6; 19 | optional string longName = 7; 20 | optional string contractMonth = 8; 21 | optional string industry = 9; 22 | optional string category = 10; 23 | optional string subcategory = 11; 24 | optional string timeZoneId = 12; 25 | optional string tradingHours = 13; 26 | optional string liquidHours = 14; 27 | optional string evRule = 15; 28 | optional double evMultiplier = 16; 29 | repeated TagValue secIdList = 17; 30 | optional int32 aggGroup = 18; 31 | optional string underSymbol = 19; 32 | optional string underSecType = 20; 33 | optional string marketRuleIds = 21; 34 | optional string realExpirationDate = 22; 35 | optional string stockType = 23; 36 | optional string minSize = 24; 37 | optional string sizeIncrement = 25; 38 | optional string suggestedSizeIncrement = 26; 39 | 40 | // fund fields 41 | optional string fundName = 27; 42 | optional string fundFamily = 28; 43 | optional string fundType = 29; 44 | optional string fundFrontLoad = 30; 45 | optional string fundBackLoad = 31; 46 | optional string fundBackLoadTimeInterval = 32; 47 | optional string fundManagementFee = 33; 48 | optional bool fundClosed = 34; 49 | optional bool fundClosedForNewInvestors = 35; 50 | optional bool fundClosedForNewMoney = 36; 51 | optional string fundNotifyAmount = 37; 52 | optional string fundMinimumInitialPurchase = 38; 53 | optional string fundSubsequentMinimumPurchase = 39; 54 | optional string fundBlueSkyStates = 40; 55 | optional string fundBlueSkyTerritories = 41; 56 | optional string fundDistributionPolicyIndicator = 42; 57 | optional string fundAssetType = 43; 58 | 59 | // bond fields 60 | optional string cusip = 44; 61 | optional string issueDate = 45; 62 | optional string ratings = 46; 63 | optional string bondType = 47; 64 | optional double coupon = 48; 65 | optional string couponType = 49; 66 | optional bool convertible = 50; 67 | optional bool callable = 51; 68 | optional bool putable = 52; 69 | optional string descAppend = 53; 70 | optional string nextOptionDate = 54; 71 | optional string nextOptionType = 55; 72 | optional bool nextOptionPartial = 56; 73 | optional string notes = 57; 74 | 75 | repeated IneligibilityReason ineligibilityReasonList = 58; 76 | 77 | // event contract fields 78 | optional string eventContract1 = 59; 79 | optional string eventContractDescription1 = 60; 80 | optional string eventContractDescription2 = 61; 81 | 82 | optional string minAlgoSize = 62; 83 | } 84 | -------------------------------------------------------------------------------- /R/protoutils.R: -------------------------------------------------------------------------------- 1 | splat <- function(pb, ...) 2 | { 3 | stopifnot(inherits(pb, "Message")) 4 | 5 | init <- list(...) 6 | 7 | # if(length(pb) < pb$descriptor()$field_count()) 8 | # warning("default needed: ", 9 | # paste(Filter(function(n) !pb$has(n), names(pb)), collapse=" ")) 10 | 11 | sapply(names(pb), function(n) { 12 | 13 | if(pb$has(n)) { 14 | 15 | val <- pb[[n]] 16 | 17 | if(inherits(val, "Message")) mapfrompb(val) 18 | else if(is.list(val)) lapply(val, mapfrompb) 19 | else val 20 | } 21 | else if(utils::hasName(init, n)) 22 | init[[n]] 23 | 24 | else { 25 | warning("default not provided: ", n) 26 | NA 27 | } 28 | }, 29 | simplify=FALSE) 30 | } 31 | 32 | 33 | mapfrompb <- function(pb) 34 | { 35 | stopifnot(inherits(pb, "Message")) 36 | 37 | desc <- pb$descriptor() 38 | 39 | res <- if(length(pb) == desc$field_count()) list() 40 | else get0(desc$name(), parent.env(environment()), mode="list", inherits=FALSE) 41 | 42 | if(is.null(res)) { 43 | warning(desc$name(), " not found. Using as.list()") 44 | return(as.list(pb)) 45 | } 46 | 47 | for(n in names(pb)) { 48 | 49 | if(!pb$has(n)) 50 | next 51 | 52 | val <- pb[[n]] 53 | 54 | if(inherits(val, "Message")) 55 | val <- mapfrompb(val) 56 | 57 | else if(is.list(val)) 58 | val <- if(desc[[n]]$message_type()$name() == "TagValue") 59 | tagvaluefrompb(val) 60 | 61 | else if(desc[[n]]$message_type()$name() == "OrderCondition") 62 | lapply(val, conditionfrompb) 63 | 64 | else 65 | lapply(val, mapfrompb) 66 | 67 | res[[n]] <- val 68 | } 69 | 70 | res 71 | } 72 | 73 | 74 | maptopb <- function(x, desc, exclude=character()) 75 | { 76 | pb <- RProtoBuf::new(desc) 77 | 78 | for(n in names(x)) { 79 | 80 | if(n %in% exclude) 81 | next 82 | 83 | val <- x[[n]] 84 | 85 | if(length(val) == 0L) 86 | next 87 | 88 | fld <- desc[[n]] 89 | 90 | if(is.list(val)) { 91 | if(is.null(names(val))) { 92 | stopifnot(fld$is_repeated(), 93 | fld$message_type()$name() %in% c("OrderCondition", "ComboLeg")) 94 | 95 | val <- if(fld$message_type()$name() == "OrderCondition") 96 | lapply(val, conditiontopb) 97 | else 98 | lapply(val, maptopb, desc=fld$message_type()) 99 | } 100 | else { 101 | stopifnot(!fld$is_repeated(), 102 | fld$message_type()$name() %in% c("Contract", "Order", 103 | "SoftDollarTier", "DeltaNeutralContract", 104 | "ExecutionFilter")) 105 | 106 | val <- maptopb(val, fld$message_type()) 107 | 108 | if(length(val) == 0L) 109 | next 110 | } 111 | } 112 | else if(fld$is_repeated()) { 113 | 114 | stopifnot(!is.na(val)) 115 | 116 | if(fld$type() == RProtoBuf::TYPE_MESSAGE) { 117 | 118 | stopifnot(fld$message_type()$name() == "TagValue") 119 | 120 | val <- tagvaluetopb(val) 121 | } 122 | 123 | # Repeated scalar are unchanged 124 | } 125 | else if(is.na(val) || # Optional scalar types 126 | is.character(val) && !nzchar(val, keepNA=TRUE) || 127 | isFALSE(val)) 128 | next 129 | 130 | pb[[n]] <- val 131 | } 132 | 133 | pb 134 | } 135 | 136 | 137 | tagvaluetopb <- function(tv) 138 | { 139 | stopifnot(is.character(tv), 140 | !is.null(names(tv))) 141 | 142 | mapply(function(k, v) RProtoBuf::new(IBProto.TagValue, key=k, value=v), names(tv), tv) 143 | } 144 | 145 | 146 | tagvaluefrompb <- function(pb) 147 | { 148 | n <- sapply(pb, function(kv) kv$key) 149 | v <- sapply(pb, function(kv) kv$value) 150 | 151 | structure(v, names=n) 152 | } 153 | 154 | 155 | conditiontopb <- function(cond) 156 | { 157 | cond$type <- map_enum2int("Condition", cond$type) 158 | cond$isConjunction <- cond$conjunction == "a" 159 | cond$conjunction <- NULL 160 | 161 | maptopb(cond, IBProto.OrderCondition) 162 | } 163 | 164 | 165 | conditionfrompb <- function(pb) 166 | { 167 | stopifnot(pb$descriptor()$name() == "OrderCondition", 168 | pb$has("type"), 169 | pb$has("isConjunction")) 170 | 171 | cond <- fCondition(map_int2enum("Condition", pb$type)) 172 | if(pb$isConjunction) 173 | cond$conjunction <- "a" 174 | 175 | for(n in names(pb)) { 176 | 177 | if(n %in% c("type", "isConjunction") || !pb$has(n)) 178 | next 179 | 180 | if(utils::hasName(cond, n)) 181 | cond[[n]] <- pb[[n]] 182 | 183 | else 184 | warning("unknown name: ", n) 185 | } 186 | 187 | cond 188 | } 189 | -------------------------------------------------------------------------------- /R/codes.R: -------------------------------------------------------------------------------- 1 | ticktype <- function(t) 2 | { 3 | res <- map_ticktype[t + 1L] 4 | 5 | if(is.na(res)) { 6 | warning("unknown ticktype: ", t) 7 | "UNKNOWN" 8 | } 9 | else 10 | res 11 | } 12 | 13 | map_ticktype <- c("BID_SIZE", # 0 14 | "BID", # 1 15 | "ASK", # 2 16 | "ASK_SIZE", # 3 17 | "LAST", # 4 18 | "LAST_SIZE", # 5 19 | "HIGH", # 6 20 | "LOW", # 7 21 | "VOLUME", # 8 22 | "CLOSE", # 9 23 | "BID_OPTION", # 10 24 | "ASK_OPTION", # 11 25 | "LAST_OPTION", # 12 26 | "MODEL_OPTION", # 13 27 | "OPEN", # 14 28 | "LOW_13_WEEK", # 15 29 | "HIGH_13_WEEK", # 16 30 | "LOW_26_WEEK", # 17 31 | "HIGH_26_WEEK", # 18 32 | "LOW_52_WEEK", # 19 33 | "HIGH_52_WEEK", # 20 34 | "AVG_VOLUME", # 21 35 | "OPEN_INTEREST", # 22 36 | "OPTION_HISTORICAL_VOL", # 23 37 | "OPTION_IMPLIED_VOL", # 24 38 | "OPTION_BID_EXCH", # 25 39 | "OPTION_ASK_EXCH", # 26 40 | "OPTION_CALL_OPEN_INTEREST", # 27 41 | "OPTION_PUT_OPEN_INTEREST", # 28 42 | "OPTION_CALL_VOLUME", # 29 43 | "OPTION_PUT_VOLUME", # 30 44 | "INDEX_FUTURE_PREMIUM", # 31 45 | "BID_EXCH", # 32 46 | "ASK_EXCH", # 33 47 | "AUCTION_VOLUME", # 34 48 | "AUCTION_PRICE", # 35 49 | "AUCTION_IMBALANCE", # 36 50 | "MARK_PRICE", # 37 51 | "BID_EFP_COMPUTATION", # 38 52 | "ASK_EFP_COMPUTATION", # 39 53 | "LAST_EFP_COMPUTATION", # 40 54 | "OPEN_EFP_COMPUTATION", # 41 55 | "HIGH_EFP_COMPUTATION", # 42 56 | "LOW_EFP_COMPUTATION", # 43 57 | "CLOSE_EFP_COMPUTATION", # 44 58 | "LAST_TIMESTAMP", # 45 59 | "SHORTABLE", # 46 60 | "FUNDAMENTAL_RATIOS", # 47 61 | "RT_VOLUME", # 48 62 | "HALTED", # 49 63 | "BID_YIELD", # 50 64 | "ASK_YIELD", # 51 65 | "LAST_YIELD", # 52 66 | "CUST_OPTION_COMPUTATION", # 53 67 | "TRADE_COUNT", # 54 68 | "TRADE_RATE", # 55 69 | "VOLUME_RATE", # 56 70 | "LAST_RTH_TRADE", # 57 71 | "RT_HISTORICAL_VOL", # 58 72 | "IB_DIVIDENDS", # 59 73 | "BOND_FACTOR_MULTIPLIER", # 60 74 | "REGULATORY_IMBALANCE", # 61 75 | "NEWS_TICK", # 62 76 | "SHORT_TERM_VOLUME_3_MIN", # 63 77 | "SHORT_TERM_VOLUME_5_MIN", # 64 78 | "SHORT_TERM_VOLUME_10_MIN", # 65 79 | "DELAYED_BID", # 66 80 | "DELAYED_ASK", # 67 81 | "DELAYED_LAST", # 68 82 | "DELAYED_BID_SIZE", # 69 83 | "DELAYED_ASK_SIZE", # 70 84 | "DELAYED_LAST_SIZE", # 71 85 | "DELAYED_HIGH", # 72 86 | "DELAYED_LOW", # 73 87 | "DELAYED_VOLUME", # 74 88 | "DELAYED_CLOSE", # 75 89 | "DELAYED_OPEN", # 76 90 | "RT_TRD_VOLUME", # 77 91 | "CREDITMAN_MARK_PRICE", # 78 92 | "CREDITMAN_SLOW_MARK_PRICE", # 79 93 | "DELAYED_BID_OPTION", # 80 94 | "DELAYED_ASK_OPTION", # 81 95 | "DELAYED_LAST_OPTION", # 82 96 | "DELAYED_MODEL_OPTION", # 83 97 | "LAST_EXCH", # 84 98 | "LAST_REG_TIME", # 85 99 | "FUTURES_OPEN_INTEREST", # 86 100 | "AVG_OPT_VOLUME", # 87 101 | "DELAYED_LAST_TIMESTAMP", # 88 102 | "SHORTABLE_SHARES", # 89 103 | "DELAYED_HALTED", # 90 104 | "REUTERS_2_MUTUAL_FUNDS", # 91 105 | "ETF_NAV_CLOSE", # 92 106 | "ETF_NAV_PRIOR_CLOSE", # 93 107 | "ETF_NAV_BID", # 94 108 | "ETF_NAV_ASK", # 95 109 | "ETF_NAV_LAST", # 96 110 | "ETF_FROZEN_NAV_LAST", # 97 111 | "ETF_NAV_HIGH", # 98 112 | "ETF_NAV_LOW", # 99 113 | "SOCIAL_MARKET_ANALYTICS", # 100 114 | "ESTIMATED_IPO_MIDPOINT", # 101 115 | "FINAL_IPO_LAST", # 102 116 | "DELAYED_YIELD_BID", # 103 117 | "DELAYED_YIELD_ASK") # 104 118 | 119 | 120 | funddist <- function(v) switch(v, 121 | N= "Accumulation Fund", 122 | Y= "Income Fund", 123 | "None") 124 | 125 | 126 | fundtype <- function(v) switch(v, 127 | "000" = "Others", 128 | "001" = "Money Market", 129 | "002" = "Fixed Income", 130 | "003" = "Multi-asset", 131 | "004" = "Equity", 132 | "005" = "Sector", 133 | "006" = "Guaranteed", 134 | "007" = "Alternative", 135 | "None") 136 | 137 | 138 | optexercisetype <- function(v) 139 | { 140 | if (v == -1L) "None" 141 | else if(v == 1L) "Exercise" 142 | else if(v == 2L) "Lapse" 143 | else if(v == 3L) "DoNothing" 144 | else if(v == 100L) "Assigned" 145 | else if(v == 101L) "AutoexerciseClearing" 146 | else if(v == 102L) "Expired" 147 | else if(v == 103L) "Netting" 148 | else if(v == 200L) "AutoexerciseTrading" 149 | else { 150 | warning("unknown type: ", v) 151 | "None" 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /inst/proto/Order.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package IBProto; 4 | 5 | import "MiscData.proto"; 6 | import "OrderCondition.proto"; 7 | import "TagValue.proto"; 8 | 9 | message Order { 10 | 11 | // order ids 12 | optional int32 clientId = 1; 13 | optional int32 orderId = 2; 14 | optional int64 permId = 3; 15 | optional int32 parentId = 4; 16 | 17 | // primary attributes 18 | optional string action = 5; 19 | optional string totalQuantity = 6; 20 | optional int32 displaySize = 7; 21 | optional string orderType = 8; 22 | optional double lmtPrice = 9; 23 | optional double auxPrice = 10; 24 | optional string tif = 11; 25 | 26 | // clearing info 27 | optional string account = 12; 28 | optional string settlingFirm = 13; 29 | optional string clearingAccount = 14; 30 | optional string clearingIntent = 15; 31 | 32 | // secondary attributes 33 | optional bool allOrNone = 16; 34 | optional bool blockOrder = 17; 35 | optional bool hidden = 18; 36 | optional bool outsideRth = 19; 37 | optional bool sweepToFill = 20; 38 | optional double percentOffset = 21; 39 | optional double trailingPercent = 22; 40 | optional double trailStopPrice = 23; 41 | optional int32 minQty = 24; 42 | optional string goodAfterTime = 25; 43 | optional string goodTillDate = 26; 44 | optional string ocaGroup = 27; 45 | optional string orderRef = 28; 46 | optional string rule80A = 29; 47 | optional int32 ocaType = 30; 48 | optional int32 triggerMethod = 31; 49 | 50 | // extended order fields 51 | optional string activeStartTime = 32; 52 | optional string activeStopTime = 33; 53 | 54 | // advisor allocation orders 55 | optional string faGroup = 34; 56 | optional string faMethod = 35; 57 | optional string faPercentage = 36; 58 | 59 | // volatility orders 60 | optional double volatility = 37; 61 | optional int32 volatilityType = 38; 62 | optional bool continuousUpdate = 39; 63 | optional int32 referencePriceType = 40; 64 | optional string deltaNeutralOrderType = 41; 65 | optional double deltaNeutralAuxPrice = 42; 66 | optional int32 deltaNeutralConId = 43; 67 | optional string deltaNeutralOpenClose = 44; 68 | optional bool deltaNeutralShortSale = 45; 69 | optional int32 deltaNeutralShortSaleSlot = 46; 70 | optional string deltaNeutralDesignatedLocation = 47; 71 | 72 | // scale orders 73 | optional int32 scaleInitLevelSize = 48; 74 | optional int32 scaleSubsLevelSize = 49; 75 | optional double scalePriceIncrement = 50; 76 | optional double scalePriceAdjustValue = 51; 77 | optional int32 scalePriceAdjustInterval = 52; 78 | optional double scaleProfitOffset = 53; 79 | optional bool scaleAutoReset = 54; 80 | optional int32 scaleInitPosition = 55; 81 | optional int32 scaleInitFillQty = 56; 82 | optional bool scaleRandomPercent = 57; 83 | optional string scaleTable = 58; 84 | 85 | // hedge orders 86 | optional string hedgeType = 59; 87 | optional string hedgeParam = 60; 88 | 89 | // algo orders 90 | optional string algoStrategy = 61; 91 | repeated TagValue algoParams = 62; 92 | optional string algoId = 63; 93 | 94 | // combo orders 95 | repeated TagValue smartComboRoutingParams = 64; 96 | 97 | // processing control 98 | optional bool whatIf = 65; 99 | optional bool transmit = 66; 100 | optional bool overridePercentageConstraints = 67; 101 | 102 | // Institutional orders only 103 | optional string openClose = 68; 104 | optional int32 origin = 69; 105 | optional int32 shortSaleSlot = 70; 106 | optional string designatedLocation = 71; 107 | optional int32 exemptCode = 72; 108 | optional string deltaNeutralSettlingFirm = 73; 109 | optional string deltaNeutralClearingAccount = 74; 110 | optional string deltaNeutralClearingIntent = 75; 111 | 112 | // SMART routing only 113 | optional double discretionaryAmt = 76; 114 | optional bool optOutSmartRouting = 77; 115 | 116 | // BOX ORDERS ONLY 117 | optional double startingPrice = 78; 118 | optional double stockRefPrice = 79; 119 | optional double delta = 80; 120 | 121 | // pegged to stock or VOL orders 122 | optional double stockRangeLower = 81; 123 | optional double stockRangeUpper = 82; 124 | 125 | // Not Held 126 | optional bool notHeld = 83; 127 | 128 | // order misc options 129 | repeated TagValue orderMiscOptions = 84; 130 | 131 | //order algo id 132 | optional bool solicited = 85; 133 | 134 | optional bool randomizeSize = 86; 135 | optional bool randomizePrice = 87; 136 | 137 | // PEG2BENCH fields 138 | optional int32 referenceContractId = 88; 139 | optional double peggedChangeAmount = 89; 140 | optional bool isPeggedChangeAmountDecrease = 90; 141 | optional double referenceChangeAmount = 91; 142 | optional string referenceExchangeId = 92; 143 | optional string adjustedOrderType = 93; 144 | optional double triggerPrice = 94; 145 | optional double adjustedStopPrice = 95; 146 | optional double adjustedStopLimitPrice = 96; 147 | optional double adjustedTrailingAmount = 97; 148 | optional int32 adjustableTrailingUnit = 98; 149 | optional double lmtPriceOffset = 99; 150 | 151 | repeated OrderCondition conditions = 100; 152 | optional bool conditionsCancelOrder = 101; 153 | optional bool conditionsIgnoreRth = 102; 154 | 155 | // models 156 | optional string modelCode = 103; 157 | 158 | optional string extOperator = 104; 159 | 160 | optional SoftDollarTier softDollarTier = 105; 161 | 162 | // native cash quantity 163 | optional double cashQty = 106; 164 | 165 | optional string mifid2DecisionMaker = 107; 166 | optional string mifid2DecisionAlgo = 108; 167 | optional string mifid2ExecutionTrader = 109; 168 | optional string mifid2ExecutionAlgo = 110; 169 | 170 | // don't use auto price for hedge 171 | optional bool dontUseAutoPriceForHedge = 111; 172 | 173 | optional bool isOmsContainer = 112; 174 | optional bool discretionaryUpToLimitPrice = 113; 175 | 176 | optional string autoCancelDate = 114; 177 | optional string filledQuantity = 115; 178 | optional int32 refFuturesConId = 116; 179 | optional bool autoCancelParent = 117; 180 | optional string shareholder = 118; 181 | optional bool imbalanceOnly = 119; 182 | optional int32 routeMarketableToBbo = 120; 183 | optional int64 parentPermId = 121; 184 | 185 | optional int32 usePriceMgmtAlgo = 122; 186 | optional int32 duration = 123; 187 | optional int32 postToAts = 124; 188 | optional string advancedErrorOverride = 125; 189 | optional string manualOrderTime = 126; 190 | optional int32 minTradeQty = 127; 191 | optional int32 minCompeteSize = 128; 192 | optional double competeAgainstBestOffset = 129; 193 | optional double midOffsetAtWhole = 130; 194 | optional double midOffsetAtHalf = 131; 195 | optional string customerAccount = 132; 196 | optional bool professionalCustomer = 133; 197 | optional string bondAccruedInterest = 134; 198 | optional bool includeOvernight = 135; 199 | optional int32 manualOrderIndicator = 136; 200 | optional string submitter = 137; 201 | optional bool deactivate = 138; 202 | optional bool postOnly = 139; 203 | optional bool allowPreOpen = 140; 204 | optional bool ignoreOpenAuction = 141; 205 | optional int32 seekPriceImprovement = 142; 206 | optional int32 whatIfType = 143; 207 | } 208 | -------------------------------------------------------------------------------- /R/IBWrap.R: -------------------------------------------------------------------------------- 1 | IBWrap <- R6Class("IBWrap", 2 | 3 | class= FALSE, 4 | cloneable= FALSE, 5 | lock_class= TRUE, 6 | 7 | public= list( 8 | 9 | # Callbacks 10 | tickPrice= function(reqId, tickType, price, size, attrib) warning("default implementation"), 11 | 12 | tickSize= function(reqId, tickType, size) warning("default implementation"), 13 | 14 | tickOptionComputation= function(reqId, tickType, tickAttrib, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice) warning("default implementation"), 15 | 16 | tickGeneric= function(reqId, tickType, value) warning("default implementation"), 17 | 18 | tickString= function(reqId, tickType, value) warning("default implementation"), 19 | 20 | tickEFP= function(reqId, tickType, basisPoints, formattedBasisPoints, totalDividends, holdDays, futureLastTradeDate, dividendImpact, dividendsToLastTradeDate) warning("default implementation"), 21 | 22 | orderStatus= function(orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld, mktCapPrice) warning("default implementation"), 23 | 24 | openOrder= function(orderId, contract, order, orderState) warning("default implementation"), 25 | 26 | openOrderEnd= function() warning("default implementation"), 27 | 28 | # connectionClosed= function() warning("default implementation"), 29 | 30 | updateAccountValue= function(key, value, currency, accountName) warning("default implementation"), 31 | 32 | updatePortfolio= function(contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName) warning("default implementation"), 33 | 34 | updateAccountTime= function(timestamp) warning("default implementation"), 35 | 36 | accountDownloadEnd= function(accountName) warning("default implementation"), 37 | 38 | nextValidId= function(orderId) warning("default implementation"), 39 | 40 | contractDetails= function(reqId, contractDetails) warning("default implementation"), 41 | 42 | bondContractDetails= function(reqId, contractDetails) warning("default implementation"), 43 | 44 | contractDetailsEnd= function(reqId) warning("default implementation"), 45 | 46 | execDetails= function(reqId, contract, execution) warning("default implementation"), 47 | 48 | execDetailsEnd= function(reqId) warning("default implementation"), 49 | 50 | error= function(id, errorTime, errorCode, errorString, advancedOrderRejectJson) warning("default implementation"), 51 | 52 | updateMktDepth= function(reqId, position, operation, side, price, size) warning("default implementation"), 53 | 54 | updateMktDepthL2= function(reqId, position, marketMaker, operation, side, price, size, isSmartDepth) warning("default implementation"), 55 | 56 | updateNewsBulletin= function(msgId, msgType, newsMessage, originExch) warning("default implementation"), 57 | 58 | managedAccounts= function(accountsList) warning("default implementation"), 59 | 60 | receiveFA= function(faDataType, xml) warning("default implementation"), 61 | 62 | historicalData= function(reqId, bars) warning("default implementation"), 63 | 64 | scannerParameters= function(xml) warning("default implementation"), 65 | 66 | scannerData= function(reqId, data) warning("default implementation"), 67 | 68 | realtimeBar= function(reqId, time, open, high, low, close, volume, wap, count) warning("default implementation"), 69 | 70 | currentTime= function(time) warning("default implementation"), 71 | 72 | fundamentalData= function(reqId, data) warning("default implementation"), 73 | 74 | deltaNeutralValidation= function(reqId, deltaNeutralContract) warning("default implementation"), 75 | 76 | tickSnapshotEnd= function(reqId) warning("default implementation"), 77 | 78 | marketDataType= function(reqId, marketDataType) warning("default implementation"), 79 | 80 | commissionReport= function(commissionReport) warning("default implementation"), 81 | 82 | position= function(account, contract, position, avgCost) warning("default implementation"), 83 | 84 | positionEnd= function() warning("default implementation"), 85 | 86 | accountSummary= function(reqId, account, tag, value, currency) warning("default implementation"), 87 | 88 | accountSummaryEnd= function(reqId) warning("default implementation"), 89 | 90 | verifyMessageAPI= function(apiData) warning("default implementation"), 91 | 92 | verifyCompleted= function(isSuccessful, errorText) warning("default implementation"), 93 | 94 | displayGroupList= function(reqId, groups) warning("default implementation"), 95 | 96 | displayGroupUpdated= function(reqId, contractInfo) warning("default implementation"), 97 | 98 | verifyAndAuthMessageAPI= function(apiData, xyzChallange) warning("default implementation"), 99 | 100 | verifyAndAuthCompleted= function(isSuccessful, errorText) warning("default implementation"), 101 | 102 | # connectAck= function() warning("default implementation"), 103 | 104 | positionMulti= function(reqId, account, modelCode, contract, position, avgCost) warning("default implementation"), 105 | 106 | positionMultiEnd= function(reqId) warning("default implementation"), 107 | 108 | accountUpdateMulti= function(reqId, account, modelCode, key, value, currency) warning("default implementation"), 109 | 110 | accountUpdateMultiEnd= function(reqId) warning("default implementation"), 111 | 112 | securityDefinitionOptionalParameter= function(reqId, exchange, underlyingConId, tradingClass, multiplier, expirations, strikes) warning("default implementation"), 113 | 114 | securityDefinitionOptionalParameterEnd= function(reqId) warning("default implementation"), 115 | 116 | softDollarTiers= function(reqId, tiers) warning("default implementation"), 117 | 118 | familyCodes= function(familyCodes) warning("default implementation"), 119 | 120 | symbolSamples= function(reqId, contractDescriptions) warning("default implementation"), 121 | 122 | mktDepthExchanges= function(depthMktDataDescriptions) warning("default implementation"), 123 | 124 | tickNews= function(reqId, timestamp, providerCode, articleId, headline, extraData) warning("default implementation"), 125 | 126 | smartComponents= function(reqId, map) warning("default implementation"), 127 | 128 | tickReqParams= function(reqId, minTick, bboExchange, snapshotPermissions) warning("default implementation"), 129 | 130 | newsProviders= function(newsProviders) warning("default implementation"), 131 | 132 | newsArticle= function(reqId, articleType, articleText) warning("default implementation"), 133 | 134 | historicalNews= function(reqId, time, providerCode, articleId, headline) warning("default implementation"), 135 | 136 | historicalNewsEnd= function(reqId, hasMore) warning("default implementation"), 137 | 138 | headTimestamp= function(reqId, headTimestamp) warning("default implementation"), 139 | 140 | histogramData= function(reqId, data) warning("default implementation"), 141 | 142 | historicalDataUpdate= function(reqId, bar) warning("default implementation"), 143 | 144 | rerouteMktDataReq= function(reqId, conId, exchange) warning("default implementation"), 145 | 146 | rerouteMktDepthReq= function(reqId, conId, exchange) warning("default implementation"), 147 | 148 | marketRule= function(marketRuleId, priceIncrements) warning("default implementation"), 149 | 150 | pnl= function(reqId, dailyPnL, unrealizedPnL, realizedPnL) warning("default implementation"), 151 | 152 | pnlSingle= function(reqId, position, dailyPnL, unrealizedPnL, realizedPnL, value) warning("default implementation"), 153 | 154 | historicalTicks= function(reqId, ticks, done) warning("default implementation"), 155 | 156 | historicalTicksBidAsk= function(reqId, ticks, done) warning("default implementation"), 157 | 158 | historicalTicksLast= function(reqId, ticks, done) warning("default implementation"), 159 | 160 | tickByTickAllLast= function(reqId, tickType, time, price, size, attribs, exchange, specialConditions) warning("default implementation"), 161 | 162 | tickByTickBidAsk= function(reqId, time, bidPrice, askPrice, bidSize, askSize, attribs) warning("default implementation"), 163 | 164 | tickByTickMidPoint= function(reqId, time, price) warning("default implementation"), 165 | 166 | orderBound= function(permId, clientId, orderId) warning("default implementation"), 167 | 168 | completedOrder= function(contract, order, orderState) warning("default implementation"), 169 | 170 | completedOrdersEnd= function() warning("default implementation"), 171 | 172 | replaceFAEnd= function(reqId, data) warning("default implementation"), 173 | 174 | wshMetaData= function(reqId, data) warning("default implementation"), 175 | 176 | wshEventData= function(reqId, data) warning("default implementation"), 177 | 178 | historicalSchedule= function(reqId, startDateTime, endDateTime, timeZone, sessions) warning("default implementation"), 179 | 180 | userInfo= function(reqId, whiteBrandingId) warning("default implementation"), 181 | 182 | historicalDataEnd= function(reqId, startDate, endDate) warning("default implementation"), 183 | 184 | currentTimeInMillis= function(timeInMillis) warning("default implementation") 185 | ) 186 | ) 187 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rib 2 | 3 | [![CRAN status](https://www.r-pkg.org/badges/version/rib?color=blue)](https://cran.r-project.org/package=rib) 4 | ![CRAN downloads](https://cranlogs.r-pkg.org/badges/grand-total/rib) 5 | 6 | *An R implementation of Interactive Brokers API* 7 | 8 | Originally inspired by [`IBrokers`](https://CRAN.R-project.org/package=IBrokers), 9 | `rib` is a native [R](https://www.r-project.org/) client that implements 10 | [Interactive Brokers](https://www.interactivebrokers.com/) API to communicate 11 | with TWS or IBGateway. 12 | 13 | It aims to be feature complete, however it does not support legacy versions. 14 | 15 | It is noteworthy to mention that the official IB API has recently adopted 16 | Protocol Buffers as the underlying wire format, replacing the legacy custom protocol. 17 | This package followed suit and support for the latter has been dropped. 18 | 19 | Currently, only API versions `v213+` are supported, which translates to 20 | TWS version `10.40` or later. 21 | 22 | The package design mirrors the official C++/Java 23 | [IB API](https://interactivebrokers.github.io/tws-api/), 24 | which is based on an asynchronous communication model over TCP. 25 | 26 | ## Installation 27 | To install from [CRAN](https://CRAN.R-project.org/package=rib): 28 | ```R 29 | install.packages("rib") 30 | ``` 31 | 32 | To install the latest snapshot from GitHub, assuming 33 | [`devtools`](https://CRAN.R-project.org/package=devtools) or at least 34 | [`remotes`](https://CRAN.R-project.org/package=remotes) is already installed: 35 | ```R 36 | remotes::install_github("lbilli/rib") 37 | ``` 38 | 39 | ## Usage 40 | The user interacts mainly with two classes, implemented as 41 | [`R6`](https://CRAN.R-project.org/package=R6) objects: 42 | - `IBClient`: responsible to establish a connection and send requests to the server 43 | - `IBWrap`: base class holding the callbacks that are invoked when responses 44 | are processed. User customizations are derived from this class. 45 | 46 | Other data structures, such as `Contract` and `Order`, are implemented as R lists, 47 | or nested lists, and mirror the respective classes in the official IB API. 48 | 49 | A complete minimal working example is shown. 50 | For this code to work, an instance of IB TWS or IBGateway needs to be running 51 | on the local machine and listening on port `4002`. 52 | **Note:** _demo_ or _paper_ account recommended!! :smirk: 53 | ```R 54 | library(rib) 55 | 56 | # Define a customized callbacks wrapper 57 | IBWrapCustom <- R6::R6Class("IBWrapCustom", 58 | class= FALSE, 59 | cloneable= FALSE, 60 | lock_class= TRUE, 61 | 62 | inherit= IBWrap, 63 | 64 | public= list( 65 | # Customized methods go here 66 | error= function(id, errorTime, errorCode, errorString, advancedOrderRejectJson) 67 | cat("Error:", id, errorTime, errorCode, errorString, advancedOrderRejectJson, "\n"), 68 | 69 | nextValidId= function(orderId) 70 | cat("Next OrderId:", orderId, "\n"), 71 | 72 | managedAccounts= function(accountsList) 73 | cat("Managed Accounts:", accountsList, "\n") 74 | 75 | # more method overrides can go here... 76 | ) 77 | ) 78 | 79 | # Instantiate wrapper and client 80 | wrap <- IBWrapCustom$new() 81 | ic <- IBClient$new() 82 | 83 | # Connect to the server with clientId = 1 84 | ic$connect(port=4002, clientId=1) 85 | 86 | # Check connection messages (optional) 87 | ic$checkMsg(wrap) 88 | 89 | # Define contract 90 | contract <- IBContract(symbol="GOOG", secType="STK", exchange="SMART", currency="USD") 91 | 92 | # Define order 93 | order <- IBOrder(action="BUY", totalQuantity=10, orderType="LMT", lmtPrice=100) 94 | 95 | orderId <- 1 # Should match whatever is returned by the server 96 | 97 | # Send order 98 | ic$placeOrder(orderId, contract, order) 99 | 100 | # Check inbound messages 101 | ic$checkMsg(wrap) 102 | 103 | # Disconnect 104 | ic$disconnect() 105 | ``` 106 | 107 | As R is single threaded, in general it is the user's responsibility to code 108 | some kind of event loop to periodically process incoming messages: 109 | _i.e._ there is no background `Reader` monitoring the connection 110 | and processing the server responses. 111 | 112 | Two possible approaches, with or without a loop, are described: 113 | 114 | #### Straight Request-Response pattern. No loop. 115 | This is the simplest case. It's not suitable for data subscriptions or whenever a 116 | stream of messages is expected. It follows the pattern: 117 | - connect 118 | - send requests 119 | - process responses 120 | - disconnect 121 | 122 | ```R 123 | library(rib) 124 | 125 | # Instantiate wrapper, client and connect 126 | wrap <- IBWrapSimple$new() 127 | ic <- IBClient$new() 128 | ic$connect(port=4002, clientId=1) 129 | 130 | # Send requests, e.g.: 131 | contract <- IBContract(symbol="GOOG", secType="STK", exchange="SMART", currency="USD") 132 | ic$reqContractDetails(11, contract) 133 | 134 | # more requests can go here... 135 | 136 | # Parse responses 137 | # Might need to be called several times to exhaust all messages 138 | ic$checkMsg(wrap) 139 | 140 | # Find results in 141 | wrap$context 142 | 143 | # Disconnect 144 | ic$disconnect() 145 | ``` 146 | 147 | #### Request-Response loop 148 | A more realistic application requires a loop around the previous example: 149 | - connect 150 | - repeat 151 | - send requests 152 | - process responses 153 | - if done exit 154 | - disconnect 155 | 156 | ```R 157 | library(rib) 158 | 159 | # Instantiate wrapper, client and connect 160 | wrap <- IBWrapSimple$new() 161 | ic <- IBClient$new() 162 | ic$connect(port=4002, clientId=1) 163 | 164 | # Main loop 165 | repeat { 166 | 167 | # Application logic goes here 168 | # e.g.: send request 169 | ic$reqContractDetails(...) 170 | 171 | # Wait and process responses 172 | ic$checkMsg(wrap) 173 | 174 | if(done) 175 | break 176 | 177 | # Might be convenient to have a little wait here 178 | Sys.sleep(1) 179 | } 180 | 181 | # Disconnect 182 | ic$disconnect() 183 | ``` 184 | 185 | ## Implementation Details 186 | 187 | #### [`IBClient`](R/IBClient.R) 188 | This implements the IB `EClient` class functionality. Among its methods: 189 | - `new()`: create a new instance. 190 | - `connect(host, port, clientId, connectOptions)`: establish a connection. 191 | - `disconnect()`: terminate the connection. 192 | - `checkMsg(wrap, timeout)`: wait for responses and dispatch callbacks defined 193 | in `wrap`, which must be an instance of a class derived from `IBWrap`. 194 | If no response is available, it **blocks** up to `timeout` seconds. 195 | If `wrap` is missing, messages are taken off the wire and discarded. 196 | Return the number of responses processed. **Needs to be called regularly!** 197 | - methods that send requests to the server. 198 | Refer to the official IB `EClient` class documentation for further details and 199 | method signatures. 200 | 201 | #### [`IBWrap`](R/IBWrap.R) 202 | Like the official IB `EWrapper` class, this holds the callbacks that are dispatched 203 | when responses are processed. `IBWrap` itself contains only stubs. 204 | Users need to derive from it and override the desired methods. 205 | The code [above](#usage) provides a template of the procedure. 206 | 207 | For a more extensive example refer to the definition of 208 | [`IBWrapSimple`](examples/IBWrapSimple.R), mainly provided for 209 | illustrative purposes, which simply prints out the content of the responses 210 | or store it within `IBWrapSimple$context` for later inspection. 211 | 212 | For more details about callback definitions and signatures, 213 | refer to the official IB `EWrapper` class documentation. 214 | 215 | ## Notes 216 | Callbacks are generally invoked with arguments and types matching the signatures 217 | as described in the official documentation. 218 | However, there are few exceptions: 219 | - `tickPrice()` has an extra `size` argument, 220 | which is meaningful only when `TickType ∈ {BID, ASK, LAST}`. 221 | In these cases, the official IB API fires an extra `tickSize()` event instead. 222 | - `historicalData()` is invoked only once per request, 223 | presenting all the historical data as a list of rows, 224 | whereas the official IB API invokes it on a row-by-row basis. 225 | - `scannerData()` is similarly invoked once per request with a list of rows 226 | as argument. Consequently, `scannerDataEnd()` is redundant and 227 | it is **not** used in this package. 228 | 229 | These modifications make it possible to establish the rule: 230 | _one callback per server response_. 231 | 232 | Tabular data are generally structured as lists of rows. 233 | This applies to several callbacks, such as: 234 | `softDollarTiers()`, `familyCodes()`, `mktDepthExchanges()`, 235 | `smartComponents()`, `newsProviders()`, `histogramData()`, 236 | `marketRule()` and the `historicalTicks*()` family. 237 | 238 | #### Missing Values 239 | Occasionally, for numerical types, there is the need to represent 240 | the lack of a value. 241 | 242 | IB API does not have a uniform solution across the board, but rather 243 | it adopts a variety of sentinel values. 244 | They can be either the plain `0` or the largest representable value 245 | of a given type such as `2147483647` and `9223372036854775807` 246 | for 32- and 64-bit integers respectively or `1.7976931348623157E308` 247 | for 64-bit floating point. 248 | 249 | This package makes an effort to use R built-in `NA` 250 | in all circumstances. 251 | 252 | #### Data Structures 253 | Other classes that mainly hold data are also [replicated](R/structs.R). 254 | They are implemented as R lists, possibly nested, with names, types and default values 255 | matching the IB API counterparts: _e.g._ 256 | `Contract`, `Order`, `ComboLeg`, `ExecutionFilter`, `ScannerSubscription` 257 | and `Condition`. 258 | 259 | To use them, simply make a copy and override their elements: 260 | ```R 261 | contract <- Contract 262 | contract$conId <- 12345 263 | contract$currency <- "USD" 264 | ``` 265 | In the case of `Contract` and `Order`, helper [functions](R/factory.R) 266 | are also provided to simplify the assignment to a subset of the fields: 267 | ```R 268 | contract <- IBContract(symbol="GOOG", secType="STK", exchange="SMART", currency="USD") 269 | 270 | # Equivalent to 271 | contract <- Contract 272 | contract$symbol <- "GOOG" 273 | contract$secType <- "STK" 274 | contract$exchange <- "SMART" 275 | contract$currency <- "USD" 276 | ``` 277 | and 278 | ```R 279 | order <- IBOrder(action="BUY", totalQuantity=100, orderType="LMT", lmtPrice=110) 280 | 281 | # Equivalent to 282 | order <- Order 283 | order$action <- "BUY" 284 | order$totalQuantity <- 100 285 | order$orderType <- "LMT" 286 | order$lmtPrice <- 110 287 | ``` 288 | To instantiate a `Condition`, invoke `fCondition(type)` 289 | and fill in the appropriate fields: 290 | ```R 291 | condition <- fCondition("Price") 292 | condition$conId <- 265598L 293 | condition$exchange <- "SMART" 294 | condition$is_more <- TRUE 295 | condition$value <- 200 296 | ``` 297 | `TagValueList` are implemented as R named character vectors. 298 | Wherever a `TagValueList` is needed, something like this can be used: 299 | ```R 300 | tagvaluelist <- c(tag1="value1", tag2="value2") 301 | # or, in case of an empty list: 302 | emptylist <- character() 303 | ``` 304 | -------------------------------------------------------------------------------- /examples/IBWrapSimple.R: -------------------------------------------------------------------------------- 1 | IBWrapSimple <- R6::R6Class("IBWrapSimple", 2 | 3 | class= FALSE, 4 | cloneable= FALSE, 5 | lock_class= TRUE, 6 | 7 | inherit= IBWrap, 8 | 9 | public= list( 10 | 11 | # Environment holding results 12 | context= NULL, 13 | 14 | initialize= function() self$context <- new.env(), 15 | 16 | # Override methods 17 | tickPrice= function(reqId, tickType, price, size, attrib) 18 | cat("tickPrice:", reqId, tickType, price, size, unlist(attrib), "\n"), 19 | 20 | tickSize= function(reqId, tickType, size) 21 | cat("tickSize:", reqId, tickType, size, "\n"), 22 | 23 | tickOptionComputation= function(reqId, tickType, tickAttrib, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice) { 24 | self$context$option <- list(tickType, tickAttrib, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice) 25 | cat("tickOption:", reqId, tickType, "\n") 26 | }, 27 | 28 | tickGeneric= function(reqId, tickType, value) 29 | cat("tickGeneric:", reqId, tickType, value, "\n"), 30 | 31 | tickString= function(reqId, tickType, value) 32 | cat("tickString:", reqId, tickType, value, "\n"), 33 | 34 | orderStatus= function(orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld, mktCapPrice) 35 | cat("orderStatus:", orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld, mktCapPrice, "\n"), 36 | 37 | openOrder= function(orderId, contract, order, orderState) { 38 | self$context$order <- list(id=orderId, contract=contract, order=order, orderState=orderState) 39 | cat("openOrder:", orderId, "\n") 40 | }, 41 | 42 | openOrderEnd= function() 43 | cat("openOrderEnd\n"), 44 | 45 | updateAccountValue= function(key, value, currency, accountName) 46 | cat("accountValue:", key, value, currency, accountName, "\n"), 47 | 48 | updatePortfolio= function(contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName) 49 | cat("portfolio:", contract$symbol, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName, "\n"), 50 | 51 | updateAccountTime= function(timestamp) 52 | cat("accountTime:", timestamp, "\n"), 53 | 54 | accountDownloadEnd= function(accountName) 55 | cat("accountDownloadEnd:", accountName, "\n"), 56 | 57 | nextValidId= function(orderId) 58 | self$context$nextId <- orderId, 59 | 60 | contractDetails= function(reqId, contractDetails) { 61 | self$context$contract <- contractDetails 62 | cat("contractDetails:", reqId, contractDetails$contract$conId, "\n") 63 | }, 64 | 65 | bondContractDetails=function(reqId, contractDetails) { 66 | self$context$bond <- contractDetails 67 | cat("bondDetails:", reqId, contractDetails$contract$conId, "\n") 68 | }, 69 | 70 | contractDetailsEnd= function(reqId) 71 | cat("contractDetailsEnd:", reqId, "\n"), 72 | 73 | execDetails= function(reqId, contract, execution) { 74 | self$context$ex_contract <- contract 75 | self$context$execution <- execution 76 | cat("execDetails:", reqId, contract$symbol, execution$time, execution$side, execution$shares, execution$price, "\n") 77 | }, 78 | 79 | execDetailsEnd= function(reqId) 80 | cat("execDetailsEnd:", reqId, "\n"), 81 | 82 | error= function(id, errorTime, errorCode, errorString, advancedOrderRejectJson) 83 | cat("error:", id, errorTime, errorCode, errorString, advancedOrderRejectJson, "\n"), 84 | 85 | updateMktDepth= function(reqId, position, operation, side, price, size) 86 | cat("mktDepth:", reqId, position, operation, side, price, size, "\n"), 87 | 88 | updateMktDepthL2= function(reqId, position, marketMaker, operation, side, price, size, isSmartDepth) 89 | cat("mktDepthL2:", reqId, position, marketMaker, operation, side, price, size, isSmartDepth, "\n"), 90 | 91 | updateNewsBulletin= function(msgId, msgType, newsMessage, originExch) { 92 | self$context$news <- newsMessage 93 | cat("newsBulletin:", msgId, msgType, originExch, "\n", 94 | newsMessage, "\n") 95 | }, 96 | 97 | managedAccounts= function(accountsList) 98 | self$context$accounts <- accountsList, 99 | 100 | receiveFA= function(faDataType, xml) { 101 | self$context$fa <- xml 102 | cat("receiveFA:", faDataType, "\n") 103 | }, 104 | 105 | historicalData= function(reqId, bars) { 106 | self$context$historical <- bars 107 | cat("historicalData:", reqId, "Rows:", length(bars), "\n") 108 | }, 109 | 110 | scannerParameters= function(xml) { 111 | self$context$scannerParameters <- xml 112 | cat("scannerParameters: Received\n") 113 | }, 114 | 115 | scannerData= function(reqId, data) { 116 | self$context$scanner <- data 117 | cat("scannerData:", reqId, length(data), "\n") 118 | }, 119 | 120 | realtimeBar= function(reqId, time, open, high, low, close, volume, wap, count) 121 | cat("realtimeBar:", reqId, time, open, high, low, close, volume, wap, count, "\n"), 122 | 123 | currentTime= function(time) { 124 | self$context$time <- time 125 | cat("currentTime:", time, "\n") 126 | }, 127 | 128 | fundamentalData= function(reqId, data) { 129 | self$context$fundamentalData <- data 130 | cat("fundamentalData:", reqId, "\n") 131 | }, 132 | 133 | tickSnapshotEnd= function(reqId) 134 | cat("tickSnapshotEnd:", reqId, "\n"), 135 | 136 | marketDataType= function(reqId, marketDataType) 137 | cat("marketDataType:", reqId, map_int2enum("MarketData", marketDataType), "\n"), 138 | 139 | commissionReport= function(commissionReport) 140 | cat("commissionReport:", unlist(commissionReport), "\n"), 141 | 142 | position= function(account, contract, position, avgCost) 143 | cat("position:", account, contract$symbol, position, avgCost, "\n"), 144 | 145 | positionEnd= function() 146 | cat("positionEnd\n"), 147 | 148 | accountSummary= function(reqId, account, tag, value, currency) 149 | cat("account:", reqId, account, tag, value, currency, "\n"), 150 | 151 | accountSummaryEnd= function(reqId) 152 | cat("accountEnd:", reqId, "\n"), 153 | 154 | displayGroupList= function(reqId, groups) 155 | cat("displayGroupList:", reqId, groups, "\n"), 156 | 157 | displayGroupUpdated= function(reqId, contractInfo) 158 | cat("displayGroupUpdated:", reqId, contractInfo, "\n"), 159 | 160 | positionMulti= function(reqId, account, modelCode, contract, position, avgCost) 161 | cat("positionMulti:", reqId, account, modelCode, contract$symbol, position, avgCost, "\n"), 162 | 163 | positionMultiEnd= function(reqId) 164 | cat("positionMultiEnd:", reqId, "\n"), 165 | 166 | accountUpdateMulti= function(reqId, account, modelCode, key, value, currency) 167 | cat("accountUpdateMulti:", reqId, account, modelCode, key, value, currency, "\n"), 168 | 169 | accountUpdateMultiEnd= function(reqId) 170 | cat("accountUpdateMultiEnd:", reqId, "\n"), 171 | 172 | securityDefinitionOptionalParameter= function(reqId, exchange, underlyingConId, tradingClass, multiplier, expirations, strikes) 173 | cat("sdop:", reqId, exchange, underlyingConId, tradingClass, multiplier, length(expirations), length(strikes), "\n"), 174 | 175 | securityDefinitionOptionalParameterEnd= function(reqId) 176 | cat("sdopEnd:", reqId, "\n"), 177 | 178 | softDollarTiers= function(reqId, tiers) { 179 | self$context$softdollar <- tiers 180 | cat("softDollarTiers:", reqId, length(tiers), "\n") 181 | }, 182 | 183 | familyCodes= function(familyCodes) { 184 | self$context$familycodes <- familyCodes 185 | cat("familyCodes:", length(familyCodes), "\n") 186 | }, 187 | 188 | symbolSamples= function(reqId, contractDescriptions) { 189 | self$context$cds <- contractDescriptions 190 | cat("symbolSamples:", reqId, length(contractDescriptions), "\n") 191 | }, 192 | 193 | mktDepthExchanges= function(depthMktDataDescriptions) { 194 | self$context$mktDepthExchanges <- depthMktDataDescriptions 195 | cat("mktDepthExchanges:", length(depthMktDataDescriptions), "\n") 196 | }, 197 | 198 | tickNews= function(reqId, timestamp, providerCode, articleId, headline, extraData) 199 | cat("tickNews:", reqId, timestamp, providerCode, articleId, headline, extraData, "\n"), 200 | 201 | smartComponents= function(reqId, map) { 202 | self$context$smartcomponents <- map 203 | cat("smartComponents:", reqId, length(map), "\n") 204 | }, 205 | 206 | tickReqParams= function(reqId, minTick, bboExchange, snapshotPermissions) 207 | cat("tickReqParams:", reqId, minTick, bboExchange, snapshotPermissions, "\n"), 208 | 209 | newsProviders= function(newsProviders) { 210 | self$context$newsproviders <- newsProviders 211 | cat("newsProviders:", length(newsProviders), "\n") 212 | }, 213 | 214 | newsArticle= function(reqId, articleType, articleText) { 215 | self$context$newsarticle <- articleText 216 | cat("newsArticle:", reqId, articleType, "\n") 217 | }, 218 | 219 | historicalNews= function(reqId, time, providerCode, articleId, headline) 220 | cat("historicalNews:", reqId, time, providerCode, articleId, headline, "\n"), 221 | 222 | historicalNewsEnd= function(reqId, hasMore) 223 | cat("historicalNewsEnd:", reqId, hasMore, "\n"), 224 | 225 | headTimestamp= function(reqId, headTimestamp) 226 | cat("headTimestamp:", reqId, headTimestamp, "\n"), 227 | 228 | histogramData= function(reqId, data) { 229 | self$context$histogram <- data 230 | cat("histogramData:", reqId, length(data), "\n") 231 | }, 232 | 233 | historicalDataUpdate= function(reqId, bar) 234 | cat("historicalDataUpdate:", reqId, unlist(bar), "\n"), 235 | 236 | rerouteMktDataReq= function(reqId, conId, exchange) 237 | cat("rerouteMktDataReq:", reqId, conId, exchange, "\n"), 238 | 239 | rerouteMktDepthReq= function(reqId, conId, exchange) 240 | cat("rerouteMktDepthReq:", reqId, conId, exchange, "\n"), 241 | 242 | marketRule= function(marketRuleId, priceIncrements) { 243 | self$context$marketrule <- priceIncrements 244 | cat("marketRule:", marketRuleId, length(priceIncrements), "\n") 245 | }, 246 | 247 | pnl= function(reqId, dailyPnL, unrealizedPnL, realizedPnL) 248 | cat("pnl:", reqId, dailyPnL, unrealizedPnL, realizedPnL, "\n"), 249 | 250 | pnlSingle= function(reqId, position, dailyPnL, unrealizedPnL, realizedPnL, value) 251 | cat("pnlSingle:", reqId, position, dailyPnL, unrealizedPnL, realizedPnL, value, "\n"), 252 | 253 | historicalTicks= function(reqId, ticks, done) { 254 | self$context$historicalTicks <- ticks 255 | cat("historicalTicks:", reqId, done, length(ticks), "\n") 256 | }, 257 | 258 | historicalTicksBidAsk= function(reqId, ticks, done) { 259 | self$context$historicalTicksBidAsk <- ticks 260 | cat("historicalTicksBidAsk:", reqId, done, length(ticks), "\n") 261 | }, 262 | 263 | historicalTicksLast= function(reqId, ticks, done) { 264 | self$context$historicalTicksLast <- ticks 265 | cat("historicalTicksLast:", reqId, done, length(ticks), "\n") 266 | }, 267 | 268 | tickByTickAllLast= function(reqId, tickType, time, price, size, attribs, exchange, specialConditions) 269 | cat("tickByTickAllLast:", reqId, tickType, time, price, size, unlist(attribs), exchange, specialConditions, "\n"), 270 | 271 | tickByTickBidAsk= function(reqId, time, bidPrice, askPrice, bidSize, askSize, attribs) 272 | cat("tickByTickBidAsk:", reqId, time, bidPrice, askPrice, bidSize, askSize, unlist(attribs), "\n"), 273 | 274 | tickByTickMidPoint= function(reqId, time, price) 275 | cat("tickByTickMidPoint:", reqId, time, price, "\n"), 276 | 277 | orderBound= function(permId, clientId, orderId) 278 | cat("orderBound:", permId, clientId, orderId, "\n"), 279 | 280 | completedOrder= function(contract, order, orderState) { 281 | self$context$completed <- list(contract=contract, order=order, orderState=orderState) 282 | cat("completedOrder:", contract$symbol, orderState$status, "\n") 283 | }, 284 | 285 | completedOrdersEnd= function() 286 | cat("completedOrdersEnd\n"), 287 | 288 | replaceFAEnd= function(reqId, data) 289 | cat("replaceFAEnd:", reqId, data, "\n"), 290 | 291 | wshMetaData= function(reqId, data) { 292 | self$context$wshmeta <- data 293 | cat("wshMetaData:", reqId, "\n") 294 | }, 295 | 296 | wshEventData= function(reqId, data) { 297 | self$context$wshevents <- data 298 | cat("wshEventData:", reqId, "\n") 299 | }, 300 | 301 | historicalSchedule= function(reqId, startDateTime, endDateTime, timeZone, sessions) { 302 | self$context$schedule <- sessions 303 | cat("historicalSchedule:", reqId, startDateTime, endDateTime, timeZone, "\n") 304 | }, 305 | 306 | userInfo= function(reqId, whiteBrandingId) 307 | cat("userInfo:", reqId, whiteBrandingId, "\n"), 308 | 309 | historicalDataEnd= function(reqId, startDate, endDate) 310 | cat("historicalDataEnd:", reqId, startDate, endDate, "\n"), 311 | 312 | currentTimeInMillis= function(timeInMillis) { 313 | self$context$timemillis <- timeInMillis 314 | cat("currentTimeInMillis:", timeInMillis, "\n") 315 | } 316 | ) 317 | ) 318 | -------------------------------------------------------------------------------- /R/structs.R: -------------------------------------------------------------------------------- 1 | # 2 | # IB structs 3 | # 4 | 5 | Execution <- list(orderId= 0L, 6 | execId= "", 7 | time= "", 8 | acctNumber= "", 9 | exchange= "", 10 | side= "", 11 | shares= 0, 12 | price= 0, 13 | permId= "", 14 | clientId= 0L, 15 | liquidation= FALSE, 16 | cumQty= 0, 17 | avgPrice= 0, 18 | orderRef= "", 19 | evRule= "", 20 | evMultiplier= NA_real_, 21 | modelCode= "", 22 | lastLiquidity= 0L, 23 | pendingPriceRevision= FALSE, 24 | submitter= "", 25 | optExerciseOrLapseType= "") 26 | 27 | ExecutionFilter <- list(clientId= 0L, 28 | acctCode= "", 29 | time= "", 30 | symbol= "", 31 | secType= "", 32 | exchange= "", 33 | side= "", 34 | lastNDays= NA_integer_, 35 | specificDates= integer()) 36 | 37 | ComboLeg <- list(conId= 0L, 38 | ratio= 0L, 39 | action= "", 40 | exchange= "", 41 | openClose= 0L, 42 | shortSaleSlot= 0L, 43 | designatedLocation= "", 44 | exemptCode= -1L) 45 | 46 | DeltaNeutralContract <- list(conId= 0L, 47 | delta= 0, 48 | price= 0) 49 | 50 | Contract <- list(conId= 0L, 51 | symbol= "", 52 | secType= "", 53 | lastTradeDateOrContractMonth= "", # xxxx [xxxx [xxxx]] 54 | # - lastTradedDateOrContractMonth / bond maturity 55 | # - ContractDetails$lastTradeTime 56 | # - ContractDetails$timeZoneId 57 | strike= NA_real_, 58 | right= "", 59 | multiplier= NA_real_, 60 | exchange= "", 61 | primaryExchange= "", 62 | currency= "", 63 | localSymbol= "", 64 | tradingClass= "", 65 | includeExpired= FALSE, 66 | secIdType= "", 67 | secId= "", 68 | description= "", 69 | issuerId= "", 70 | lastTradeDate= "", 71 | comboLegsDescrip= "", 72 | comboLegs= list(), 73 | deltaNeutralContract= NA) 74 | 75 | ContractDetails <- list(contract= Contract, 76 | marketName= "", 77 | minTick= 0, 78 | orderTypes= "", 79 | validExchanges= "", 80 | priceMagnifier= 0L, 81 | underConId= 0L, 82 | longName= "", 83 | contractMonth= "", 84 | industry= "", 85 | category= "", 86 | subcategory= "", 87 | timeZoneId= "", 88 | tradingHours= "", 89 | liquidHours= "", 90 | evRule= "", 91 | evMultiplier= NA_real_, 92 | aggGroup= NA_integer_, 93 | underSymbol= "", 94 | underSecType= "", 95 | marketRuleIds= "", 96 | realExpirationDate= "", 97 | lastTradeTime= "", 98 | stockType= "", 99 | minSize= NA_real_, 100 | sizeIncrement= NA_real_, 101 | suggestedSizeIncrement= NA_real_, 102 | minAlgoSize= NA_real_, 103 | secIdList= character(), 104 | cusip= "", 105 | ratings= "", 106 | descAppend= "", 107 | bondType= "", 108 | couponType= "", 109 | callable= FALSE, 110 | putable= FALSE, 111 | coupon= NA_real_, 112 | convertible= FALSE, 113 | maturity= "", 114 | issueDate= "", 115 | nextOptionDate= "", 116 | nextOptionType= "", 117 | nextOptionPartial= FALSE, 118 | notes= "", 119 | fundName= "", 120 | fundFamily= "", 121 | fundType= "", 122 | fundFrontLoad= "", 123 | fundBackLoad= "", 124 | fundBackLoadTimeInterval= "", 125 | fundManagementFee= "", 126 | fundClosed= FALSE, 127 | fundClosedForNewInvestors= FALSE, 128 | fundClosedForNewMoney= FALSE, 129 | fundNotifyAmount= "", 130 | fundMinimumInitialPurchase= "", 131 | fundSubsequentMinimumPurchase= "", 132 | fundBlueSkyStates= "", 133 | fundBlueSkyTerritories= "", 134 | fundDistributionPolicyIndicator= "", 135 | fundAssetType= "", 136 | ineligibilityReasonList= list(), 137 | eventContract1= "", 138 | eventContractDescription1= "", 139 | eventContractDescription2= "") 140 | 141 | OrderState <- list(status= "", 142 | initMarginBefore= NA_real_, 143 | maintMarginBefore= NA_real_, 144 | equityWithLoanBefore= NA_real_, 145 | initMarginChange= NA_real_, 146 | maintMarginChange= NA_real_, 147 | equityWithLoanChange= NA_real_, 148 | initMarginAfter= NA_real_, 149 | maintMarginAfter= NA_real_, 150 | equityWithLoanAfter= NA_real_, 151 | commission= NA_real_, 152 | minCommission= NA_real_, 153 | maxCommission= NA_real_, 154 | commissionCurrency= "", 155 | marginCurrency= "", 156 | initMarginBeforeOutsideRTH= NA_real_, 157 | maintMarginBeforeOutsideRTH= NA_real_, 158 | equityWithLoanBeforeOutsideRTH= NA_real_, 159 | initMarginChangeOutsideRTH= NA_real_, 160 | maintMarginChangeOutsideRTH= NA_real_, 161 | equityWithLoanChangeOutsideRTH= NA_real_, 162 | initMarginAfterOutsideRTH= NA_real_, 163 | maintMarginAfterOutsideRTH= NA_real_, 164 | equityWithLoanAfterOutsideRTH= NA_real_, 165 | suggestedSize= NA_real_, 166 | rejectReason= "", 167 | orderAllocations= list(), 168 | warningText= "", 169 | completedTime= "", 170 | completedStatus= "") 171 | 172 | SoftDollarTier <- list(name= "", 173 | val= "", 174 | displayName= "") 175 | 176 | Order <- list(orderId= 0L, 177 | clientId= 0L, 178 | permId= "", 179 | action= "", 180 | totalQuantity= 0, 181 | orderType= "", 182 | lmtPrice= NA_real_, 183 | auxPrice= NA_real_, 184 | tif= "", 185 | activeStartTime= "", 186 | activeStopTime= "", 187 | ocaGroup= "", 188 | ocaType= 0L, 189 | orderRef= "", 190 | transmit= TRUE, 191 | parentId= 0L, 192 | blockOrder= FALSE, 193 | sweepToFill= FALSE, 194 | displaySize= NA_integer_, 195 | triggerMethod= 0L, 196 | outsideRth= FALSE, 197 | hidden= FALSE, 198 | goodAfterTime= "", 199 | goodTillDate= "", 200 | rule80A= "", 201 | allOrNone= FALSE, 202 | minQty= NA_integer_, 203 | percentOffset= NA_real_, 204 | overridePercentageConstraints= FALSE, 205 | trailStopPrice= NA_real_, 206 | trailingPercent= NA_real_, 207 | faGroup= "", 208 | faMethod= "", 209 | faPercentage= "", 210 | openClose= "", 211 | origin= 0L, 212 | shortSaleSlot= 0L, 213 | designatedLocation= "", 214 | exemptCode= -1L, 215 | discretionaryAmt= NA_real_, 216 | optOutSmartRouting= FALSE, 217 | auctionStrategy= 0L, 218 | startingPrice= NA_real_, 219 | stockRefPrice= NA_real_, 220 | delta= NA_real_, 221 | stockRangeLower= NA_real_, 222 | stockRangeUpper= NA_real_, 223 | randomizeSize= FALSE, 224 | randomizePrice= FALSE, 225 | volatility= NA_real_, 226 | volatilityType= NA_integer_, 227 | deltaNeutralOrderType= "", 228 | deltaNeutralAuxPrice= NA_real_, 229 | deltaNeutralConId= 0L, 230 | deltaNeutralSettlingFirm= "", 231 | deltaNeutralClearingAccount= "", 232 | deltaNeutralClearingIntent= "", 233 | deltaNeutralOpenClose= "", 234 | deltaNeutralShortSale= FALSE, 235 | deltaNeutralShortSaleSlot= 0L, 236 | deltaNeutralDesignatedLocation= "", 237 | continuousUpdate= FALSE, 238 | referencePriceType= NA_integer_, 239 | basisPoints= NA_real_, 240 | basisPointsType= NA_integer_, 241 | scaleInitLevelSize= NA_integer_, 242 | scaleSubsLevelSize= NA_integer_, 243 | scalePriceIncrement= NA_real_, 244 | scalePriceAdjustValue= NA_real_, 245 | scalePriceAdjustInterval= NA_integer_, 246 | scaleProfitOffset= NA_real_, 247 | scaleAutoReset= FALSE, 248 | scaleInitPosition= NA_integer_, 249 | scaleInitFillQty= NA_integer_, 250 | scaleRandomPercent= FALSE, 251 | scaleTable= "", 252 | hedgeType= "", 253 | hedgeParam= "", 254 | account= "", 255 | settlingFirm= "", 256 | clearingAccount= "", 257 | clearingIntent= "", 258 | algoStrategy= "", 259 | algoParams= character(), 260 | smartComboRoutingParams= character(), 261 | algoId= "", 262 | whatIf= FALSE, 263 | notHeld= FALSE, 264 | solicited= FALSE, 265 | modelCode= "", 266 | orderComboLegs= numeric(), 267 | orderMiscOptions= character(), 268 | referenceContractId= 0L, 269 | peggedChangeAmount= 0, 270 | isPeggedChangeAmountDecrease= FALSE, 271 | referenceChangeAmount= 0, 272 | referenceExchangeId= "", 273 | adjustedOrderType= "", 274 | triggerPrice= NA_real_, 275 | adjustedStopPrice= NA_real_, 276 | adjustedStopLimitPrice= NA_real_, 277 | adjustedTrailingAmount= NA_real_, 278 | adjustableTrailingUnit= 0L, 279 | lmtPriceOffset= NA_real_, 280 | conditions= list(), 281 | conditionsCancelOrder= FALSE, 282 | conditionsIgnoreRth= FALSE, 283 | extOperator= "", 284 | softDollarTier= SoftDollarTier, 285 | cashQty= NA_real_, 286 | mifid2DecisionMaker= "", 287 | mifid2DecisionAlgo= "", 288 | mifid2ExecutionTrader= "", 289 | mifid2ExecutionAlgo= "", 290 | dontUseAutoPriceForHedge= FALSE, 291 | isOmsContainer= FALSE, 292 | discretionaryUpToLimitPrice= FALSE, 293 | autoCancelDate= "", 294 | filledQuantity= NA_real_, 295 | refFuturesConId= NA_integer_, 296 | autoCancelParent= FALSE, 297 | shareholder= "", 298 | imbalanceOnly= FALSE, 299 | routeMarketableToBbo= NA, 300 | parentPermId= "", 301 | usePriceMgmtAlgo= NA, 302 | duration= NA_integer_, 303 | postToAts= NA_integer_, 304 | advancedErrorOverride= "", 305 | manualOrderTime= "", 306 | minTradeQty= NA_integer_, 307 | minCompeteSize= NA_integer_, 308 | competeAgainstBestOffset= NA_real_, 309 | midOffsetAtWhole= NA_real_, 310 | midOffsetAtHalf= NA_real_, 311 | customerAccount= "", 312 | professionalCustomer= FALSE, 313 | bondAccruedInterest= "", 314 | includeOvernight= FALSE, 315 | manualOrderIndicator= NA_integer_, 316 | submitter= "", 317 | deactivate= FALSE, 318 | postOnly= FALSE, 319 | allowPreOpen= FALSE, 320 | ignoreOpenAuction= FALSE, 321 | seekPriceImprovement= NA, 322 | whatIfType= NA_integer_, 323 | slOrderId= NA_integer_, 324 | slOrderType= "", 325 | ptOrderId= NA_integer_, 326 | ptOrderType= "") 327 | 328 | OrderCancel <- list(manualOrderCancelTime= "", 329 | extOperator= "", 330 | manualOrderIndicator= NA_integer_) 331 | 332 | ScannerSubscription <- list(numberOfRows= -1L, 333 | instrument= "", 334 | locationCode= "", 335 | scanCode= "", 336 | abovePrice= NA_real_, 337 | belowPrice= NA_real_, 338 | aboveVolume= NA_integer_, 339 | marketCapAbove= NA_real_, 340 | marketCapBelow= NA_real_, 341 | moodyRatingAbove= "", 342 | moodyRatingBelow= "", 343 | spRatingAbove= "", 344 | spRatingBelow= "", 345 | maturityDateAbove= "", 346 | maturityDateBelow= "", 347 | couponRateAbove= NA_real_, 348 | couponRateBelow= NA_real_, 349 | excludeConvertible= FALSE, 350 | averageOptionVolumeAbove= NA_integer_, 351 | scannerSettingPairs= "", 352 | stockTypeFilter= "") 353 | 354 | WshEventData <- list(conId= NA_integer_, 355 | filter= "", 356 | fillWatchlist= FALSE, 357 | fillPortfolio= FALSE, 358 | fillCompetitors= FALSE, 359 | startDate= "", 360 | endDate= "", 361 | totalLimit= NA_integer_) 362 | -------------------------------------------------------------------------------- /R/IBClient.R: -------------------------------------------------------------------------------- 1 | IBClient <- R6Class("IBClient", 2 | 3 | class= FALSE, 4 | cloneable= FALSE, 5 | lock_class= TRUE, 6 | 7 | private= list( 8 | 9 | socket= NULL, # Socket connection 10 | 11 | serverVersion= NULL, # Returned on connection 12 | serverTimestamp= NULL, # Returned on connection 13 | 14 | id= NULL, # Client ID 15 | 16 | # 17 | # Finalizer 18 | # 19 | finalize= function() { 20 | 21 | self$disconnect() 22 | }, 23 | 24 | encodeInit= function(msg) { 25 | 26 | stopifnot(length(msg) == 1L, 27 | is.character(msg), 28 | !is.na(msg)) 29 | 30 | raw_msg <- charToRaw(msg) # Doesn't terminate with '\0' 31 | 32 | len <- length(raw_msg) 33 | 34 | stopifnot(raw_msg < as.raw(0x80L), # Only ASCII chars are allowed 35 | len <= MAX_MSG_LEN) 36 | 37 | header <- writeBin(len, raw(), size=HEADER_LEN, endian="big") 38 | 39 | # Write to socket 40 | writeBin(c(API_SIGN, header, raw_msg), private$socket) 41 | }, 42 | 43 | # 44 | # Encode and send a message 45 | # 46 | # msgid: message id as integer 47 | # msg: protobuf message 48 | # 49 | encodeMsg= function(msgid, msg) { 50 | 51 | stopifnot(is.integer(msgid), 52 | missing(msg) || inherits(msg, "Message")) 53 | 54 | # Apply offset 55 | msgid <- msgid + PROTOBUF_MSG_ID 56 | 57 | raw_msg <- c(writeBin(msgid, raw(), size=RAWID_LEN, endian="big"), 58 | if(!missing(msg)) RProtoBuf::serialize(msg, NULL)) 59 | 60 | len <- length(raw_msg) 61 | 62 | stopifnot(len <= MAX_MSG_LEN) 63 | 64 | header <- writeBin(len, raw(), size=HEADER_LEN, endian="big") 65 | 66 | # Write to socket 67 | writeBin(c(header, raw_msg), private$socket) 68 | }, 69 | 70 | readInit= function() { 71 | 72 | # Read header and decode message length 73 | len <- readBin(private$socket, integer(), size=HEADER_LEN, endian="big") 74 | 75 | # Invalid socket 76 | if(length(len) == 0L) 77 | stop("lost connection") 78 | 79 | # Header consistency check 80 | stopifnot(len > 0L, 81 | len <= MAX_MSG_LEN) 82 | 83 | raw_msg <- readBin(private$socket, raw(), n=len) 84 | 85 | # Count the fields 86 | n <- sum(raw_msg == as.raw(0L)) 87 | 88 | # Consistency checks 89 | stopifnot(length(raw_msg) == len, 90 | raw_msg[len] == as.raw(0L), 91 | n == 2L) 92 | 93 | readBin(raw_msg, character(), n=n) 94 | }, 95 | 96 | # 97 | # Read one message. BLOCKING 98 | # 99 | # Return a list(msgid(int), msg(message iterator or raw message)) 100 | # 101 | readOneMsg= function() { 102 | 103 | # Read header and decode message length 104 | len <- readBin(private$socket, integer(), size=HEADER_LEN, endian="big") 105 | 106 | # Invalid socket 107 | if(length(len) == 0L) 108 | stop("lost connection") 109 | 110 | # Header consistency check 111 | stopifnot(len > 0L, 112 | len <= MAX_MSG_LEN) 113 | 114 | msgid <- readBin(private$socket, integer(), size=RAWID_LEN, endian="big") 115 | 116 | raw_msg <- readBin(private$socket, raw(), n=len - RAWID_LEN) 117 | 118 | list(msgid=msgid, msg=raw_msg) 119 | }, 120 | 121 | # Convenience wrappers for simple payload requests 122 | req_int= function(msgid, reqId) 123 | private$encodeMsg(msgid, 124 | RProtoBuf::new(IBProto.SingleInt32, value=reqId)), 125 | 126 | req_bool= function(msgid, value) 127 | private$encodeMsg(msgid, 128 | if(value) RProtoBuf::new(IBProto.SingleBool, value=value) 129 | else RProtoBuf::new(IBProto.SingleBool)), 130 | 131 | req_intstring= function(msgid, reqId, data) 132 | private$encodeMsg(msgid, 133 | RProtoBuf::new(IBProto.StringData, reqId=reqId, data=data)), 134 | 135 | encodeargs= function(msgid, descriptor) { 136 | 137 | args <- sapply(formalArgs(sys.function(-1L)), get, envir=parent.frame(), simplify=FALSE) 138 | 139 | stopifnot(names(args) %in% names(descriptor)) 140 | 141 | msg <- maptopb(args, descriptor) 142 | 143 | private$encodeMsg(msgid, msg) 144 | } 145 | 146 | ), 147 | 148 | active= list( 149 | 150 | serVersion= function() private$serverVersion, 151 | 152 | serTimestamp= function() private$serverTimestamp, 153 | 154 | clientId= function() private$id 155 | ), 156 | 157 | public= list( 158 | 159 | connect= function(host="localhost", port=4002L, clientId=1L, connectOptions="", optionalCapabilities="") { 160 | 161 | stopifnot(is.null(private$socket)) 162 | 163 | # Open connection to server 164 | private$socket <- socketConnection(host=host, port=port, open="r+b", blocking=TRUE) 165 | 166 | # Prefix " " to connectOptions, if not empty 167 | if(nzchar(connectOptions, keepNA=TRUE)) 168 | connectOptions <- paste0(" ", connectOptions) 169 | 170 | # Start handshake 171 | private$encodeInit(paste0("v", MIN_CLIENT_VER, "..", MAX_CLIENT_VER, connectOptions)) 172 | 173 | # Server response 174 | res <- private$readInit() 175 | 176 | private$serverVersion <- as.integer(res[1]) 177 | private$serverTimestamp <- res[2] 178 | 179 | message("server version: ", private$serverVersion, " timestamp: ", private$serverTimestamp) 180 | 181 | # Check server version 182 | if(private$serverVersion < MIN_CLIENT_VER || 183 | private$serverVersion > MAX_CLIENT_VER) { 184 | 185 | self$disconnect() 186 | stop("unsupported version") 187 | } 188 | 189 | # startAPI 190 | self$startApi(clientId, optionalCapabilities) 191 | 192 | private$id <- clientId 193 | 194 | # TODO 195 | # Verify that connection was successful 196 | }, 197 | 198 | disconnect= function() { 199 | 200 | if(!is.null(private$socket)) { 201 | 202 | close(private$socket) 203 | 204 | private$socket <- 205 | private$serverVersion <- 206 | private$serverTimestamp <- 207 | private$id <- NULL 208 | } 209 | }, 210 | 211 | # 212 | # Process server responses 213 | # 214 | # Block up to timeout 215 | # If wrap is missing, messages are discarded 216 | # otherwise callbacks are dispatched 217 | # 218 | checkMsg= function(wrap, timeout=0.2) { 219 | 220 | count <- 0L 221 | 222 | while(socketSelect(list(private$socket), write=FALSE, timeout=timeout)) { 223 | 224 | count <- count + 1L 225 | 226 | msg <- private$readOneMsg() 227 | 228 | if(missing(wrap)) 229 | next 230 | 231 | # Decode message 232 | res <- decode(msg, private$serverVersion) 233 | 234 | # Dispatch callback 235 | if(!is.null(res)) 236 | do.call(wrap[[res$fname]], res$fargs) 237 | } 238 | 239 | count 240 | }, 241 | 242 | # ######################################################################## 243 | # 244 | # Send requests to the server 245 | # 246 | # ######################################################################## 247 | 248 | reqMktData= function(reqId, contract, genericTicks, snapshot, regulatorySnapshot=FALSE, mktDataOptions=character()) 249 | private$encodeargs(1L, IBProto.MarketDataRequest), ### REQ_MKT_DATA 250 | 251 | cancelMktData= function(reqId) private$req_int(2L, reqId), ### CANCEL_MKT_DATA 252 | 253 | placeOrder= function(id, contract, order) { 254 | 255 | msgid <- 3L ### PLACE_ORDER 256 | 257 | c <- maptopb(contract, IBProto.Contract, "lastTradeDate") 258 | 259 | n <- length(order$orderComboLegs) 260 | 261 | stopifnot(n %in% c(0L, length(contract$comboLegs))) 262 | 263 | for(i in seq_len(n)) 264 | c$comboLegs[[i]]$perLegPrice <- order$orderComboLegs[i] 265 | 266 | threestatebool <- c("routeMarketableToBbo", 267 | "usePriceMgmtAlgo", 268 | "seekPriceImprovement") 269 | 270 | attachedorders <- c("slOrderId", 271 | "slOrderType", 272 | "ptOrderId", 273 | "ptOrderType") 274 | 275 | o <- maptopb(order, IBProto.Order, c("orderId", 276 | "rule80A", 277 | "auctionStrategy", 278 | "basisPoints", 279 | "basisPointsType", 280 | "orderComboLegs", 281 | "mifid2DecisionMaker", 282 | "mifid2DecisionAlgo", 283 | "mifid2ExecutionTrader", 284 | "mifid2ExecutionAlgo", 285 | "autoCancelDate", 286 | "filledQuantity", 287 | "refFuturesConId", 288 | "shareholder", 289 | "parentPermId", 290 | 291 | # Require separate handling 292 | "totalQuantity", # Decimal 293 | threestatebool, 294 | attachedorders)) 295 | 296 | o$totalQuantity <- as.character(order$totalQuantity) 297 | 298 | for(n in threestatebool) 299 | if(!is.na(order[[n]])) 300 | o[[n]] <- order[[n]] 301 | 302 | if(self$serVersion < MIN_SERVER_VER_ADDITIONAL_ORDER_PARAMS_1) 303 | for(n in c("deactivate", "postOnly", "allowPreOpen", "ignoreOpenAuction")) 304 | if(o$has(n)) stop("Order parameter not supported: ", n) 305 | 306 | if(self$serVersion < MIN_SERVER_VER_ADDITIONAL_ORDER_PARAMS_2) 307 | for(n in c("routeMarketableToBbo", "seekPriceImprovement", "whatIfType")) 308 | if(o$has(n)) stop("Order parameter not supported: ", n) 309 | 310 | ao <- RProtoBuf::new(IBProto.AttachedOrders) 311 | 312 | for(n in attachedorders) { 313 | val <- order[[n]] 314 | 315 | if(is.na(val) || !nzchar(val)) 316 | next 317 | 318 | if(self$serVersion < MIN_SERVER_VER_ATTACHED_ORDERS) 319 | stop("Attached order parameter not supported: ", n) 320 | else 321 | ao[[n]] <- val 322 | } 323 | 324 | msg <- RProtoBuf::new(IBProto.PlaceOrderRequest, 325 | orderId=id, 326 | contract=c, 327 | order=o, 328 | attachedOrders=ao) 329 | 330 | private$encodeMsg(msgid, msg) 331 | }, 332 | 333 | cancelOrder= function(id, orderCancel) 334 | private$encodeMsg(4L, ### CANCEL_ORDER 335 | RProtoBuf::new(IBProto.CancelOrderRequest, 336 | orderId=id, 337 | orderCancel=maptopb(orderCancel, IBProto.OrderCancel))), 338 | 339 | reqOpenOrders= function() private$encodeMsg(5L), ### REQ_OPEN_ORDERS 340 | 341 | reqAccountUpdates= function(subscribe, acctCode) 342 | private$encodeargs(6L, IBProto.AccountDataRequest), ### REQ_ACCT_DATA 343 | 344 | reqExecutions= function(reqId, filter) 345 | private$encodeargs(7L, IBProto.ExecutionRequest), ### REQ_EXECUTIONS 346 | 347 | reqIds= function() 348 | # numIds is omitted as it's deprecated and unused 349 | private$encodeMsg(8L), ### REQ_IDS 350 | 351 | reqContractDetails= function(reqId, contract) 352 | private$encodeargs(9L, IBProto.ContractDataRequest), ### REQ_CONTRACT_DATA 353 | 354 | reqMktDepth= function(reqId, contract, numRows, isSmartDepth, mktDepthOptions=character()) 355 | private$encodeargs(10L, IBProto.MarketDepthRequest), ### REQ_MKT_DEPTH 356 | 357 | cancelMktDepth= function(reqId, isSmartDepth) 358 | private$encodeargs(11L, IBProto.CancelMarketDepth), ### CANCEL_MKT_DEPTH 359 | 360 | reqNewsBulletins= function(allMsgs) private$req_bool(12L, allMsgs), ### REQ_NEWS_BULLETINS 361 | 362 | cancelNewsBulletins= function() private$encodeMsg(13L), ### CANCEL_NEWS_BULLETINS 363 | 364 | setServerLogLevel= function(logLevel) private$req_int(14L, logLevel), ### SET_SERVER_LOGLEVEL 365 | 366 | reqAutoOpenOrders= function(bAutoBind) private$req_bool(15L, bAutoBind), ### REQ_AUTO_OPEN_ORDERS 367 | 368 | reqAllOpenOrders= function() private$encodeMsg(16L), ### REQ_ALL_OPEN_ORDERS 369 | 370 | reqManagedAccts= function() private$encodeMsg(17L), ### REQ_MANAGED_ACCTS 371 | 372 | requestFA= function(faDataType) private$req_int(18L, map_enum2int("FaDataType", faDataType)), ### REQ_FA 373 | 374 | replaceFA= function(reqId, faDataType, xml) 375 | private$encodeMsg(19L, ### REPLACE_FA 376 | RProtoBuf::new(IBProto.FAReplace, 377 | reqId=reqId, 378 | faDataType=map_enum2int("FaDataType", faDataType), 379 | xml=xml)), 380 | 381 | reqHistoricalData= function(reqId, contract, endDateTime, duration, barSizeSetting, 382 | whatToShow, useRTH, formatDate, keepUpToDate, 383 | chartOptions=character()) 384 | private$encodeargs(20L, IBProto.HistoricalDataRequest), ### REQ_HISTORICAL_DATA 385 | 386 | exerciseOptions= function(reqId, contract, exerciseAction, exerciseQuantity, 387 | account, override, manualOrderTime, customerAccount, 388 | professionalCustomer) 389 | private$encodeargs(21L, IBProto.ExerciseOptionsRequest), ### EXERCISE_OPTIONS 390 | 391 | reqScannerSubscription= function(reqId, subscription, scannerSubscriptionOptions=character(), scannerSubscriptionFilterOptions=character()) { 392 | 393 | msgid <- 22L ### REQ_SCANNER_SUBSCRIPTION 394 | 395 | sub <- maptopb(c(subscription, 396 | list(scannerSubscriptionOptions=scannerSubscriptionOptions, 397 | scannerSubscriptionFilterOptions=scannerSubscriptionFilterOptions)), 398 | IBProto.ScannerSubscription) 399 | 400 | msg <- RProtoBuf::new(IBProto.ScannerSubscriptionRequest, 401 | reqId=reqId, 402 | subscription=sub) 403 | 404 | private$encodeMsg(msgid, msg) 405 | }, 406 | 407 | cancelScannerSubscription= function(reqId) private$req_int(23L, reqId), ### CANCEL_SCANNER_SUBSCRIPTION 408 | 409 | reqScannerParameters= function() private$encodeMsg(24L), ### REQ_SCANNER_PARAMETERS 410 | 411 | cancelHistoricalData= function(reqId) private$req_int(25L, reqId), ### CANCEL_HISTORICAL_DATA 412 | 413 | reqCurrentTime= function() private$encodeMsg(49L), ### REQ_CURRENT_TIME 414 | 415 | reqRealTimeBars= function(reqId, contract, barSize, whatToShow, useRTH, realTimeBarsOptions=character()) 416 | private$encodeargs(50L, IBProto.RealTimeBarsRequest), ### REQ_REAL_TIME_BARS 417 | 418 | cancelRealTimeBars= function(reqId) private$req_int(51L, reqId), ### CANCEL_REAL_TIME_BARS 419 | 420 | reqFundamentalData= function(reqId, contract, reportType, fundamentalDataOptions=character()) 421 | private$encodeargs(52L, ### REQ_FUNDAMENTAL_DATA 422 | IBProto.FundamentalDataRequest), 423 | 424 | cancelFundamentalData= function(reqId) private$req_int(53L, reqId), ### CANCEL_FUNDAMENTAL_DATA 425 | 426 | calculateImpliedVolatility= function(reqId, contract, optionPrice, underPrice, miscOptions=character()) 427 | private$encodeargs(54L, ### REQ_CALC_IMPLIED_VOLAT 428 | IBProto.CalculateImpliedVolatilityRequest), 429 | 430 | calculateOptionPrice= function(reqId, contract, volatility, underPrice, miscOptions=character()) 431 | private$encodeargs(55L, ### REQ_CALC_OPTION_PRICE 432 | IBProto.CalculateOptionPriceRequest), 433 | 434 | cancelCalculateImpliedVolatility= function(reqId) private$req_int(56L, reqId), ### CANCEL_CALC_IMPLIED_VOLAT 435 | 436 | cancelCalculateOptionPrice= function(reqId) private$req_int(57L, reqId), ### CANCEL_CALC_OPTION_PRICE 437 | 438 | reqGlobalCancel= function(orderCancel) 439 | private$encodeMsg(58L, ### REQ_GLOBAL_CANCEL 440 | RProtoBuf::new(IBProto.GlobalCancelRequest, 441 | orderCancel=maptopb(orderCancel, IBProto.OrderCancel))), 442 | 443 | reqMarketDataType= function(marketDataType) private$req_int(59L, marketDataType), ### REQ_MARKET_DATA_TYPE 444 | 445 | reqPositions= function() private$encodeMsg(61L), ### REQ_POSITIONS 446 | 447 | reqAccountSummary= function(reqId, group, tags) 448 | private$encodeargs(62L, IBProto.AccountSummaryRequest), ### REQ_ACCOUNT_SUMMARY 449 | 450 | cancelAccountSummary= function(reqId) private$req_int(63L, reqId), ### CANCEL_ACCOUNT_SUMMARY 451 | 452 | cancelPositions= function() private$encodeMsg(64L), ### CANCEL_POSITIONS 453 | 454 | verifyRequest= function(apiName, apiVersion) 455 | private$encodeargs(65L, IBProto.VerifyRequest), ### VERIFY_REQUEST 456 | 457 | verifyMessage= function(apiData) 458 | private$encodeMsg(66L, ### VERIFY_MESSAGE 459 | RProtoBuf::new(IBProto.SingleString, value=apiData)), 460 | 461 | queryDisplayGroups= function(reqId) private$req_int(67L, reqId), ### QUERY_DISPLAY_GROUPS 462 | 463 | subscribeToGroupEvents= function(reqId, groupId) 464 | private$encodeargs(68L, IBProto.SubscribeToGroupEventsRequest), ### SUBSCRIBE_TO_GROUP_EVENTS 465 | 466 | updateDisplayGroup= function(reqId, contractInfo) 467 | private$req_intstring(69L, reqId, contractInfo), ### UPDATE_DISPLAY_GROUP 468 | 469 | unsubscribeFromGroupEvents= function(reqId) private$req_int(70L, reqId), ### UNSUBSCRIBE_FROM_GROUP_EVENTS 470 | 471 | startApi= function(clientId, optionalCapabilities) 472 | private$req_intstring(71L, clientId, optionalCapabilities), ### START_API 473 | 474 | # verifyAndAuthRequest= function(apiName, apiVersion, opaqueIsvKey) { 475 | # 476 | # # WARN: Assume extraAuth = TRUE 477 | # 478 | # msgid <- 72L ### VERIFY_AND_AUTH_REQUEST 479 | # 480 | # msg <- c("1", apiName, apiVersion, opaqueIsvKey) 481 | # 482 | # private$encodeMsg(msgid, msg) 483 | # }, 484 | # 485 | # verifyAndAuthMessage= function(apiData, xyzResponse) private$req_simple(73L, "1", apiData, xyzResponse), ### VERIFY_AND_AUTH_MESSAGE 486 | 487 | reqPositionsMulti= function(reqId, account, modelCode) 488 | private$encodeargs(74L, IBProto.PositionsMultiRequest), ### REQ_POSITIONS_MULTI 489 | 490 | cancelPositionsMulti= function(reqId) private$req_int(75L, reqId), ### CANCEL_POSITIONS_MULTI 491 | 492 | reqAccountUpdatesMulti= function(reqId, account, modelCode, ledgerAndNLV) 493 | private$encodeargs(76L, IBProto.AccountUpdatesMultiRequest), ### REQ_ACCOUNT_UPDATES_MULTI 494 | 495 | cancelAccountUpdatesMulti= function(reqId) private$req_int(77L, reqId), ### CANCEL_ACCOUNT_UPDATES_MULTI 496 | 497 | reqSecDefOptParams= function(reqId, underlyingSymbol, futFopExchange, underlyingSecType, underlyingConId) 498 | private$encodeargs(78L, IBProto.SecDefOptParamsRequest), ### REQ_SEC_DEF_OPT_PARAMS 499 | 500 | reqSoftDollarTiers= function(reqId) private$req_int(79L, reqId), ### REQ_SOFT_DOLLAR_TIERS 501 | 502 | reqFamilyCodes= function() private$encodeMsg(80L), ### REQ_FAMILY_CODES 503 | 504 | reqMatchingSymbols= function(reqId, pattern) 505 | private$req_intstring(81L, reqId, pattern), ### REQ_MATCHING_SYMBOLS 506 | 507 | reqMktDepthExchanges= function() private$encodeMsg(82L), ### REQ_MKT_DEPTH_EXCHANGES 508 | 509 | reqSmartComponents= function(reqId, bboExchange) 510 | private$req_intstring(83L, reqId, bboExchange), ### REQ_SMART_COMPONENTS 511 | 512 | reqNewsArticle= function(reqId, providerCode, articleId, newsArticleOptions=character()) 513 | private$encodeargs(84L, IBProto.NewsArticleRequest), ### REQ_NEWS_ARTICLE 514 | 515 | reqNewsProviders= function() private$encodeMsg(85L), ### REQ_NEWS_PROVIDERS 516 | 517 | reqHistoricalNews= function(reqId, conId, providerCodes, startDateTime, endDateTime, totalResults, historicalNewsOptions=character()) 518 | private$encodeargs(86L, IBProto.HistoricalNewsRequest), ### REQ_HISTORICAL_NEWS 519 | 520 | reqHeadTimestamp= function(reqId, contract, whatToShow, useRTH, formatDate) 521 | private$encodeargs(87L, IBProto.HeadTimestampRequest), ### REQ_HEAD_TIMESTAMP 522 | 523 | reqHistogramData= function(reqId, contract, useRTH, timePeriod) 524 | private$encodeargs(88L, IBProto.HistogramDataRequest), ### REQ_HISTOGRAM_DATA 525 | 526 | cancelHistogramData= function(reqId) private$req_int(89L, reqId), ### CANCEL_HISTOGRAM_DATA 527 | 528 | cancelHeadTimestamp= function(reqId) private$req_int(90L, reqId), ### CANCEL_HEAD_TIMESTAMP 529 | 530 | reqMarketRule= function(marketRuleId) private$req_int(91L, marketRuleId), ### REQ_MARKET_RULE 531 | 532 | reqPnL= function(reqId, account, modelCode) 533 | private$encodeargs(92L, IBProto.PnLRequest), ### REQ_PNL 534 | 535 | cancelPnL= function(reqId) private$req_int(93L, reqId), ### CANCEL_PNL 536 | 537 | reqPnLSingle= function(reqId, account, modelCode, conId) 538 | private$encodeargs(94L, IBProto.PnLSingleRequest), ### REQ_PNL_SINGLE 539 | 540 | cancelPnLSingle= function(reqId) private$req_int(95L, reqId), ### CANCEL_PNL_SINGLE 541 | 542 | reqHistoricalTicks= function(reqId, contract, startDateTime, endDateTime, numberOfTicks, whatToShow, useRTH, ignoreSize, miscOptions=character()) 543 | private$encodeargs(96L, IBProto.HistoricalTicksRequest), ### REQ_HISTORICAL_TICKS 544 | 545 | reqTickByTickData= function(reqId, contract, tickType, numberOfTicks, ignoreSize) 546 | private$encodeargs(97L, IBProto.TickByTickRequest), ### REQ_TICK_BY_TICK_DATA 547 | 548 | cancelTickByTickData= function(reqId) private$req_int(98L, reqId), ### CANCEL_TICK_BY_TICK_DATA 549 | 550 | reqCompletedOrders= function(apiOnly) private$req_bool(99L, apiOnly), ### REQ_COMPLETED_ORDERS 551 | 552 | reqWshMetaData= function(reqId) private$req_int(100L, reqId), ### REQ_WSH_META_DATA 553 | 554 | cancelWshMetaData= function(reqId) private$req_int(101L, reqId), ### CANCEL_WSH_META_DATA 555 | 556 | reqWshEventData= function(reqId, wshEventData) { 557 | 558 | msgid <- 102L ### REQ_WSH_EVENT_DATA 559 | 560 | msg <- maptopb(wshEventData, IBProto.WshEventDataRequest) 561 | 562 | msg$reqId <- reqId 563 | 564 | private$encodeMsg(msgid, msg) 565 | }, 566 | 567 | cancelWshEventData= function(reqId) private$req_int(103L, reqId), ### CANCEL_WSH_EVENT_DATA 568 | 569 | reqUserInfo= function(reqId) private$req_int(104L, reqId), ### REQ_USER_INFO 570 | 571 | reqCurrentTimeInMillis= function() private$encodeMsg(105L), ### REQ_CURRENT_TIME_IN_MILLIS 572 | 573 | cancelContractData= function(reqId) private$req_int(106L, reqId), ### CANCEL_CONTRACT_DATA 574 | 575 | cancelHistoricalTick= function(reqId) private$req_int(107L, reqId) ### CANCEL_HISTORICAL_TICKS 576 | 577 | ) 578 | ) 579 | -------------------------------------------------------------------------------- /R/decode.R: -------------------------------------------------------------------------------- 1 | # 2 | # Decode message 3 | # 4 | decode <- function(msg, ver) 5 | { 6 | stopifnot(is.list(msg)) 7 | 8 | # Find handler 9 | handler <- process[[as.character(msg$msgid)]] 10 | 11 | if(is.null(handler)) { 12 | warning("unknown message id: ", msg$msgid) 13 | NULL 14 | } 15 | else 16 | # Call the appropriate handler 17 | handler(msg$msg, ver) 18 | } 19 | 20 | # 21 | # Validate/convert args 22 | # 23 | validatepb <- function(fname, fargs) 24 | { 25 | # Return callback name and argument list 26 | list(fname=fname, fargs=fargs) 27 | } 28 | 29 | # 30 | # Unmask "mask" into a list of logicals 31 | # 32 | unmask <- function(mask, names) 33 | { 34 | as.list(structure(intToBits(mask)[seq_along(names)] != 0L, 35 | names=names)) 36 | } 37 | 38 | # ############################################################## 39 | # 40 | # Message handlers 41 | # 42 | # ############################################################## 43 | process <- list2env(list( 44 | 45 | # 46 | # Messages using ProtoBuf have an offset applied 47 | # 48 | # msgid -> msgid + PROTOBUF_MSG_ID = 200 49 | # 50 | 51 | # TICK_PRICE 52 | "201"= function(msg, ver) { 53 | 54 | pb <- RProtoBuf::read(IBProto.TickPrice, msg) 55 | 56 | args <- splat(pb, price=NA_real_, size=NA_real_) 57 | 58 | validatepb("tickPrice", list(reqId= args$reqId, 59 | tickType= ticktype(args$tickType), 60 | price= args$price, 61 | size= as.numeric(args$size), 62 | attrib= unmask(args$attrMask, 63 | c("canAutoExecute", "pastLimit", "preOpen")))) 64 | }, 65 | 66 | # TICK_SIZE 67 | "202"= function(msg, ver) { 68 | 69 | pb <- RProtoBuf::read(IBProto.TickString, msg) 70 | 71 | args <- splat(pb) 72 | 73 | validatepb("tickSize", list(reqId= args$reqId, 74 | tickType= ticktype(args$tickType), 75 | size= as.numeric(args$value))) 76 | }, 77 | 78 | # ORDER_STATUS 79 | "203"= function(msg, ver) { 80 | 81 | pb <- RProtoBuf::read(IBProto.OrderStatus, msg) 82 | 83 | args <- splat(pb, whyHeld="") 84 | 85 | args$filled <- as.numeric(args$filled) 86 | args$remaining <- as.numeric(args$remaining) 87 | 88 | validatepb("orderStatus", args) 89 | }, 90 | 91 | # ERR_MSG 92 | "204"= function(msg, ver) { 93 | 94 | pb <- RProtoBuf::read(IBProto.Error, msg) 95 | 96 | validatepb("error", splat(pb, errorCode=NA_integer_, advancedOrderRejectJson="")) 97 | }, 98 | 99 | # OPEN_ORDER 100 | "205"= function(msg, ver) { 101 | 102 | pb <- RProtoBuf::read(IBProto.OpenOrder, msg) 103 | 104 | args <- splat(pb) 105 | 106 | # Check orderId 107 | if(args$orderId != args$order$orderId) 108 | warning("orderId mismatch: ", args$orderId, args$order$orderId) 109 | 110 | # Transfer comboLeg prices 111 | for(i in seq_len(length(args$contract$comboLegs))) 112 | if(hasName(args$contract$comboLegs[[i]], "perLegPrice")) { 113 | args$order$orderComboLegs[i] <- args$contract$comboLegs[[i]]$perLegPrice 114 | args$contract$comboLegs[[i]]$perLegPrice <- NULL 115 | } 116 | 117 | if(any(is.na(args$order$orderComboLegs))) 118 | warning("perLegPrice: not all filled") 119 | 120 | # Conversions 121 | args$order$totalQuantity <- as.numeric(args$order$totalQuantity) 122 | args$order$filledQuantity <- as.numeric(args$order$filledQuantity) 123 | 124 | for(i in seq_len(length(args$orderState$orderAllocations))) 125 | args$orderState$orderAllocations[[i]][2L:6L] <- 126 | as.numeric(args$orderState$orderAllocations[[i]][2L:6L]) # position -> allowedAllocQty 127 | 128 | for(n in c("routeMarketableToBbo", "usePriceMgmtAlgo", "seekPriceImprovement")) { 129 | 130 | val <- args$order[[n]] 131 | 132 | if(val %in% c(0L, 1L)) 133 | args$order[[n]] <- as.logical(val) 134 | else if(!is.na(val)) 135 | warning("unexpected ", n, ": ", val) 136 | } 137 | 138 | validatepb("openOrder", args) 139 | }, 140 | 141 | # ACCT_VALUE 142 | "206"= function(msg, ver) { 143 | 144 | pb <- RProtoBuf::read(IBProto.AccountValue, msg) 145 | 146 | validatepb("updateAccountValue", splat(pb, currency="")) 147 | }, 148 | 149 | # PORTFOLIO_VALUE 150 | "207"= function(msg, ver) { 151 | 152 | pb <- RProtoBuf::read(IBProto.PortfolioValue, msg) 153 | 154 | args <- splat(pb, unrealizedPNL=0) 155 | 156 | args$position <- as.numeric(args$position) 157 | 158 | validatepb("updatePortfolio", args) 159 | }, 160 | 161 | # ACCT_UPDATE_TIME 162 | "208"= function(msg, ver) { 163 | 164 | pb <- RProtoBuf::read(IBProto.SingleString, msg) 165 | 166 | validatepb("updateAccountTime", list(timestamp=pb$value)) 167 | }, 168 | 169 | # NEXT_VALID_ID 170 | "209"= function(msg, ver) { 171 | 172 | pb <- RProtoBuf::read(IBProto.SingleInt32, msg) 173 | 174 | validatepb("nextValidId", list(orderId=pb$value)) 175 | }, 176 | 177 | # CONTRACT_DATA 178 | "210"= function(msg, ver) { 179 | 180 | pb <- RProtoBuf::read(IBProto.ContractData, msg) 181 | 182 | args <- splat(pb) 183 | 184 | args$contractDetails$contract <- args$contract 185 | 186 | fields <- c("minTick", "minSize", "sizeIncrement", "suggestedSizeIncrement", "minAlgoSize") 187 | args$contractDetails[fields] <- as.numeric(args$contractDetails[fields]) 188 | 189 | args$contractDetails$fundDistributionPolicyIndicator <- funddist(args$contractDetails$fundDistributionPolicyIndicator) 190 | args$contractDetails$fundAssetType <- fundtype(args$contractDetails$fundAssetType) 191 | 192 | validatepb("contractDetails", args[c("reqId", "contractDetails")]) 193 | }, 194 | 195 | # EXECUTION_DATA 196 | "211"= function(msg, ver) { 197 | 198 | pb <- RProtoBuf::read(IBProto.ExecutionDetails, msg) 199 | 200 | args <- splat(pb) 201 | 202 | args$execution$shares <- as.numeric(args$execution$shares) 203 | args$execution$cumQty <- as.numeric(args$execution$cumQty) 204 | args$execution$optExerciseOrLapseType <- optexercisetype(args$execution$optExerciseOrLapseType) 205 | 206 | validatepb("execDetails", args) 207 | }, 208 | 209 | # MARKET_DEPTH 210 | "212"= function(msg, ver) { 211 | 212 | pb <- RProtoBuf::read(IBProto.MarketDepth, msg) 213 | 214 | args <- as.list(pb$marketDepthData) 215 | 216 | args$size <- as.numeric(args$size) 217 | 218 | validatepb("updateMktDepth", c(reqId=pb$reqId, args[1L:5L])) 219 | }, 220 | 221 | # MARKET_DEPTH_L2 222 | "213"= function(msg, ver) { 223 | 224 | pb <- RProtoBuf::read(IBProto.MarketDepth, msg) 225 | 226 | args <- as.list(pb$marketDepthData) 227 | 228 | args$size <- as.numeric(args$size) 229 | 230 | # args are not in order, but they are named! 231 | validatepb("updateMktDepthL2", c(reqId=pb$reqId, args)) 232 | }, 233 | 234 | # NEWS_BULLETINS 235 | "214"= function(msg, ver) { 236 | 237 | pb <- RProtoBuf::read(IBProto.NewsBulletin, msg) 238 | 239 | validatepb("updateNewsBulletin", splat(pb)) 240 | }, 241 | 242 | # MANAGED_ACCTS 243 | "215"= function(msg, ver) { 244 | 245 | pb <- RProtoBuf::read(IBProto.SingleString, msg) 246 | 247 | validatepb("managedAccounts", list(accountsList=pb$value)) 248 | }, 249 | 250 | # RECEIVE_FA 251 | "216"= function(msg, ver) { 252 | 253 | pb <- RProtoBuf::read(IBProto.StringData, msg) 254 | 255 | validatepb("receiveFA", 256 | list(faDataType=map_int2enum("FaDataType", pb$reqId), xml=pb$data)) 257 | }, 258 | 259 | # HISTORICAL_DATA 260 | "217"= function(msg, ver) { 261 | 262 | pb <- RProtoBuf::read(IBProto.HistoricalData, msg) 263 | 264 | args <- as.list(pb) 265 | 266 | args$bars <- lapply(args$bars, function(b) { 267 | 268 | res <- splat(b) 269 | 270 | res$volume <- as.numeric(res$volume) 271 | res$wap <- as.numeric(res$wap) 272 | 273 | res 274 | }) 275 | 276 | list(fname="historicalData", fargs=args) 277 | }, 278 | 279 | # BOND_CONTRACT_DATA 280 | "218"= function(msg, ver) { 281 | 282 | pb <- RProtoBuf::read(IBProto.ContractData, msg) 283 | 284 | args <- splat(pb) 285 | 286 | args$contractDetails$contract <- args$contract 287 | 288 | fields <- c("minTick", "minSize", "sizeIncrement", "suggestedSizeIncrement", "minAlgoSize") 289 | args$contractDetails[fields] <- as.numeric(args$contractDetails[fields]) 290 | 291 | validatepb("bondContractDetails", args[c("reqId", "contractDetails")]) 292 | }, 293 | 294 | # SCANNER_PARAMETERS 295 | "219"= function(msg, ver) { 296 | 297 | pb <- RProtoBuf::read(IBProto.SingleString, msg) 298 | 299 | validatepb("scannerParameters", list(xml=pb$value)) 300 | }, 301 | 302 | # SCANNER_DATA 303 | "220"= function(msg, ver) { 304 | 305 | pb <- RProtoBuf::read(IBProto.ScannerData, msg) 306 | 307 | args <- as.list(pb) 308 | 309 | args$data <- lapply(args$data, splat, distance="", 310 | benchmark="", 311 | projection="", 312 | comboKey="") 313 | 314 | validatepb("scannerData", args) 315 | }, 316 | 317 | # TICK_OPTION_COMPUTATION 318 | "221"= function(msg, ver) { 319 | 320 | pb <- RProtoBuf::read(IBProto.TickOptionComputation, msg) 321 | 322 | args <- splat(pb) 323 | 324 | args$tickType <- ticktype(args$tickType) 325 | 326 | idx <- c("impliedVol", "optPrice", "pvDividend", "undPrice") 327 | args[idx[args[idx] == -1]] <- NA_real_ 328 | 329 | idx <- c("delta", "gamma", "vega", "theta") 330 | args[idx[args[idx] == -2]] <- NA_real_ 331 | 332 | validatepb("tickOptionComputation", args) 333 | }, 334 | 335 | # TICK_GENERIC 336 | "245"= function(msg, ver) { 337 | 338 | pb <- RProtoBuf::read(IBProto.TickGeneric, msg) 339 | 340 | args <- splat(pb) 341 | 342 | args$tickType <- ticktype(args$tickType) 343 | 344 | validatepb("tickGeneric", args) 345 | }, 346 | 347 | # TICK_STRING 348 | "246"= function(msg, ver) { 349 | 350 | pb <- RProtoBuf::read(IBProto.TickString, msg) 351 | 352 | args <- splat(pb) 353 | 354 | args$tickType <- ticktype(args$tickType) 355 | 356 | validatepb("tickString", args) 357 | }, 358 | 359 | # CURRENT_TIME 360 | "249"= function(msg, ver) { 361 | 362 | pb <- RProtoBuf::read(IBProto.SingleInt64, msg) 363 | 364 | validatepb("currentTime", list(time=as.integer(pb$value))) 365 | }, 366 | 367 | # REAL_TIME_BARS 368 | "250"= function(msg, ver) { 369 | 370 | pb <- RProtoBuf::read(IBProto.RealTimeBarTick, msg) 371 | 372 | args <- splat(pb) 373 | 374 | args$time <- as.integer(args$time) 375 | 376 | args$volume <- as.numeric(args$volume) 377 | args$wap <- as.numeric(args$wap) 378 | 379 | validatepb("realtimeBar", args) 380 | }, 381 | 382 | # FUNDAMENTAL_DATA 383 | "251"= function(msg, ver) { 384 | 385 | pb <- RProtoBuf::read(IBProto.StringData, msg) 386 | 387 | validatepb("fundamentalData", splat(pb)) 388 | }, 389 | 390 | # CONTRACT_DATA_END 391 | "252"= function(msg, ver) { 392 | 393 | pb <- RProtoBuf::read(IBProto.SingleInt32, msg) 394 | 395 | validatepb("contractDetailsEnd", list(reqId=pb$value)) 396 | }, 397 | 398 | # OPEN_ORDER_END 399 | "253"= function(msg, ver) validatepb("openOrderEnd", list()), 400 | 401 | # ACCT_DOWNLOAD_END 402 | "254"= function(msg, ver) { 403 | 404 | pb <- RProtoBuf::read(IBProto.SingleString, msg) 405 | 406 | validatepb("accountDownloadEnd", list(accountName=pb$value)) 407 | }, 408 | 409 | # EXECUTION_DATA_END 410 | "255"= function(msg, ver) { 411 | 412 | pb <- RProtoBuf::read(IBProto.SingleInt32, msg) 413 | 414 | validatepb("execDetailsEnd", list(reqId=pb$value)) 415 | }, 416 | 417 | # TICK_SNAPSHOT_END 418 | "257"= function(msg, ver) { 419 | 420 | pb <- RProtoBuf::read(IBProto.SingleInt32, msg) 421 | 422 | validatepb("tickSnapshotEnd", list(reqId=pb$value)) 423 | }, 424 | 425 | # MARKET_DATA_TYPE 426 | "258"= function(msg, ver) { 427 | 428 | pb <- RProtoBuf::read(IBProto.MarketDataType, msg) 429 | 430 | validatepb("marketDataType", splat(pb)) 431 | }, 432 | 433 | # COMMISSION_REPORT 434 | "259"= function(msg, ver) { 435 | 436 | pb <- RProtoBuf::read(IBProto.CommissionReport, msg) 437 | 438 | args <- splat(pb, realizedPNL=NA_real_, 439 | yield=NA_real_, 440 | yieldRedemptionDate=NA_integer_) 441 | 442 | args$yieldRedemptionDate <- as.integer(args$yieldRedemptionDate) 443 | 444 | validatepb("commissionReport", list(commissionReport=args)) 445 | }, 446 | 447 | # POSITION_DATA 448 | "261"= function(msg, ver) { 449 | 450 | pb <- RProtoBuf::read(IBProto.Position, msg) 451 | 452 | args <- splat(pb) 453 | 454 | args$position <- as.numeric(args$position) 455 | 456 | validatepb("position", args) 457 | }, 458 | 459 | # POSITION_END 460 | "262"= function(msg, ver) validatepb("positionEnd", list()), 461 | 462 | # ACCOUNT_SUMMARY 463 | "263"= function(msg, ver) { 464 | 465 | pb <- RProtoBuf::read(IBProto.AccountSummary, msg) 466 | 467 | validatepb("accountSummary", splat(pb, currency="")) 468 | }, 469 | 470 | # ACCOUNT_SUMMARY_END 471 | "264"= function(msg, ver) { 472 | 473 | pb <- RProtoBuf::read(IBProto.SingleInt32, msg) 474 | 475 | validatepb("accountSummaryEnd", list(reqId=pb$value)) 476 | }, 477 | 478 | # VERIFY_MESSAGE_API 479 | "265"= function(msg, ver) { 480 | 481 | pb <- RProtoBuf::read(IBProto.SingleString, msg) 482 | 483 | validatepb("verifyMessageAPI", list(apiData=pb$value)) 484 | }, 485 | 486 | # VERIFY_COMPLETED 487 | "266"= function(msg, ver) { 488 | 489 | pb <- RProtoBuf::read(IBProto.VerifyCompleted, msg) 490 | 491 | validatepb("verifyCompleted", splat(pb)) 492 | }, 493 | 494 | # DISPLAY_GROUP_LIST 495 | "267"= function(msg, ver) { 496 | 497 | pb <- RProtoBuf::read(IBProto.StringData, msg) 498 | 499 | validatepb("displayGroupList", list(reqId=pb$reqId, groups=pb$data)) 500 | }, 501 | 502 | # DISPLAY_GROUP_UPDATED 503 | "268"= function(msg, ver) { 504 | 505 | pb <- RProtoBuf::read(IBProto.StringData, msg) 506 | 507 | validatepb("displayGroupUpdated", list(reqId=pb$reqId, contractInfo=pb$data)) 508 | }, 509 | 510 | # POSITION_MULTI 511 | "271"= function(msg, ver) { 512 | 513 | pb <- RProtoBuf::read(IBProto.PositionMulti, msg) 514 | 515 | args <- splat(pb, modelCode="") 516 | 517 | args$position <- as.numeric(args$position) 518 | 519 | validatepb("positionMulti", args) 520 | }, 521 | 522 | # POSITION_MULTI_END 523 | "272"= function(msg, ver) { 524 | 525 | pb <- RProtoBuf::read(IBProto.SingleInt32, msg) 526 | 527 | validatepb("positionMultiEnd", list(reqId=pb$value)) 528 | }, 529 | 530 | # ACCOUNT_UPDATE_MULTI 531 | "273"= function(msg, ver) { 532 | 533 | pb <- RProtoBuf::read(IBProto.AccountUpdateMulti, msg) 534 | 535 | validatepb("accountUpdateMulti", splat(pb, modelCode="", currency="")) 536 | }, 537 | 538 | # ACCOUNT_UPDATE_MULTI_END 539 | "274"= function(msg, ver) { 540 | 541 | pb <- RProtoBuf::read(IBProto.SingleInt32, msg) 542 | 543 | validatepb("accountUpdateMultiEnd", list(reqId=pb$value)) 544 | }, 545 | 546 | # SECURITY_DEFINITION_OPTION_PARAMETER 547 | "275"= function(msg, ver) { 548 | 549 | pb <- RProtoBuf::read(IBProto.SecDefOptParameter, msg) 550 | 551 | validatepb("securityDefinitionOptionalParameter", splat(pb)) 552 | }, 553 | 554 | # SECURITY_DEFINITION_OPTION_PARAMETER_END 555 | "276"= function(msg, ver) { 556 | 557 | pb <- RProtoBuf::read(IBProto.SingleInt32, msg) 558 | 559 | validatepb("securityDefinitionOptionalParameterEnd", list(reqId=pb$value)) 560 | }, 561 | 562 | # SOFT_DOLLAR_TIERS 563 | "277"= function(msg, ver) { 564 | 565 | pb <- RProtoBuf::read(IBProto.SoftDollarTiers, msg) 566 | 567 | validatepb("softDollarTiers", splat(pb, tiers=list())) 568 | }, 569 | 570 | # FAMILY_CODES 571 | "278"= function(msg, ver) { 572 | 573 | pb <- RProtoBuf::read(IBProto.FamilyCodes, msg) 574 | 575 | args <- as.list(pb) 576 | args$familyCodes <- lapply(args$familyCodes, splat, familyCode="") 577 | 578 | validatepb("familyCodes", args) 579 | }, 580 | 581 | # SYMBOL_SAMPLES 582 | "279"= function(msg, ver) { 583 | 584 | pb <- RProtoBuf::read(IBProto.SymbolSamples, msg) 585 | 586 | args <- as.list(pb) 587 | args$contractDescriptions <- lapply(args$contractDescriptions, splat, derivativeSecTypes=character()) 588 | 589 | validatepb("symbolSamples", args) 590 | }, 591 | 592 | # MKT_DEPTH_EXCHANGES 593 | "280"= function(msg, ver) { 594 | 595 | pb <- RProtoBuf::read(IBProto.MarketDepthExchanges, msg) 596 | 597 | args <- as.list(pb) 598 | args$depthMktDataDescriptions <- lapply(args$depthMktDataDescriptions, splat, listingExch="", aggGroup=NA_integer_) 599 | 600 | validatepb("mktDepthExchanges", args) 601 | }, 602 | 603 | 604 | # TICK_REQ_PARAMS 605 | "281"= function(msg, ver) { 606 | 607 | pb <- RProtoBuf::read(IBProto.TickReqParams, msg) 608 | 609 | args <- splat(pb, bboExchange="") 610 | 611 | args$minTick <- as.numeric(args$minTick) 612 | 613 | validatepb("tickReqParams", args) 614 | }, 615 | 616 | # SMART_COMPONENTS 617 | "282"= function(msg, ver) { 618 | 619 | pb <- RProtoBuf::read(IBProto.SmartComponents, msg) 620 | 621 | args <- as.list(pb) 622 | 623 | args$map <- lapply(args$map, as.list) 624 | 625 | list(fname="smartComponents", fargs=args) 626 | }, 627 | 628 | # NEWS_ARTICLE 629 | "283"= function(msg, ver) { 630 | 631 | pb <- RProtoBuf::read(IBProto.NewsArticle, msg) 632 | 633 | validatepb("newsArticle", splat(pb)) 634 | }, 635 | 636 | # TICK_NEWS 637 | "284"= function(msg, ver) { 638 | 639 | pb <- RProtoBuf::read(IBProto.TickNews, msg) 640 | 641 | validatepb("tickNews", splat(pb)) 642 | }, 643 | 644 | # NEWS_PROVIDERS 645 | "285"= function(msg, ver) { 646 | 647 | pb <- RProtoBuf::read(IBProto.NewsProviders, msg) 648 | 649 | validatepb("newsProviders", splat(pb, newsProviders=list())) 650 | }, 651 | 652 | # HISTORICAL_NEWS 653 | "286"= function(msg, ver) { 654 | 655 | pb <- RProtoBuf::read(IBProto.HistoricalNews, msg) 656 | 657 | validatepb("historicalNews", splat(pb)) 658 | }, 659 | 660 | # HISTORICAL_NEWS_END 661 | "287"= function(msg, ver) { 662 | 663 | pb <- RProtoBuf::read(IBProto.HistoricalNewsEnd, msg) 664 | 665 | validatepb("historicalNewsEnd", splat(pb)) 666 | }, 667 | 668 | # HEAD_TIMESTAMP 669 | "288"= function(msg, ver) { 670 | 671 | pb <- RProtoBuf::read(IBProto.StringData, msg) 672 | 673 | validatepb("headTimestamp", list(reqId=pb$reqId, headTimestamp=pb$data)) 674 | }, 675 | 676 | # HISTOGRAM_DATA 677 | "289"= function(msg, ver) { 678 | 679 | pb <- RProtoBuf::read(IBProto.HistogramData, msg) 680 | 681 | args <- as.list(pb) 682 | 683 | args$data <- lapply(args$data, function(b) { 684 | 685 | res <- as.list(b) 686 | 687 | res$size <- as.numeric(res$size) 688 | 689 | res 690 | }) 691 | 692 | list(fname="histogramData", fargs=args) 693 | }, 694 | 695 | # HISTORICAL_DATA_UPDATE 696 | "290"= function(msg, ver) { 697 | 698 | pb <- RProtoBuf::read(IBProto.HistoricalDataUpdate, msg) 699 | 700 | args <- splat(pb) 701 | 702 | args$bar$volume <- as.numeric(args$bar$volume) 703 | args$bar$wap <- as.numeric(args$bar$wap) 704 | 705 | validatepb("historicalDataUpdate", args) 706 | }, 707 | 708 | # REROUTE_MKT_DATA_REQ 709 | "291"= function(msg, ver) { 710 | 711 | pb <- RProtoBuf::read(IBProto.Reroute, msg) 712 | 713 | validatepb("rerouteMktDataReq", splat(pb)) 714 | }, 715 | 716 | # REROUTE_MKT_DEPTH_REQ 717 | "292"= function(msg, ver) { 718 | 719 | pb <- RProtoBuf::read(IBProto.Reroute, msg) 720 | 721 | validatepb("rerouteMktDepthReq", splat(pb)) 722 | }, 723 | 724 | # MARKET_RULE 725 | "293"= function(msg, ver) { 726 | 727 | pb <- RProtoBuf::read(IBProto.MarketRule, msg) 728 | 729 | validatepb("marketRule", splat(pb)) 730 | }, 731 | 732 | # PNL 733 | "294"= function(msg, ver) { 734 | 735 | pb <- RProtoBuf::read(IBProto.PnL, msg) 736 | 737 | validatepb("pnl", splat(pb)) 738 | }, 739 | 740 | # PNL_SINGLE 741 | "295"= function(msg, ver) { 742 | 743 | pb <- RProtoBuf::read(IBProto.PnLSingle, msg) 744 | 745 | args <- splat(pb, dailyPnL=NA_real_, unrealizedPnL=NA_real_, realizedPnL=NA_real_) 746 | 747 | args$position <- as.numeric(args$position) 748 | 749 | validatepb("pnlSingle", args) 750 | }, 751 | 752 | # HISTORICAL_TICKS 753 | "296"= function(msg, ver) { 754 | 755 | pb <- RProtoBuf::read(IBProto.HistoricalTicks, msg) 756 | 757 | args <- as.list(pb) 758 | 759 | args$ticks <- lapply(args$ticks, function(t) { 760 | 761 | res <- as.list(t) 762 | 763 | res$time <- as.integer(res$time) 764 | res$size <- as.numeric(res$size) 765 | 766 | res 767 | }) 768 | 769 | list(fname="historicalTicks", fargs=args) 770 | }, 771 | 772 | # HISTORICAL_TICKS_BID_ASK 773 | "297"= function(msg, ver) { 774 | 775 | pb <- RProtoBuf::read(IBProto.HistoricalTicksBidAsk, msg) 776 | 777 | args <- as.list(pb) 778 | 779 | args$ticks <- lapply(args$ticks, function(t) { 780 | 781 | res <- as.list(t) 782 | 783 | res$time <- as.integer(res$time) 784 | res$attribs <- as.list(res$attribs) 785 | res$bidSize <- as.numeric(res$bidSize) 786 | res$askSize <- as.numeric(res$askSize) 787 | 788 | res 789 | }) 790 | 791 | list(fname="historicalTicksBidAsk", fargs=args) 792 | }, 793 | 794 | # HISTORICAL_TICKS_LAST 795 | "298"= function(msg, ver) { 796 | 797 | pb <- RProtoBuf::read(IBProto.HistoricalTicksLast, msg) 798 | 799 | args <- as.list(pb) 800 | 801 | args$ticks <- lapply(args$ticks, function(t) { 802 | 803 | res <- as.list(t) 804 | 805 | res$time <- as.integer(res$time) 806 | res$attribs <- as.list(res$attribs) 807 | res$size <- as.numeric(res$size) 808 | 809 | res 810 | }) 811 | 812 | list(fname="historicalTicksLast", fargs=args) 813 | }, 814 | 815 | # TICK_BY_TICK 816 | "299"= function(msg, ver) { 817 | 818 | pb <- RProtoBuf::read(IBProto.TickByTickData, msg) 819 | 820 | if(pb$tickType %in% c(1L, 2L)){ 821 | 822 | args <- splat(pb$tickLast, exchange="", specialConditions="") 823 | 824 | args$time <- as.integer(args$time) 825 | args$size <- as.numeric(args$size) 826 | 827 | validatepb("tickByTickAllLast", c(list(reqId=pb$reqId, tickType=pb$tickType), args)) 828 | } 829 | else if(pb$tickType == 3L) { 830 | 831 | args <- splat(pb$tickBidAsk) 832 | 833 | args$time <- as.integer(args$time) 834 | args$bidSize <- as.numeric(args$bidSize) 835 | args$askSize <- as.numeric(args$askSize) 836 | 837 | validatepb("tickByTickBidAsk", c(reqId=pb$reqId, args)) 838 | } 839 | else if(pb$tickType == 4L) { 840 | 841 | args <- splat(pb$tickMidPoint) 842 | 843 | args$time <- as.integer(args$time) 844 | 845 | validatepb("tickByTickMidPoint", c(reqId=pb$reqId, args[c("time", "price")])) 846 | } 847 | else { 848 | warning("TICK_BY_TICK: unknown TickType ", pb$tickType) 849 | NULL 850 | } 851 | }, 852 | 853 | # ORDER_BOUND 854 | "300"= function(msg, ver) { 855 | 856 | pb <- RProtoBuf::read(IBProto.OrderBound, msg) 857 | 858 | validatepb("orderBound", splat(pb)) 859 | }, 860 | 861 | # COMPLETED_ORDER 862 | "301"= function(msg, ver) { 863 | 864 | pb <- RProtoBuf::read(IBProto.CompletedOrder, msg) 865 | 866 | args <- splat(pb) 867 | 868 | # TODO: 869 | # - Transfer comboleg price 870 | # - Decimal Conversion 871 | 872 | # Transfer comboLeg prices 873 | for(i in seq_len(length(args$contract$comboLegs))) 874 | if(hasName(args$contract$comboLegs[[i]], "perLegPrice")) { 875 | args$order$orderComboLegs[i] <- args$contract$comboLegs[[i]]$perLegPrice 876 | args$contract$comboLegs[[i]]$perLegPrice <- NULL 877 | } 878 | 879 | if(any(is.na(args$order$orderComboLegs))) 880 | warning("perLegPrice: not all filled") 881 | 882 | # Conversions 883 | args$order$totalQuantity <- as.numeric(args$order$totalQuantity) 884 | args$order$filledQuantity <- as.numeric(args$order$filledQuantity) 885 | 886 | for(n in c("routeMarketableToBbo", "usePriceMgmtAlgo", "seekPriceImprovement")) { 887 | 888 | val <- args$order[[n]] 889 | 890 | if(val %in% c(0L, 1L)) 891 | args$order[[n]] <- as.logical(val) 892 | else if(!is.na(val)) 893 | warning("unexpected ", n, ": ", val) 894 | } 895 | 896 | validatepb("completedOrder", args) 897 | }, 898 | 899 | # COMPLETED_ORDERS_END 900 | "302"= function(msg, ver) validatepb("completedOrdersEnd", list()), 901 | 902 | # REPLACE_FA_END 903 | "303"= function(msg, ver) { 904 | 905 | pb <- RProtoBuf::read(IBProto.StringData, msg) 906 | 907 | validatepb("replaceFAEnd", splat(pb)) 908 | }, 909 | 910 | # WSH_META_DATA 911 | "304"= function(msg, ver) { 912 | 913 | pb <- RProtoBuf::read(IBProto.StringData, msg) 914 | 915 | validatepb("wshMetaData", splat(pb)) 916 | }, 917 | 918 | # WSH_EVENT_DATA 919 | "305"= function(msg, ver) { 920 | 921 | pb <- RProtoBuf::read(IBProto.StringData, msg) 922 | 923 | validatepb("wshEventData", splat(pb)) 924 | }, 925 | 926 | # HISTORICAL_SCHEDULE 927 | "306"= function(msg, ver) { 928 | 929 | pb <- RProtoBuf::read(IBProto.HistoricalSchedule, msg) 930 | 931 | validatepb("historicalSchedule", splat(pb)) 932 | }, 933 | 934 | # USER_INFO 935 | "307"= function(msg, ver) { 936 | 937 | pb <- RProtoBuf::read(IBProto.StringData, msg) 938 | 939 | validatepb("userInfo", list(reqId=pb$reqId, whiteBrandingId=pb$data)) 940 | }, 941 | 942 | # HISTORICAL_DATA_END 943 | "308" = function(msg, ver) { 944 | 945 | pb <- RProtoBuf::read(IBProto.HistoricalDataEnd, msg) 946 | 947 | validatepb("historicalDataEnd", splat(pb)) 948 | }, 949 | 950 | # CURRENT_TIME_IN_MILLIS 951 | "309" = function(msg, ver) { 952 | 953 | pb <- RProtoBuf::read(IBProto.SingleInt64, msg) 954 | 955 | validatepb("currentTimeInMillis", list(timeInMillis=pb$value)) 956 | } 957 | 958 | )) 959 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------