Git Product home page Git Product logo

rib's People

Contributors

enricoschumann avatar lbilli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rib's Issues

Simple example crashing both rstudio and R client

Thanks a lot for sharing this package! I am very excited to see it and try it as soon as I got home. Unfortunately, I couldn't get it to work. I am using RStudio 1.2.1335 and R 3.5.3. Every time I tried to run the following simple example, the code before line ic$checkMsg(2) works, but when running this line, RStudio 1.2.1335 or R 3.5.3 client will crash immediately. I can not see any error message before the crash. How can I trouble shoot this issue?

library(rib)

# Instantiate wrapper, client and connect
wrap <- IBWrapSimple$new()
ic   <- IBClient$new(wrap)
ic$connect(port=4002, clientId=1)

# Send requests, e.g.:
contract <- IBContract("GOOG")
ic$reqContractDetails(11, contract)

# more requests can go here...

# Parse responses.
# Might need to be called several times to process all messages
ic$checkMsg(2)

# Find results in
wrap$context

# Disconnect
ic$disconnect()

Time zone issue (JST) when connecting to the IB API

Thank you for this new package.

Connection to the API seems ok but with a time zone error : JST (Japan) given by the IB server is not a valid time zone string. The issue seems to be the same for the Julia package Jib.jl

What is not clear to me at this stage is whether this error has a consequence on the next steps. I cannot retrieve any information from the connection but it may be because I am not using the right syntax and not because of this error.

> library(rib)
> # Instantiate wrapper, client and connect
> wrap <- IBWrapSimple$new()
> ic   <- IBClient$new(wrap)
> ic$connect(port=7496, clientId=1)
Server Version and Timestamp: 151 20190820 15:25:04 JST 
Error in checkTZ(substr(s, 19L, nchar(s))) : 
  tz %in% OlsonNames() is not TRUE
> ic$isOpen
[1] TRUE
> ic$reqCurrentTime()
> ic$checkMsg(2)
[1] 0
> wrap$content
NULL

Drop attempt to infer server time zone

Remove the functionality to infer the time zone that TWS is using, which is set at login time.
Let then the user be responsible of keeping track of it.

IB is also moving away from implicit time zones and this feature's cons might outweigh the pros.

Decimal vs floating point data type for sizes

As of API v163, official IB implementations (except C++, see InteractiveBrokers/tws-api#1061) started reporting market data sizes and volumes as decimals instead of integers.

Here numeric (i.e. standard 64-bit floating point) are used instead, which limits the precision to ~16 decimal digits.

Make contract specification more flexible

It is really good to see an up-to-date pure R implementation of the IB API.

For creating a contract with IBContract, would you consider either adding localSymbol or replacing symbol with localSymbol? In my experience, you can unambiguously define any contract via the local symbol, instrument type, exchange and currency (plus possibly the includeExpired flag). (See https://github.com/enricoschumann/IButils#finding-the-contract-specification )

You could then easily define derivatives contracts. As an example, here would be the Euro Bund Future, expiry December 2019:

library("rib")
wrap <- IBWrapSimple$new()
ic   <- IBClient$new(wrap)
ic$connect(port = 7496, clientId = 1)

contract <- IBContract("FGBL DEC 19",
                       secType  = "FUT",
                       exchange = "DTB",
                       currency = "EUR")
ic$reqContractDetails(1, contract)
ic$checkMsg(2)
ic$disconnect()

I am aware that I can later on override contract$localSymbol. I'd just consider it more natural/convenient if the function supported the local symbol.

thank you.

fCondition

great work with this package.

May I ask if it is possible to include more than one condition in your fCondition function?

For instance, in a trailing stop order, could it be possible to use a different trailing offset for say two or more given prices?...

say, I go long at $10 and, place a trailing stop 1% below. can one set a conditional second trailing stop at 0.5%, when price is above $11?

this could make your function very useful to adjusts offset values, when there is a strong trending, like explained here

Getting started

Hi, first at all, thank so much for the package.

I'm trying to test the req/resp example and I getting an error in the connection:

> wrap <- IBWrapSimple$new()
> ic   <- IBClient$new(wrap)
> ic$connect(port=7496, clientId=1)
Error: length(res) == 2L is not TRUE

I'm using TWS972.

For other hand, I'm getting the following functions' output:

> ic$serVersion
NULL
> ic$isOpen
[1] TRUE
> ic$reqCurrentTime()
> ic$checkMsg(2000)
[1] 0
> 

is.null(private$socket) is not TRUE

Hi,

I am trying to connect to IB through Gateway.

The Gateway works as expected when I use http calls, but when I try to use code from docs:

# Instantiate wrapper, client and connect
wrap <- IBWrapSimple$new()
ic   <- IBClient$new(wrap)
ic$connect(host="localhost", port=5000L, clientId=1L)

I got an error:

Error in ic$connect(host = "localhost", port = 5000L, clientId = 1L) : 
  is.null(private$socket) is not TRUE

Live updating dataframe

Hello, I have the following code that I am using to stream data, and hopefully create a live updating plot in R.

Can you please guide me on how I can export the wrap$context$historical field into a R dataframe that is steadily updated as the streamed data comes through?

library(rib)

tickers <- c("AAPL", "GOOG")

wrap <- IBWrapSimple$new()
ic   <- IBClient$new(wrap)

ic$connect(port=7497, clientId=5)

for(i in 1:length(tickers))
  ic$reqHistoricalData(i, IBContract(tickers[i]), endDateTime = "", durationStr = "1 M", barSizeSetting = "1 day", useRTH = "1", 
                       whatToShow = "TRADES", keepUpToDate = TRUE, formatDate = "1")

repeat
  ic$checkMsg()

Error in readBin(private$socket, raw(), n = len) : invalid 'n' argument

Many thanks sharing this package.

I already use it a while and randomly get the follwing error:
Error in readBin(private$socket, raw(), n = len) : invalid 'n' argument

The strange thing ist that this error is showing up randomly, i.e. when I run the same code 10 times in a row it can be that no error is showing up, but the next time each other request is showing the error.

Do you have an idea how this can happen? Your help is really appreciated.

Here is an example code snippet with reponse from the console:

library(rib)
wrap <- IBWrapSimple$new()
ic <- IBClient$new()
ic$connect(port=7500, clientId=1)
contract <- IBContract(symbol="GOOG", secType="STK", exchange="SMART", currency="USD")
ic$reqContractDetails(11, contract)
ic$checkMsg(wrap)
Error in readBin(private$socket, raw(), n = len) : invalid 'n' argument

Alternative implementation based on official cppclient

H!

I am embarrassed to acknowledge that I have just discovered your repo 😞 I have written my own version of the R IB client, and I even named it the same πŸ˜„ Had I known about your package I would most surely not had attempted mine.

I wrap the official cppclient with its obvious advantages like speed and almost out of the box 100% compatibility. The disadvantage, cannot release to CRAN and the user needs to download the official api client code.

I also go quite a bit further than by providing an interceptor style handling of messages which could be used for building complex data processing patterns and bots. The idea is to make the experience quite a bit more user-friendly by providing object constructors and data fetching functionality which would work out of the box.

Obviously, I would love to join efforts but, as you could guess, by now I am inclined to do it the cppclient-way πŸ˜„

Would love to hear your thoughts.

No initialize method for IBClient class after update?

Looks like there is no initialize function now for the IBClient object now.
ic <- IBClient$new(wrap)
Error in IBClient$new(wrap) :
Called new() with arguments, but there is no initialize method.

I have checked the code in the class description and don't see it as well.

Messages not getting decoded properly?

I get warnings when sending requests/receiving messages when using your example/other requests:

I have checked Decoder class but still not sure what's wrong, just getting 'default implementation' message...

ic$reqContractDetails(11, contract)

more requests can go here...

Parse responses

Might need to be called several times to exhaust all messages

ic$checkMsg()
[1] 49
There were 49 warnings (use warnings() to see them)

Find results in

wrap$context
NULL
warnings()
Warning messages:
1: In (function (orderId, contract, order, orderstate) ... : default implementation
2: In (function (orderId, status, filled, remaining, avgFillPrice, ... :
default implementation
3: In (function (orderId, contract, order, orderstate) ... : default implementation
4: In (function (orderId, status, filled, remaining, avgFillPrice, ... :
default implementation
5: In (function (orderId, contract, order, orderstate) ... : default implementation

Just to clarify, the client does get connected and I get responses from the TWS:

ic$connect(port=7496, clientId=1)
server version and timestamp: 175 20220919 10:37:43 British Summer Time

ic$checkMsg()
Managed Accounts: U*****
Next OrderId: 1
Error: -1 2104 Market data farm connection is OK:cafarm
Error: -1 2104 Market data farm connection is OK:hfarm
Error: -1 2104 Market data farm connection is OK:usfuture.il
Error: -1 2104 Market data farm connection is OK:eufarmnj
Error: -1 2104 Market data farm connection is OK:cashfarm
Error: -1 2104 Market data farm connection is OK:usfuture.

Error when fetching contract details

With the latest version of rib (a67af06), when I try to fetch contract details, I get an error. Here is a very stripped-down example to reproduce the error:

library("rib")
port <- 7496
clientId <- 1

wrap <- R6::R6Class("IBWrapCustom",
    class = FALSE,
    cloneable = FALSE,
    lock_class= TRUE,
    inherit = rib::IBWrap,

    public = list(
        error = function(id, errorCode, errorString, advancedOrderRejectJson)
            NULL,
        contractDetails=    function(reqId, contractDetails)
            NULL,
        contractDetailsEnd= function(reqId)
            NULL,
        nextValidId=        function(orderId)
            NULL,
        managedAccounts=    function(accountsList)
            NULL
    )
)

wrap <- wrap$new()
ic <- IBClient$new()

ic$connect(port = port, clientId = clientId)
ic$checkMsg(wrap)

contr <- rib::Contract
contr$secIdType <- "ISIN"
contr$secId <- "CA82509L1076"
contr$exchange <- "NYSE"
contr$secType <- "STK"

ic$reqContractDetails(1, contr)
ic$checkMsg(wrap)
## Error in ev$.validate(arglist, names = names, types = types) : 
##   names(arglist) == names are not all TRUE
## In addition: Warning message:
## In names(arglist) == names :
##   longer object length is not a multiple of shorter object length

ic$disconnect()

With the previous version (748b8f3), I don't get this error.
The latest commit added a field lastTradeDate to contract details. Shouldn't that field also be reflected in inst/data-raw/codes_struct.txt?

Thank you.

How to set-up Market Scanners

Thank you so much for this library. It has helped me tremendously.

I am a bit stuck on how to set-up market scanners. Could you kindly point me to any resource that will help me.

Thanks in advance.

Kind regards
Joe

How to modify callback methods

Hello,

First, let me thank you for creating this package. It is very well written and seems to be truly feature complete, which is great.

Alas, i have a problem. I am trying to modify the IBWrapSimple class to include more complex logic with respect to the various callback methods (mostly tickPrice and tickSize). I have tried creating a new class by copy pasting the source code and making modifications to it, and then instantiating a new wrapper object from that new class. This works well for the most part, except when the checkMsg() calls marketDataType() which then calls map_int2enum(), which cannot be found. It appears to only be visible within the rib namespace, which my new copy pasted version of the class can’t see.

I tried modifying the IBWrapSimple class this way as the public methods in the objects instantiated by IBWrapSimple were blocked. Is there a way to unblock them?

More generally, what would be the preferred approach to modifying callback methods without affecting the behaviour of the rib package?

Thank you,

AS

Not recognising Trigger Price Order parameter

Hi, thank you for writing this great package! Its the only one on Github written in R that truly provides a comprehensive connection to the IB TWS.
While looking at some of the more complicated orders, I came across the following two problems.
The goal is to attach a Trailing Stop Loss order and change the trailing percent parameter when a certain threshold is breached.

However, in the example below, the Trigger Price and the corresponding trailing percent is not recognised, i.e. the order is send to IB TWS, but the trigger price column is empty.

wrap <- IBWrapCustom$new()
ic   <- IBClient$new(wrap)

ic$connect(port=7496, clientId=10)

ic$checkMsg()

ID       <- 4258

Action   <- "BUY"

Contract <- IBContract("AAPL")

 lapply(1:2, function(i) {
  
    if (i == 1){
  
    Order          <- IBOrder(totalQuantity = 10, lmtPrice = 310, action = "BUY")

    Order$orderId  <- ID + i
    
    Order$transmit <- FALSE
    
  } else if (i == 2){
    
    Order                        <- rib::Order
    
    Order$orderId                <- ID + i 
    
    Order$action                 <- "SELL"
    Order$totalQuantity          <- 10
    Order$orderType              <- "TRAIL"
    Order$trailingPercent        <- 0.5
    
    Order$parentId               <- ID + 1
    Order$triggerPrice           <- 315
    Order$adjustableTrailingUnit <- 0
    Order$adjustedTrailingAmount <- 1

    Order$transmit               <- TRUE
    
  }
  
  Order$outsideRth                    <- TRUE
  Order$overridePercentageConstraints <- TRUE
  
  ic$placeOrder(id = ID + i, contract = Contract, order = Order)
 
})

Any clues on what could cause this behaviour?
The second problem is that in another example the trigger price is recognised, but it only accepts adjustableTrailingUnit = 0, which corresponds to trailing amount in nominal change, not in percentage points (adjustableTrailingUnit = 1). Contrary to the code above, this parameter always fails, i.e. attached orders with adjustableTrailingUnit = 1 are always dark in IB TWS (it displays "ticks" in the Adj_Trailing_Amount column). Going through your source sode it is not obvious why Order$adjustableTrailingUnit <- 0 is accepted whereas Order$adjustableTrailingUnit <- 1 is not. It is a small technical difficulty and the only one I haven't been able to solve by myself in an otherwise fantastic package so it would be really great if you could provide some thoughts or fixes.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.