Giter VIP home page Giter VIP logo

ibrokers's People

Contributors

jaryan avatar joshuaulrich avatar phated avatar vspinu avatar wesseldr 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ibrokers's Issues

same day and historical intraday prices

Description

I've posted on stack this issue 2 weeks ago: https://stackoverflow.com/questions/66603261/ibrokers-r-api-and-same-day-intraday-prices

I am using reqHistoricalData to get 1 minutes intraday historical data. The market is open and I am not getting the same day's data. I only get previous trading day's data.

Is it possible to get the same day intraday bar data?

Expected behavior

I am expecting bars for the same day

Minimal, reproducible example

here is the code I am using, it only gives data for the previous day, not same day.

library(tidyverse)
library(IBrokers)
tws = twsConnect()
contract <- twsEquity('VOD','SMART')
VOD_intraday = IBrokers::reqHistoricalData(tws, Contract = contract, barSize = "1 min", duration = "1 D")
VOD_intraday %>% as.data.frame() %>% rownames_to_column(var = "time") %>% arrange(desc(time)) %>% head()

It's 10:28 GMT on 2021-03-29 and London is open. And here is the response - it only gives data from 2020-03-26:

> contract <- twsEquity('VOD','SMART')
> VOD_intraday = IBrokers::reqHistoricalData(tws, Contract = contract, barSize = "1 min", duration = "1 D")
waiting for TWS reply on VOD .... done.
> VOD_intraday %>% as.data.frame() %>% rownames_to_column(var = "time") %>% arrange(desc(time)) %>% head()
                 time VOD.Open VOD.High VOD.Low VOD.Close VOD.Volume VOD.WAP VOD.hasGaps VOD.Count
1 2021-03-26 19:59:00    18.86    18.88   18.85     18.88        281  18.866           0       165
2 2021-03-26 19:58:00    18.86    18.86   18.84     18.86        688  18.850           0       192
3 2021-03-26 19:57:00    18.86    18.86   18.85     18.86        132  18.855           0        62
4 2021-03-26 19:56:00    18.85    18.86   18.84     18.86        144  18.849           0        98
5 2021-03-26 19:55:00    18.84    18.85   18.83     18.85        101  18.839           0        66
6 2021-03-26 19:54:00    18.81    18.84   18.81     18.84        331  18.823           0       134

Instead of VOD, you can use SPY, MSFT or any US security while the US market is open

Session Info

R version 4.0.3 (2020-10-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19041)

Matrix products: default

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

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

other attached packages:
 [1] IBrokers_0.9-12            tidyquant_1.0.2            PerformanceAnalytics_2.0.4 lubridate_1.7.9.2          timetk_2.6.0               quantmod_0.4.17           
 [7] TTR_0.24.2                 xts_0.12.1                 zoo_1.8-8                  forcats_0.5.0              stringr_1.4.0              dplyr_1.0.2               
[13] purrr_0.3.4                readr_1.4.0                tidyr_1.1.2                tibble_3.0.4               ggplot2_3.3.2              tidyverse_1.3.0           

loaded via a namespace (and not attached):
 [1] fs_1.5.0           DiceDesign_1.8-1   httr_1.4.2         tools_4.0.3        backports_1.2.0    utf8_1.1.4         R6_2.5.0           rpart_4.1-15       DBI_1.1.0         
[10] colorspace_2.0-0   yardstick_0.0.7    nnet_7.3-14        withr_2.3.0        tidyselect_1.1.0   curl_4.3           compiler_4.0.3     cli_2.2.0          rvest_0.99.0.9000 
[19] xml2_1.3.2         scales_1.1.1       quadprog_1.5-8     tune_0.1.2         digest_0.6.27      pkgconfig_2.0.3    parallelly_1.21.0  lhs_1.1.1          dbplyr_2.0.0      
[28] rlang_0.4.10       readxl_1.3.1       rstudioapi_0.13    generics_0.1.0     jsonlite_1.7.2     magrittr_2.0.1     tbl2xts_1.0.4      Matrix_1.2-18      Quandl_2.10.0     
[37] Rcpp_1.0.6         munsell_0.5.0      fansi_0.4.1        GPfit_1.0-8        lifecycle_0.2.0    furrr_0.2.1        pROC_1.16.2        stringi_1.5.3      yaml_2.2.1        
[46] MASS_7.3-53        plyr_1.8.6         recipes_0.1.15     grid_4.0.3         parallel_4.0.3     listenv_0.8.0      crayon_1.3.4       fortunes_1.5-4     lattice_0.20-41   
[55] haven_2.3.1        splines_4.0.3      hms_0.5.3          pillar_1.4.7       dials_0.0.9        codetools_0.2-16   parsnip_0.1.4      reprex_0.3.0       glue_1.4.2        
[64] rsample_0.0.8      modelr_0.1.8       vctrs_0.3.6        foreach_1.5.1      cellranger_1.1.0   gtable_0.3.0       future_1.20.1      assertthat_0.2.1   gower_0.2.2       
[73] prodlim_2019.11.13 broom_0.7.2        class_7.3-17       survival_3.2-7     timeDate_3043.102  iterators_1.0.13   lava_1.6.8.1       workflows_0.2.1    globals_0.14.0    
[82] ellipsis_0.3.1     ipred_0.9-9 

Connot connect with tws

What steps will reproduce the problem?
1. run tws. API opened.
2. tws<-twsConnect()
3.

What is the expected output? What do you see instead?
Error in structure(list(s, clientId = clientId, port = port, server.version
= SERVER_VERSION,  : 
  object "SERVER_VERSION" not found


What version of the product are you using? On what operating system?
Windows Vista, R 2.7.2

Please provide any additional information below.


Original issue reported on code.google.com by [email protected] on 12 Nov 2008 at 5:48

Issue with reqIds/ reqMktData v10.2 of IBrokers

Description

I wish to report a problem w.r.t latest version of IBrokers (10.2). There seems to be a conflict processing messages when reqMktData and reqIds are run in two parallel R sessions. I've got two R scripts that run in parallel, Script 1 collects data using reqMktData whereas Script 2 places orders using statistics derived from Script 1. With the latest version of IBrokers, only one the scripts works ok and the other fails with following message.

Error in if (curMsg == .twsIncomingMSG$TICK_PRICE) {msg :
argument is of length zero

Minimal, reproducible example

You can reproduce the problem via below mentioned scripts running in parallel R sessions. To confirm, this problem doesn't occur in older version of IBrokers (9.12)

### Script_1 (reqMktData)

library(data.table)
library(IBrokers)

memory.limit(size = 100000)
tws <- twsConnect(port = 4002)

snapShot= function (twsCon, eWrapper, timestamp, file, playback = 1, ...)
{
  if (missing(eWrapper))
    eWrapper <- eWrapper()
  
  names(eWrapper$.Data$data) <- eWrapper$.Data$symbols
  con <- twsCon[[1]]
  if (inherits(twsCon, "twsPlayback")) {
    sys.time <- NULL
    while (TRUE) {
      if (!is.null(timestamp)) {
        last.time <- sys.time
        sys.time <- as.POSIXct(strptime(paste(readBin(con,
                                                      character(), 2), collapse = " "), timestamp))
        if (!is.null(last.time)) {
          Sys.sleep((sys.time - last.time) * playback)
        }
        curMsg <- .Internal(readBin(con, "character",
                                    1L, NA_integer_, TRUE, FALSE))
        if (length(curMsg) < 1)
          next
        processMsg(curMsg, con, eWrapper, format(sys.time,
                                                 timestamp), file, ...)
      }
      else {
        curMsg <- readBin(con, character(), 1)
        if (length(curMsg) < 1)
          next
        processMsg(curMsg, con, eWrapper, timestamp,
                   file, ...)
        if (curMsg == .twsIncomingMSG$REAL_TIME_BARS)
          Sys.sleep(5 * playback)
      }
    }
  }
  else {
    while (TRUE) {
      socketSelect(list(con), FALSE, NULL)
      curMsg <- .Internal(readBin(con, "character", 1L,
                                  NA_integer_, TRUE, FALSE))
      if (!is.null(timestamp)) {
        processMsg(curMsg, con, eWrapper, format(Sys.time(),
                                                 timestamp), file, ...)
      }
      else {
        processMsg(curMsg, con, eWrapper, timestamp,
                   file, ...)
      }
      if (!any(sapply(eWrapper$.Data$data, is.na)))
        return(do.call(rbind, lapply(eWrapper$.Data$data,
                                     as.data.frame)))
    }
  }
}

sec = twsFuture(symbol = 'NQ',exch = 'CME', expiry = '20230915', currency = 'USD',multiplier = '20')
tm = Sys.time()
Dt = Sys.Date()
ed = paste(Dt,"21:01:00", "BST", sep = " ")

while(tm < ed) {
  dwn_data = reqMktData(tws,CALLBACK = snapShot,eventWrapper = eWrapper.data(length(1)),Contract = sec);
  print(dwn_data)
  Sys.sleep(3)
}

### Script_2 (reqIds) - 

library(data.table)
library(IBrokers)

options(digits.secs = 2)
tws <- twsConnect(port = 4002)
reqIds(tws)

Guidance for adding support for high resolution (tick based) historical data retrieval

Description

Hi Josh,

First, sorry for dropping the ball on issue #19 ; never got to explore the fix on the new branch, life is crazy and never got to the point I had to use the new version (yet).

I have a question about some additional functionality I consider adding, and can use your guidance with that. What I'm referring to is getting tick level historical data (TWS API: High Resolution Historical Data).
I read your library code for supporting the bin based historical data, and the documentation for the C++ API referenced above. The API documentation is based on multiple thread C++ function call API, though, and your implementation seem to go a level below that, and basically imitate the behavior of these functions by basically sending the server the data the execution of these function would have sent, and listening to responses, and parsing it so the user can get the info and process it via a wrapper, imitating the C++ api executing the function call and passing the arguments to it. (Basically polling vs interrupt based approach)

My question:

how did you figure out the coding and structures that needed to be streamed to the server to immediate the execution the function API function call that request the data? And even more importantly, the coding of the data in the incoming data stream? I don't think that there is any ECC equivalent so it seems that getting even one byte wrong will make it very difficult to debug.

I have no idea yet if I'll have the time to actually implement that, so please don't put much time into guiding me step by step, at lest not at the moment. But whether I do that highly depend on how much work it would be for me to copy and modify your code for bin based historical data requests to the tick based one (and also the additional benefit I'll get from it, e.g. how many ticks there were in a single second which is the highest bar resolution allowed). so I wanted to get an idea of how much work it would be. If I ended up doing that I guess you may hear from me again 😄 .

Thanks much!
Yossi

Problem in placing future order

Description

i try to place a future order on a future but it keeps popping error "2 10 200 No security definition has been found for the request ". It indicates problems with my contract specification. However, i can pull historical data and real time data successfully from the same contract.

Expected behavior

[Describe the behavior/output you expected]

Minimal, reproducible example

> placeOrder(tws,twsFuture("HSI",exch= "HKFE",expiry = "20190130"),twsOrder(reqIds(tws),orderType = "MKT",action = "SELL",totalQuantity = 1))
> reqMktData(tws,HSI,snapshot = T)

Session Info

2 10 200 No security definition has been found for the request 
        lastTimeStamp symbol bidSize bidPrice askPrice askSize lastPrice Volume  Open  High   Low Close
1 2020-01-10 17:20:10    HSI       5    28656    28659       4     28658    151 28662 28663 28646 28658

tws <- twsConnect() just hangs often

Description

I run Ibrokers with the latest verison of TWS and the API on windows.
While occasionally it connects, in most cases just hangs after tws <- twsConnect() (Port, host, client id etc. are all default values, and moreover it works every 10th time or so). Even with timeout set or verbose, no output is shown, no log file create in thh TWS folder.
Also, is there a rule if you should start TWS before or after R?
But in either case, only works randomly for me.

Expected behavior

[Describe the behavior/output you expected]

Minimal, reproducible example

 tws <- twsConnect()

Session Info

[Insert your sessionInfo() output]

IBrokers hangs R execution environment

If IBrokers encounters any error, it hangs the RKWard.  Not sure if this is a 
bug in RKWard or IBrokers, but my guess would be IBrokers.

What steps will reproduce the problem?
1. Run the script below in RKWard two times in a row

What is the expected output? What do you see instead?
If you look in the bottom righthand corner it says "R engine busy" in red.  
Functionality such as viewing variable contents no longer works.

What version of the product are you using? On what operating system?
RKWard 0.5.3 on Linux.


Offending script:
library(IBrokers)
tws <- twsConnect()
aapl <- reqHistoricalData(tws, twsEquity("AAPL"), "20100911 16:00:00", barSize 
= "1 min", duration = "1 D")
twsDisconnect(tws)

Original issue reported on code.google.com by [email protected] on 13 Aug 2010 at 3:20

Placing bracket order

Description

Sir, may i know how to place the bracket order? The only relevant information i could find inside the package is "parentid" inside the function "twsOrder".

If i am going to submit a bracket order in r, should i first specified two different twsOrder with one using the orderid of the parent order?

Expected behavior

[Describe the behavior/output you expected]

Minimal, reproducible example

[Insert sample data and code]

Session Info

[Insert your sessionInfo() output]

reqAccountUpdates portfolioValue returning wrong results

Description

I have a position of 10 SPY shares in my paper trading portfolio. They were bought at 411.55 and now have a market value of 4173.40 (roughly). When I run reqAccountUpdates and twsPortfolioValue the results do not match. It seems like all entries are shifted by one row. (see entries below "portfolioValue" in the list below). Also the output for twsPortfolioValue is not correct.

Edit: I just tested it and the functions show the expected behavior when using the current CRAN version IBrokers_0.9-12.

Expected behavior

reqAccountUpdates should return the current positions of the portfolio including position sizes.

Minimal, reproducible example

x <- reqAccountUpdates(conn, subscribe = T, acctCode = "1")
> twsPortfolioValue(x, zero.pos=T)[2, ]
  local sectype marketValue averageCost return position realizedPNL unrealizedPNL
2   SPY     STK     417.344          NA     NA       NA       57.91      411.5534
> x[[2]][[2]]
List of 2
 $ contract      :List of 17
  ..$ conId          : chr "756733"
  ..$ symbol         : chr "SPY"
  ..$ sectype        : chr "STK"
  ..$ exch           : chr "ARCA"
  ..$ primary        : chr "ARCA"
  ..$ expiry         : chr ""
  ..$ strike         : chr "0"
  ..$ currency       : chr "USD"
  ..$ right          : chr "0"
  ..$ local          : chr "SPY"
  ..$ multiplier     : chr ""
  ..$ combo_legs_desc: chr ""
  ..$ comboleg       : chr ""
  ..$ include_expired: chr ""
  ..$ secIdType      : chr ""
  ..$ secId          : chr ""
  ..$ tradingClass   : chr ""
  ..- attr(*, "class")= chr "twsContract"
 $ portfolioValue:List of 7
  ..$ position     : num NA
  ..$ marketPrice  : num 10
  ..$ marketValue  : num 417
  ..$ averageCost  : num 4173
  ..$ unrealizedPNL: num 412
  ..$ realizedPNL  : num 57.9
  ..$ accountName  : chr "0.0"

Session Info

I've loaded some private packages, hence I'd prefer not to share my session info. However, these don't interfere with IBrokers. I'm using Windows 10 x64 and running IB TWS Build 981.2z, Apr 13 2021.

IBrokers_0.10-1

reqHistoricalData: tzone argument does not seem to work correctly

What steps will reproduce the problem?

My local timezone is GMT+2. However, I want to use America/Chicago for 
subsequent operations. Which works with standard time operations like 
Sys.time(). Here is the discrepancy.

> Sys.timezone()
[1] "America/Chicago"
> spy =  reqHistoricalData(tws, twsEquity("SPY"), barSize="5 mins", 
duration="600 S", tzone="America/Chicago")
TWS Message: 2 -1 2100 API client has been unsubscribed from account data. 
waiting for TWS reply on SPY .... done.
> spy
                    SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.WAP SPY.hasGaps SPY.Count
2014-08-08 00:40:00   192.22   192.30  192.19    192.26       3793 192.233      
     0       757
2014-08-08 00:45:00   192.26   192.36  192.19    192.21       4364 192.286      
     0       743
2014-08-08 00:50:00   192.19   192.27  192.14    192.22       3420 192.211      
     0       673
> Sys.time()
[1] "2014-08-07 18:54:58.144836 CDT"
> index(spy)
[1] "2014-08-08 00:40:00 CDT" "2014-08-08 00:45:00 CDT" "2014-08-08 00:50:00 
CDT"
> spy =  reqHistoricalData(tws, twsEquity("SPY"), barSize="5 mins", 
duration="600 S")
waiting for TWS reply on SPY .... done.
> spy
                    SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.WAP SPY.hasGaps SPY.Count
2014-08-08 00:45:00   192.26   192.36  192.19    192.21       4364 192.286      
     0       743
2014-08-08 00:50:00   192.19   192.27  192.14    192.18       3898 192.208      
     0       751
2014-08-08 00:55:00   192.19   192.22  192.13    192.15       2483 192.174      
     0       445

What is the expected output? What do you see instead?

It seems like you're trying to diff the time, but that doesn't seem to work. I 
couldn't find a way to fix this yet.

It seems to think that GMT+1 (?) is equal to America/Chicago. Completely 
unexpected at any rate. Somehow time zone information is lost.

> Sys.setenv(TZ="Europe/Istanbul")
> Sys.time()
[1] "2014-08-08 03:01:04.078636 EEST"

What version of the product are you using? On what operating system?

0.9-10 on OS X

Please provide any additional information below.

You can mail me privately if you'd like. Cheers!

Original issue reported on code.google.com by [email protected] on 8 Aug 2014 at 12:01

Connection problem

What steps will reproduce the problem?
1. tws <- twsConnect()

What is the expected output? What do you see instead?
Error in structure(list(s, clientId = clientId, port = port, 
server.version = SERVER_VERSION,  : 
  object 'SERVER_VERSION' not found

What version of the product are you using? On what operating system?
R version 2.10.0 (2009-10-26)
Ibrokers 0.2-4 (2009-08-11)
OS: Debian Testing

Please provide any additional information below.


Original issue reported on code.google.com by [email protected] on 12 Jan 2010 at 12:49

Realtime feed restart after gateway reset

Hi Josh,

I have been enjoying using IBrokers. However I am having one issue: I’m using the IBController (github) to run IB gateway version 972. Sometimes the internet will drop out and then I will get reconnected from the gateway to IB with no issues. However my live data feed (eg EURAUD) using IBrokers in R which runs continuously will not restart and I have to manually restart my script. Is there a way to fix this so that the R script will stop the feed so that it can restart successfully?

Also – could you point me to an explanation of what blocking=TRUE does? Should I be setting this to false?

Thanks and regards,

Richard

reqHistoricalData does not work due to differing timezones

reqHistoricalData when called without an endDateTime passed grabs the current time from reqCurrentTime and then passes it back to IB as the endDateTime with the GMT timezone.

This will not work if the IBGateway is in a non GMT timezone specifically EDT.

library(IBrokers)
IBConn=ibgConnect(1234)
Contract2get = twsCurrency("EUR",currency = "JPY")
##Does not work
test = reqHistoricalData(IBConn,Contract = Contract2get,whatToShow ='BID_ASK',
  useRTH = "0",barSize = '1 min',duration="1 D")

##Works note my IBG is in EST
test = reqHistoricalData(IBConn,Contract = Contract2get,whatToShow ='BID_ASK',
  useRTH = "0",barSize = '1 min',duration="1 D",
  endDateTime = paste0(gsub("-","",reqCurrentTime(IBConn))," EST"))

Option Greeks

In the TWS API for Python and other languages, I've found documentation on returning greek values for options. Is it possible to do this with the R API? Thank you for the package.

Make placeOrder working with comboleg

Description

I noticed that order combolegs are not supported in current version.

Expected behavior

I changed just 2 lines of code to make the code working.
Hope it is useful!

Minimal, reproducible example

# working function
placeOrder = function(twsconn, Contract, Order) {
  if (!IBrokers::is.twsConnection(twsconn))
    stop("requires twsConnection object")
  if (!IBrokers::is.twsContract(Contract))
    stop("requires twsContract object for Contract arg")
  if (!inherits(Order, "twsOrder"))
    stop("requires twsOrder object for Order arg")
  con <- twsconn[[1]]
  VERSION <- "42"
  if (is.null(Order$hedgeType) || is.null(Order$hedgeParam))
    stop("NEW twsOrder has to be used")
  if (Order$orderId == "")
    Order$orderId <- reqIds(twsconn)
  order <- c(IBrokers::.twsOutgoingMSG$PLACE_ORDER, VERSION, as.character(Order$orderId),
             as.character(Contract$conId), Contract$symbol, Contract$sectype,
             Contract$expiry, Contract$strike, Contract$right, Contract$multiplier,
             Contract$exch, Contract$primary, Contract$currency, Contract$local,
             {
               if (is.null(Contract$tradingClass)) "" else Contract$tradingClass
             }, Contract$secIdType, Contract$secId, Order$action,
             Order$totalQuantity, Order$orderType, Order$lmtPrice,
             Order$auxPrice, Order$tif, Order$ocaGroup, Order$account,
             Order$openClose, Order$origin, Order$orderRef, Order$transmit,
             Order$parentId, Order$blockOrder, Order$sweepToFill,
             Order$displaySize, Order$triggerMethod, Order$outsideRTH,
             Order$hidden)
  if (Contract$sectype == "BAG") {
    #stop("BAG security type not supported") # NEW CODE
    if (is.null(Contract$comboleg)) {
      order <- c(order, 0)
    }
    else {
      comboLeg <- Contract$comboleg
      order <- c(order, length(comboLeg))
      for (i in 1:length(comboLeg)) {
        Leg <- comboLeg[[i]]
        order <- c(order, Leg$conId, Leg$ratio, Leg$action,
                   Leg$exch, Leg$openClose, Leg$shortSaleSlot,
                   #Leg$designatedLocation) # NEW CODE
                   Leg$designatedLocation, Leg$exemptCode) # NEW CODE
      }
      order <- c(order, "0", "0") # NEW CODE  -> orderComboLegsCount, smartComboRoutingParamsCount
    }
  }
  order <- c(order, "", Order$discretionaryAmt, Order$goodAfterTime,
             Order$goodTillDate, Order$faGroup, Order$faMethod, Order$faPercentage,
             Order$faProfile, Order$shortSaleSlot, Order$designatedLocation,
             Order$exemptCode, Order$ocaType, Order$rule80A, Order$settlingFirm,
             Order$allOrNone, Order$minQty, Order$percentOffset, Order$eTradeOnly,
             Order$firmQuoteOnly, Order$nbboPriceCap, Order$auctionStrategy,
             Order$startingPrice, Order$stockRefPrice, Order$delta,
             Order$stockRangeLower, Order$stockRangeUpper, Order$overridePercentageConstraints,
             Order$volatility, Order$volatilityType, Order$deltaNeutralOrderType,
             Order$deltaNeutralAuxPrice, Order$continuousUpdate, Order$referencePriceType,
             Order$trailStopPrice, Order$trailingPercent, Order$scaleInitLevelSize,
             Order$scaleSubsLevelSize, Order$scalePriceIncrement,
             Order$scaleTable, Order$activeStartTime, Order$activeStopTime)
  if (Order$hedgeType != "") {
    order <- c(order, Order$hedgeType, Order$hedgeParam)
  }
  else {
    order <- c(order, Order$hedgeType)
  }
  order <- c(order, Order$optOutSmartRouting, Order$clearingAccount,
             Order$clearingIntent, Order$notHeld, "0", Order$algoStrategy,
             Order$whatIf, "")
  
  writeBin(order, con)
  assign(".Last.orderId", as.integer(Order$orderId), .IBrokersEnv)
  invisible(as.integer(Order$orderId))
}


# SPX options - conId_1 and conId_2
leg1 = IBrokers::twsComboLeg(conId_1, action='SELL', ratio=1, exchange='CBOE'))
leg2 = IBrokers::twsComboLeg(conId_2, action='SELL', ratio=1, exchange='CBOE'))
bag = IBrokers::twsBAG(leg1, leg2)
bag$symbol = 'SPX'
bag$exch     = 'CBOE'

order = IBrokers::twsOrder(
    orderId       = 9999,
    orderType  = 'SNAP MID',
    auxPrice     = '0',
    lmtPrice      = '',
    openClose  = '',
    goodAfterTime = '',
    tif               = 'GTC',
    outsideRTH = '1',
    action        = 'BUY',
    totalQuantity = 1,
    transmit      = TRUE)

IBrokers::placeOrder(twsconn, bag, order)

reqHistoricalData for a time bar returns which segment of the bar [Open, High, Low, or Close]?

Hi,
With the whatToShow parameter, we are able to specify what price to return, but I could find a parameter to specify the time segment from which that price was quoted. For example, If I am getting 5-minute bar data and specify whatToShow = "TRADES", will I get the first, last, high, low, or some other combination of the TRADES for each bar? What is the default behavior of the function and is there a parameter to control that?

Thank you.

reqAccountUpdate

Description

reqAccountUpdates throwing error message and / or warnings. Warning is "In eWrapper$updatePortfolio(curMsg, msg, timestamp, file, ... :
NAs introduced by coercion"

Expected behavior

No warnings / errors - clean runs for years

Minimal, reproducible example

reqAccountUpdates(tws,acct="u*******")

For some reason, Account[[2]][[1]]$portfolioValue$position (for example, or any index) is NA, and the values in the other six fields (marketPrice, marketValue, averageCost,unrealizedPNL, realizedPNL, accountName) are all "shifted down" by one, so for example, the "Position" field shows NA, but the next field ("marketPrice") shows the Position. The same goes for the third field ("marketValue"), which actually shows the number that should be next to "marketPrice" above it.

Session Info

Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19043)

Matrix products: default

Random number generation:
 RNG:     Mersenne-Twister 
 Normal:  Inversion 
 Sample:  Rounding 
 
locale:
[1] LC_COLLATE=English_United States.utf8  LC_CTYPE=English_United States.utf8    LC_MONETARY=English_United States.utf8
[4] LC_NUMERIC=C                           LC_TIME=English_United States.utf8    

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

other attached packages:
 [1] dplyr_1.0.8      DBI_1.1.2        odbc_1.3.3       readr_2.1.2      aws.s3_0.3.21    RQuantLib_0.4.15 lubridate_1.8.0  jsonlite_1.8.0  
 [9] quantmod_0.4.18  TTR_0.24.3       openxlsx_4.2.5   IBrokers_0.10-1  xts_0.12.1       zoo_1.8-10      

loaded via a namespace (and not attached):
 [1] zip_2.2.0           Rcpp_1.0.8.3        pillar_1.7.0        compiler_4.2.0      base64enc_0.1-3     iterators_1.0.14    tools_4.2.0        
 [8] digest_0.6.29       bit_4.0.4           lifecycle_1.0.1     tibble_3.1.6        lattice_0.20-45     pkgconfig_2.0.3     rlang_1.0.2        
[15] foreach_1.5.2       cli_3.3.0           curl_4.3.2          xml2_1.3.3          httr_1.4.2          generics_0.1.2      vctrs_0.4.1        
[22] hms_1.1.1           bit64_4.0.5         grid_4.2.0          tidyselect_1.1.2    glue_1.6.2          R6_2.5.1            fansi_1.0.3        
[29] tzdb_0.3.0          purrr_0.3.4         blob_1.2.3          magrittr_2.0.3      codetools_0.2-18    ellipsis_0.3.2      assertthat_0.2.1   
[36] aws.signature_0.6.0 utf8_1.2.2          stringi_1.7.6       crayon_1.5.1       

Apologies in advance if this is not the correct format. This is the first GitHub issue I've submitted, but I've been using this excellent package for years and rely on it heavily so wanted to see if there was a new release possibly on the TWS side, or even the iBrokers package side, that might be causing this sudden behavior.

If this is an inappropriate forum to bring up this issue, please let me know and I will remove / repost / re-ask elsewhere.

Your API version does not support fractional size rules. Please upgrade to a minimum version 163.

Description

I have installed the latest version of R and IBrokers on Ubuntu 22.04.
I get the error mentioned in the title when I try to get a price quote for EURUSD currency pair

Expected behavior

Return the price quote for EURUSD pair.

Minimal, reproducible example

my_connection <- IBrokers::twsConnect(clientId = 0, port = 7497) # connecting to the paper trading account

isConnected(my_connection) # returns TRUE

# The next line was taken directly from the help documentation. Symbol was set to "EUR"
fx_pair <- twsCurrency(symbol = "EUR",
                                      currency='USD',
                                      exch='IDEALPRO',
                                      primary='',
                                      strike='0.0',
                                      right='',
                                      local='',
                                      multiplier='',
                                      include_expired='0',
                                      conId=0) 

is.twsContract(fx_pair) # returns true

reqMktData(my_connection, new_pair) # returns "TWS Message: 2 1 10285 Your API version does not support fractional size rules. Please upgrade to a minimum version 163."

Session Info

R version 4.3.1 (2023-06-16)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 22.04.3 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.10.0 
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0

locale:
 [1] LC_CTYPE=en_CA.UTF-8       LC_NUMERIC=C               LC_TIME=en_CA.UTF-8        LC_COLLATE=en_CA.UTF-8    
 [5] LC_MONETARY=en_CA.UTF-8    LC_MESSAGES=en_CA.UTF-8    LC_PAPER=en_CA.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_CA.UTF-8 LC_IDENTIFICATION=C       

time zone: America/Toronto
tzcode source: system (glibc)

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

other attached packages:
[1] IBrokers_0.10-2 xts_0.13.1      zoo_1.8-12     

loaded via a namespace (and not attached):
 [1] lubridate_1.9.2   xfun_0.39         lattice_0.21-8    magrittr_2.0.3    glue_1.6.2        stringr_1.5.0     knitr_1.43       
 [8] timechange_0.2.0  generics_0.1.3    lifecycle_1.0.3   cli_3.6.1         grid_4.3.1        ISOweek_0.6-2     compiler_4.3.1   
[15] highr_0.10        rstudioapi_0.15.0 tools_4.3.1       evaluate_0.21     rlang_1.1.1       stringi_1.7.12   

placeOrder does not include/transmit algoParams

Description

In IBrokers 0.10-2 the function IBrokers::placeOrder creates an order with algoStrategy that is written to the connection, but algoParams is not, while it is an argument to twsOrder. Therefore, orders that were created including algoParams tend to be rejected by TWS.

In plain terms: We can tell TWS to create a market order with "algoStrategy" == "Adaptive", but not with an adaptivePriority, e.g. "Urgent".

Expected behavior

The function should include algoParams such that algo orders can be created using IBrokers

Minimal, reproducible example

library(IBrokers) # v 0.10-2

tws <- twsConnect(port = 7496, verbose = TRUE)

contract <- twsFuture(symbol = "ES",
                       exch = "CME",
                       expiry = "202306",
                       currency = "USD")

order <- IBrokers::twsOrder(action = "BUY",
                            totalQuantity = 1,
                            orderType = "MKT",
                            tif = "DAY",
                            transmit = FALSE,
                            algoStrategy = "Adaptive",
                            algoParams = c("1", "adaptivePriority", "Patient")

placeOrder(twsconn = tws,
           Contract = contract,
           Order = order)

Suggested fix

Include Order$algoParams, in line 65 in the placeOrder function. It works on my local version. I'll try to come up with a merge request.

Session Info

R version 4.2.1 (2022-06-23 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.utf8  LC_CTYPE=English_United States.utf8    LC_MONETARY=English_United States.utf8 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.utf8    

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

other attached packages:
[1] twsInstrument_1.4-10      FinancialInstrument_1.3.1 quantmod_0.4.20           TTR_0.24.3                IBrokers_0.10-2           xts_0.13.0               
[7] zoo_1.8-11               

loaded via a namespace (and not attached):
[1] compiler_4.2.1  tools_4.2.1     rstudioapi_0.14 curl_4.3.2      grid_4.2.1      lattice_0.20-45

New incoming message code missing from twsIDs.R ?

Hi,

I noticed that commit a9ae056 introduced support for new incoming message types, such as MARKET_DATA_TYPE, COMMISSION_REPORT, etc (codes 58:68) and they are handled in processMsg.R, e.g:

  else if (curMsg == .twsIncomingMSG$MARKET_DATA_TYPE) {
    msg <- readBin(con, "character", 3)
    eWrapper$marketDataType(curMsg, msg, timestamp, file, 
      ...)
  }
  else if (curMsg == .twsIncomingMSG$COMMISSION_REPORT) {
    msg <- readBin(con, "character", 7)
    eWrapper$commissionReport(curMsg, msg, timestamp, file, 
      ...)
  }

but I do not see these new message codes in twsIDs.R:

`.twsIncomingMSG` <-
structure(list(TICK_PRICE = "1", TICK_SIZE = "2", 
    ORDER_STATUS = "3", ERR_MSG = "4", OPEN_ORDER = "5", ACCT_VALUE = "6", 
    PORTFOLIO_VALUE = "7", ACCT_UPDATE_TIME = "8", NEXT_VALID_ID = "9", 
    CONTRACT_DATA = "10", EXECUTION_DATA = "11", MARKET_DEPTH = "12", 
    MARKET_DEPTH_L2 = "13", NEWS_BULLETINS = "14", MANAGED_ACCTS = "15", 
    RECEIVE_FA = "16", HISTORICAL_DATA = "17", BOND_CONTRACT_DATA = "18", 
    SCANNER_PARAMETERS = "19", SCANNER_DATA = "20", TICK_OPTION_COMPUTATION = "21", 
    TICK_GENERIC = "45", TICK_STRING = "46", TICK_EFP = "47", 
    CURRENT_TIME = "49", REAL_TIME_BARS = "50", FUNDAMENTAL_DATA = "51",
    CONTRACT_DATA_END = "52", OPEN_ORDER_END = "53",
    ACCT_DOWNLOAD_END = "54", EXECUTION_DATA_END = "55",
    DELTA_NEUTRAL_VALIDATION = "56", TICK_SNAPSHOT_END = "57"), .Names = c("TICK_PRICE", 
"TICK_SIZE", "ORDER_STATUS", "ERR_MSG", "OPEN_ORDER", "ACCT_VALUE", 
"PORTFOLIO_VALUE", "ACCT_UPDATE_TIME", "NEXT_VALID_ID", "CONTRACT_DATA", 
"EXECUTION_DATA", "MARKET_DEPTH", "MARKET_DEPTH_L2", "NEWS_BULLETINS", 
"MANAGED_ACCTS", "RECEIVE_FA", "HISTORICAL_DATA", "BOND_CONTRACT_DATA", 
"SCANNER_PARAMETERS", "SCANNER_DATA", "TICK_OPTION_COMPUTATION", 
"TICK_GENERIC", "TICK_STRING", "TICK_EFP", "CURRENT_TIME", "REAL_TIME_BARS",
"FUNDAMENTAL_DATA","CONTRACT_DATA_END", "OPEN_ORDER_END", "ACCT_DOWNLOAD_END",
"EXECUTION_DATA_END","DELTA_NEUTRAL_VALIDATION","TICK_SNAPSHOT_END"
))

I also checked the value of .twsIncomingMSG after installing the latest version and these message indeed seems to be missing, even though the processMsg function does reference them (probably R lazy evaluation is what still allows the code to be built).
Am I missing something, or that these codes were indeed left out?

Thanks.

Make reqContractDetails always working when R API invokes remote TWS

Description

I noticed that when reqContractDetails requests many contracts (ex. option chain) and R invokes a remote TWS (not in the same machine) it doesn't work (socket error).

Expected behavior

I fixed the problem adding a small delay during the iteration. It works very well for me.
Hope it is useful!

Minimal, reproducible example

reqContractDetails <-
  function(conn, Contract, reqId="1", verbose=FALSE,
           eventWrapper=eWrapper(), CALLBACK=twsCALLBACK, ...) {
    
    .reqContractDetails(conn, Contract, reqId)
    
    if(is.null(CALLBACK))
      invisible(return(NULL))
    
    # create an internal eWrapper to *only* handle contract request data,
    # all else is discarded.
    eW <- eWrapper(NULL)
    eW$contractDetails <- function(curMsg, msg, timestamp, file, ...) {
      # custom contractData function called from processMsg
      twsContractDetails(version=msg[1],
                         #reqId=msg[2],
                         contract=twsContract(conId=msg[12+1],
                                              symbol=msg[3],
                                              sectype=msg[4],
                                              expiry=msg[5],  
                                              primary=msg[21],
                                              strike=msg[5+1],
                                              right=msg[6+1],
                                              exch=msg[7+1],
                                              currency=msg[8+1],
                                              multiplier=msg[14+1],
                                              include_expired=Contract$include_expired,
                                              combo_legs_desc="", comboleg="",
                                              local=msg[9+1]),
                         marketName=msg[10+1],
                         tradingClass=msg[11+1],
                         conId=msg[12+1],
                         minTick=msg[13+1],
                         orderTypes=unlist(strsplit(msg[15+1],",")),
                         validExchanges=unlist(strsplit(msg[16+1],",")),
                         priceMagnifier=msg[17+1],
                         underConId=msg[18+1],
                         longName=msg[19+1],
                         contractMonth=msg[22],
                         industry=msg[23],
                         category=msg[24],
                         subcategory=msg[25],
                         timeZoneId=msg[26],
                         tradingHours=msg[27],
                         liquidHours=msg[28])
    }
    
    contracts <- list()
    con <- conn[[1]]
    while (TRUE) {
      socketSelect(list(con), FALSE, NULL) 
      curMsg <- readBin(con, character(), 1)
      if(curMsg != .twsIncomingMSG$CONTRACT_DATA) {
        if(curMsg == .twsIncomingMSG$ERR_MSG) {
          if(!errorHandler(con,verbose,OK=c(165,300,366,2104,2106,2107))){
            warning("error in contract details")
            break
          }
        } else {
          processMsg(curMsg, con, eW, timestamp, file)
          if(curMsg == .twsIncomingMSG$CONTRACT_DATA_END)
            break      
        }
      }
      if(curMsg == .twsIncomingMSG$CONTRACT_DATA) {
        contracts[[length(contracts)+1]] <-
          processMsg(curMsg, con, eW, timestamp, file)
      }
      
       Sys.sleep(0.01) # NEW CODE
    }
    return(contracts)
  }

Add license

Hello. Please add a license so that the community knows what the implications are of forking this repo?

function reqHistoricalData() stalls

Description

try downloading adjusted data using symbol "SXC", the function will just hang

Expected behavior

Would be nice to have a timeout, be that even an hour, that's a must. It's the problem with IB, it's trying to retrieve the data but it can't. You can see that when trying to plot a price graph within IB.

Minimal, reproducible example

contract <- twsEquity("SXC")
reqHistoricalData(conn=tws,
                             Contract=contract,
                             endDateTime="",
                             barSize = "1 hour",
                             duration = "10 Y",
                             useRTH = "1",
                             whatToShow = "ADJUSTED_LAST", 
                             timeFormat = "1",
                             tzone = "",
                             verbose = TRUE,
                             tickerId = "1")

Session Info

> sessionInfo()
R version 3.4.4 (2018-03-15)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Linux Mint 19.3

Matrix products: default
BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1

locale:
 [1] LC_CTYPE=en_NZ.UTF-8       LC_NUMERIC=C               LC_TIME=en_NZ.UTF-8        LC_COLLATE=en_NZ.UTF-8     LC_MONETARY=en_NZ.UTF-8   
 [6] LC_MESSAGES=en_NZ.UTF-8    LC_PAPER=en_NZ.UTF-8       LC_NAME=C                  LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_NZ.UTF-8 LC_IDENTIFICATION=C       

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

other attached packages:
[1] dplyr_0.8.5     quantmod_0.4-16 TTR_0.23-6      plyr_1.8.6      IBrokers_0.9-12 xts_0.12-0      zoo_1.8-7      

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.3       rstudioapi_0.11  magrittr_1.5     tidyselect_1.0.0 munsell_0.5.0    colorspace_1.4-1 lattice_0.20-40  R6_2.4.1        
 [9] rlang_0.4.5      fansi_0.4.1      tools_3.4.4      grid_3.4.4       gtable_0.3.0     utf8_1.1.4       cli_2.0.2        assertthat_0.2.1
[17] tibble_2.1.3     lifecycle_0.2.0  crayon_1.3.4     purrr_0.3.3      ggplot2_3.3.0    vctrs_0.2.4      curl_4.3         glue_1.3.2      
[25] compiler_3.4.4   pillar_1.4.3     scales_1.1.0     jsonlite_1.6.1   pkgconfig_2.0.3 

twsConnect does not respect clientId

When using twsConnect with specific clientId, and that clientId is already in use, the code provides a connection using the next available clientId.

The reason can be seen in twsConnect lines 39-45:

if (curMsg == .twsIncomingMSG$ERR_MSG) {
    errMsg <- readBin(s, character(), 4)
    close(s)
    on.exit()
    return(twsConnect(clientId + 1, host, port, verbose, timeout, filename, blocking))
}

I suggest to add another argument to control how this should work.

Offer

Issue running reqContractDetails

Description

In the new version of IBrokers I can't seem to get reqContractDetails to work with futures.

Minimal, reproducible example

If I run the following code

contract_raw = IBrokers::twsFuture(symbol ='',exch = '',expiry = '',local = 'MESH3')
tws = twsConnect()
contract_details = reqContractDetails(conn = tws,Contract = contract_raw)

I get an error that says:

Error in if (curMsg != .twsIncomingMSG$CONTRACT_DATA) { : 
  argument is of length zero
In addition: Warning message:
In writeBin(as.character(request), con) : problem writing to connection

but running the exact same code with IBrokers version 0.9-12 works without issues.

Bug gettion option info

I use IBrokers on Linux

Simple code and its output:

opt <- twsOption(expiry="20130315", strike="21",local="", right="C", 
symbol="INTC")
reqMktData(tws, opt)


<20130315 15:59:12.920284> id=1 symbol=INTC lastSize: 20 
<20130315 15:59:12.920680> id=1 symbol=INTC Volume: 8449 
<20130315 15:59:12.921341> id=1 symbol=INTC highPrice: 0.65 
<20130315 15:59:12.921747> id=1 symbol=INTC lowPrice: 0.28 
<20130315 15:59:12.922291> id=1 symbol=INTC closePrice: 0.65 
<20130315 15:59:12.922644> id=1 symbol=INTC lastTimestamp: 1363377492 
<20130315 15:59:12.922978> id=1 symbol=INTC Halted: 0.0 
TWS Message: 2 -1 2119 Market data farm is connecting:usopt 
<20130315 15:59:13.174221> id=1 symbol=INTC modelOption: impVol:  
0.1956849992275238  delta: 0.999999999999999  modelPrice:  0.3600011338569562  
pvDiv:  0.0  gamma:  -4.009075294604543E-11  vega:  1.5483198888680883E-14  
theta:  -1.6327539756222365E-4  undPrice:  21.36 
TWS Message: 2 -1 2104 Market data farm connection is OK:usopt 
<20130315 15:59:13.486186> id=1 symbol=INTC closePrice: 0.65 
<20130315 15:59:13.486725> id=1 symbol=INTC Volume: 8457 
<20130315 15:59:13.487112> id=1 symbol=INTC highPrice: 0.65 
<20130315 15:59:13.487522> id=1 symbol=INTC lowPrice: 0.28 
<20130315 15:59:13.487965> id=1 symbol=INTC lastTimestamp: 1363377550 
<20130315 15:59:13.488381> id=1 symbol=INTC lastPrice: 0.37 
<20130315 15:59:13.488759> id=1 symbol=INTC lastSize: 5 
<20130315 15:59:13.489135> id=1 symbol=INTC bidPrice: 0.35  bidSize: 494 
<20130315 15:59:13.489541> id=1 symbol=INTC askPrice: 0.37  askSize: 3406 
<20130315 15:59:13.489936> id=1 symbol=INTC bidSize: 494 
<20130315 15:59:13.490294> id=1 symbol=INTC askSize: 3406 
<20130315 15:59:13.621428> id=1 symbol=INTC optionCallOpenInterest: 42602 
<20130315 15:59:13.621836> id=1 symbol=INTC optionPutOpenInterest: 0 
<20130315 15:59:13.922365> id=1 symbol=INTC bidSize: 513 
<20130315 15:59:13.922732> id=1 symbol=INTC askSize: 3380 
<20130315 15:59:14.003092> id=1 symbol=INTC bidOption: -1 -2 
<20130315 15:59:14.003583> id=1 symbol=INTC askOption: 2.826760735226004 
0.9184333627898871 
<20130315 15:59:14.004014> id=1 symbol=INTC lastOption: 2.826760735226004 
0.9184333627898871 
<20130315 15:59:14.005832> id=1 symbol=INTC modelOption: impVol:  
2.826760735226004  delta: 0.9184333627898871  modelPrice:  0.370000000001884  
pvDiv:  0.0  gamma:  0.5760957620536729  vega:  1.4796454132893913E-4  theta:  
-2.877241331844451  undPrice:  21.36 
<20130315 15:59:14.925486> id=1 symbol=INTC bidSize: 594 
<20130315 15:59:16.629393> id=1 symbol=INTC bidSize: 658 
<20130315 15:59:16.629796> id=1 symbol=INTC askSize: 3358 
<20130315 15:59:17.731887> id=1 symbol=INTC bidSize: 691 
<20130315 15:59:17.732255> id=1 symbol=INTC askSize: 3107 
<20130315 15:59:17.784939> id=1 symbol=INTC modelOption: impVol:  
2.826760735226004  delta: 0.9117902345558202  modelPrice:  0.3609915971320222  
pvDiv:  0.0  gamma:  0.6098849008489783  vega:  1.5586516089414836E-4  theta:  
-3.043136018620518  undPrice:  21.35 
<20130315 15:59:18.035754> id=1 symbol=INTC bidOption: -1 -2 
<20130315 15:59:18.036185> id=1 symbol=INTC askOption: 3.379444579514946 
0.8736280563971375 
<20130315 15:59:18.036636> id=1 symbol=INTC lastOption: 3.379444579514946 
0.8736280563971375 
<20130315 15:59:18.633736> id=1 symbol=INTC bidSize: 626 
<20130315 15:59:18.634130> id=1 symbol=INTC askSize: 2723 
<20130315 15:59:19.001366> id=1 symbol=INTC modelOption: impVol:  
2.826760735226004  delta: 0.9184333627898871  modelPrice:  0.370000000001884  
pvDiv:  0.0  gamma:  0.5760957620536729  vega:  1.4796454132893913E-4  theta:  
-2.877241331844451  undPrice:  21.36 

Please check option implied volatility and other Greeks, the first time it is 
correct (0.1956849992275238), the second and following times 
(2.826760735226004) it is not correct, please suggest how to fix it?



Original issue reported on code.google.com by [email protected] on 15 Mar 2013 at 8:07

Trailing stop order of IBrokers in R

Description

Here is a condition that I want place a TRAIL order with stop price is 43.41 and trailing Percent is 2%.

I use IBrokers.zip of joshuaulrich from github.

However, when I place TRAIL order with trailing Percent, the order is not contained with trailing Percent.

Expected behavior

image

Minimal, reproducible example

twsOrder(action = "SELL", totalQuantity = 399, orderType = "TRAIL",trailingPercent = "2", tif = "GTC", transmit = FALSE, trailStopPrice = 43.41)

Session Info

[Insert your sessionInfo() output]

option contract specification

Description

Specifying vanilla option contracts seems a bit touchy.

Minimal, reproducible example

For some reason these don't work

library(IBrokers)
tws <- twsConnect()
IBrokers::reqMktData(tws, IBrokers::twsOption(local = "SPY 230727C00460000"))
IBrokers::reqMktData(tws, IBrokers::twsOption(local = "SPY 20230727C00460000"))

but this works

library(IBrokers)
tws <- twsConnect()
IBrokers::reqMktData(tws, IBrokers::twsOption(symbol = "SPY", exch = "SMART", 
                                              local = "", right = "C", 
                                              strike = 460, expiry = "20230727"))

Session Info

R version 4.2.1 (2022-06-23) Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 20.04.4 LTS  Matrix products: default BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0  locale:  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8      [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8    LC_PAPER=en_US.UTF-8       LC_NAME=C                   [9] LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C         attached base packages: [1] stats     graphics  grDevices utils     datasets  methods   base       other attached packages: [1] IBrokers_0.10-2 xts_0.13.1      zoo_1.8-12       loaded via a namespace (and not attached): [1] compiler_4.2.1  tools_4.2.1     grid_4.2.1      lattice_0.20-45
--
 

duplicate order IDs

I have some problems with order IDs.

placeOrder sometimes works, sometimes does not and I cannot find out why.

I think it has to do with the duplicate order IDs, which is the message I get 
when running portfolio <- 
twsPortfolioValue(reqAccountUpdates(tws),zero.pos=FALSE).

However I do not understand how those duplicate IDs can exist, if I am always 
using this sequence for the order creation:
"
  id <- reqIds(tws)
  placeOrder(tws, future.NameTrade, twsOrder(id, action = "SELL", totalQuantity = noFut, orderType = "MKT", goodAfterTime = "22:14:00 CET")) 
"

Thus, I always create new id. 

Once the duplicate order message appears, there is no way to execute orders 
programmatically from R, and I have to go manually to either Gateway or TWS and 
"reset API order id sequence".

Is there a programmatic way from R to reset API order id sequence? Or how to 
get from this situation? I would like everything to run automatically and not 
have to manually reset orders ever.

Thank you for a reply,

Jozef

Original issue reported on code.google.com by [email protected] on 5 Oct 2012 at 9:09

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.