Will it be possible for someone to provide me a working example of reqExecutions? I am having a hard time with the ewrapper and callback mechanism. After searching google for working examples, I could not get my hands on anything that would simply work. Please note that I am not a programmer and that is why having a hard time getting my head wrapped around ewrapper and callback.
reqExecutions IBrokers package
2.4k Views Asked by aajkaltak At
1
There are 1 best solutions below
Related Questions in R
- How to make an R Shiny app with big data?
- How do I keep only specific rows based on whether a column has a specific value?
- Likert scale study - ordinal regression model
- Extract a table/matrix from R into Excel with same colors and stle
- How can I solve non-conformable arguments in R netmeta::discomb (Error in B.matrix %*% C.matrix)?
- Can raw means and estimated marginal means be the same ? And when?
- Understanding accumulate function when .dir is set to "backwards"
- Error in if (nrow(peaks) > 0) { : argument is of length zero Calls: CopywriteR ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous> Execution ha
- How to increase quality of mathjax output?
- Convert the time intervals to equal hours and fill in the value column
- How to run an R function getpoints() from IPDfromKM package in an R shiny app which in R pops up a plot that utilizes clicks to capture coordinates?
- Replace NA in list of dfs in certain columns and under certain conditions
- R and text on Cyrillic
- The ts() function in R is returning the correct start and frequency but not end value which is 1 and not 179
- TROUBLING with the "DROP_NA" Function
Related Questions in INTERACTIVE-BROKERS
- IBKR API: How do I capture and store the Close price from streaming data?
- C# Interactive brokers api load expiration dates for options
- Interactive Brokers - IB Gateway API disconnects sporadically
- Callback Function when Requesting Market Data using ib_insync and Interactive Brokers
- reqFundamentalData IBKR
- Running InteractiveBrokers Client Portal API Gateway in a Docker container
- ibapi / TWS api looping unexpectedly
- Error encountered with Interactive Brokers API - Market data farm connection issues, API version error, and unsuccessful update attempt
- IBKR TWS API - reqRealTimeBars under delayed streaming for equities
- For-If loop in python not working as intended
- Refreshing data after query includes "Promoting headers" creates "Column wasn't found" error
- Retrieve SP500 index historical data from InteractiveBroker API
- How to fix this attribute error in Interactive Brokers Python API?
- Interactive Broker watchlist maintenance via API
- interactive brokers tick by tick data
Related Questions in IBROKERS
- Subsetting reqAccountDeatils() cannot convert into Dataframe
- Can no longer retrieve snapshot data from Ibrokers
- Problem retrieving data from Interactive Brokers using R IBrokers package
- R IBrokers reqopenorders not updating
- How to handle RSS in IBKR in TWS?
- Swing high and low from Pine to R
- IBrokers R API and same day intraday prices
- Using IBrokers and R, what is the appropriate way to retrieve live trading data for multiple stocks?
- Using IBrokers and R, what is the appropriate way to retrieve last traded price during live trading session?
- Is there a from and a to argument for reqHistoricalData in IBrokers?
- Using R and IBrokers, what is the function to call to get the bid and ask prices of given stock symbol?
- Cannot connect to TWS using IBrokers with R
- How to trade multiple equities at once using Ibrokers in R
- How do I get implied volatility from TWS into R using IBrokers?
- Trailing stop order of IBrokers in R
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular # Hahtags
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Disclaimer
Before answering this question, I feel I should emphasize the disclaimer given at the very start of the IBrokers documentation:
So it looks like this package is designed and maintained by independent programmers who may or may not have a good tie-in with official IB API development now or in the future.
Further to the above, I looked at a lot of the package source, and it's fairly incomplete, vis-à-vis the actual IB API source. In fact, you've stumbled upon one of the strands of incompleteness; in the IBrokers Reference Card it says:
(Note: You can access the reference card with
IBrokersRef(), if you've configured youroptions()$pdfviewer. If not, you can just open the PDF manually; runsystem.file('doc/IBrokersREFCARD.pdf',package='IBrokers')to get its location.)So, the bottom line is, be careful with this package; you shouldn't rely on it for real trading unless you really know what you're doing.
Functionality
Taking a look at the actual
reqExecutions()package function, we have:To summarize the above, it:
is.twsConnection(), it just checks that it inherits fromtwsConnectionortwsconn. You can create such a connection withtwsConnect(). It's a plain R environment internally, classed astwsconn.`[[`()function for thetwsconnclass. If you look intoIBrokers:::`[[.twsconn`, you see it just returns thetwsconn$connenvironment entry.writeBin()): a request type enumeration, a request version, a request identifier (which could be used to differentiate multiple simultaneous requests of the same type), and then 7 filter fields. (Unfortunately, it requires the caller to fully specify all filter fields.) It then returns immediately without waiting for a response.Contrast the above with a fully-implemented request function,
reqCurrentTime():This:
.reqCurrentTime()to send the actual request, similar to whatreqExecutions()does. I won't include it here, but you can view its body withIBrokers:::.reqCurrentTime.eWrapper()which it strangely namese_current_time.currentTime()on the callback list object. The handler simply returns the second field,msg[2], which represents the server's idea of the current time, encoded as a Unix epoch value (seconds since 1970-01-01).curMsg, which is a code representing the message type, and callsprocessMsg()on it. This is another function provided by theIBrokerspackage. This is the function that actually switches on the message code and calls the appropriate callback function one_current_time, passing itcurMsgas well as the code-specific trailing fields, decoded via a call toreadBin()(not shown above; seeprocessMsgfor the code).msg[2], the second field after the message code) intocurrentTime.processMsg()actually triggered a default handler which doesn't do anything useful, and thecurrentTimevalue would be ignored.)currentTimevalue. All that's really required here is classing it as POSIXt and POSIXct, since the POSIXct type is conveniently implemented by storing the Unix epoch time to represent a date/time point.So, as you can see,
reqCurrentTime()is doing a lot more thanreqExecutions(). In its current form,reqExecutions()doesn't do anything to process the response, so it's not really useful at all.Solution
Since I'm familiar with the IB API, I was able to fill in the missing functionality, which I present below.
As a side note, I referenced the C++ API source code which is available from https://www.interactivebrokers.com/en/index.php?f=5041; the official API source can be taken as authoritative with respect to how the client needs to interact with the socket. For example, you can view the
EClient::reqExecutions()function in/TWS API/source/CppClient/client/EClient.cppto see how it encodes request fields onto the socket, and similarly you can view theEDecoder::processExecutionDataMsg()function in the/TWS API/source/CppClient/client/EDecoder.cppfile to see how it decodes the response from the server. Basically, it uses some C preprocessor macros (ENCODE_FIELD()andDECODE_FIELD()) which expand to a call to some C++ template functions for encoding (template<class T> void EClient::EncodeField(std::ostream& os, T value)) and C++ overloaded functions for decoding (bool EDecoder::DecodeField(bool/int/long/double/std::string& doubleValue, const char*& ptr, const char* endPtr)) which ultimately use the C++ streaming operators to stream primitive fields to the socketstd::ostreamfollowed by a NUL for encoding, and callatoi(),atof(), orstd::string::operator=()for decoding right from the socket buffer.I also recommend looking into the official API documentation at https://www.interactivebrokers.com/en/software/api/api.htm.
Firstly, notice that
IBrokersprovides functions liketwsContract()andtwsOrder()to allow constructing TWS-specific data objects. There's notwsExecution()function, so I wrote my own, following the same style of object construction, including attaching atwsExecutionS3 class. I also wrote aprint.twsExecution()function sotwsExecutionobjects would print the same way as the others, which basically meansstr(unclass(x)).Secondly, I wrote my own replacement for
reqExecutions()calledreqExecutions2()which encodes the request data onto the socket as perreqExecutions(), and then overrides the response handler and iterates on the socket waiting for response messages, similar toreqCurrentTime(). I was a little bit more verbose with the code, as I tried to follow the C++ algorithm as closely as possible, including its request version checks on response handling to conditionally take certain fields off the socket. I also included monitoring for error messages from the server, so that the while loop automatically breaks and the function returns on errors.reqExecutions2()returns all response records as a list, where each component is a nested list ofreqId,contract, andexecutioncomponents. This follows theexecDetails()callback design in the official API; see https://www.interactivebrokers.com/en/software/api/api.htm (C++ -> Class EWrapper Functions -> Executions -> execDetails()).Lastly, for convenience I wrote a wrapper around
reqExecutions2()calledreqExecutionsFrame(), which converts the list of records into a single data.frame.So, without further ado, here's the code:
Here's a demo on my paper trading account: