Has anybody here used the IB API in their own application before?
Has anybody here used the IB API in their own application before?
Have a look at:
IbPy https://www.youtube.com/watch?v=Bu0kpU-ozaw
PyAlgoTrade http://gbeced.github.io/pyalgotrade/
Dr Tom Starke http://www.drtomstarke.com/index.php/buying-and-selling-with-ib
QuantStart (Michael Halls-Moore) http://www.quantstart.com/articles/Using-Python-IBPy-and-the-Interactive-Brokers-API-to-Automate-Trades
I'm not sure what has happened to
IbPython3 (Colin Alexander) https://plus.google.com/102457377988694299249/videos
but I assume he wants to monetarise it in some way. I may be wholly wrong.
P.
About a year ago I looked at all of the python based IB APIs.
I encountered behavior I did not like in all of them.
Sorry, but I dont remember the details.
Also I looked at an R package called:
IBrokers
I am happy with IBrokers.
Here is some R syntax I wrote to interact with IBrokers.
# /a/ks/tws/spy/getcsv1m.r
# I use this script to copy price data out of IB-API into a CSV file.
# Demo1:
# R -f getcsv1m.r SPY USD $mytsu ../spycsv/spy_${myts}.csv
# Demo2:
# R -f getcsv1m.r SPY USD 20140727 22:35:40 ../spycsv/spy_20140727_22_35_40.csv
# Note:
# On ubuntu 14, I installed R with this shell command:
# apt-get install r-base
args = commandArgs()
print(args)
print(args[4])
print(args[5])
print(args[6])
print(args[7])
print(args[8])
mysymbol = args[4]
mycurrency = args[5]
myday = args[6]
myhr = args[7]
myfile = args[8]
my_endDateTime = sprintf("%s %s GMT", myday, myhr)
print(my_endDateTime)
# Now I make use of the IBrokers package.
# Syntax to install it:
# install.packages("IBrokers", lib="rpackages", repos="http://cran.us.r-project.org")
# Once I install it, I see it in a folder named rpackages/
# Next, tell this script where IBrokers resides:
.libPaths("rpackages")
# Now I can use IBrokers R Package:
library(IBrokers)
tws <- twsConnect()
reqCurrentTime(tws)
mytkr = twsContract(symbol=mysymbol,
currency=mycurrency,
exch='SMART',
sectype='STK',
primary='',
expiry='',
strike='0.0',
right='',
local='',
multiplier='',
combo_legs_desc='',
comboleg='',
include_expired='0',
conId=0)
reqHistoricalData(tws,mytkr,
endDateTime = sprintf("%s %s GMT", myday, myhr),
barSize = '1 min',
duration = '1 D',
useRTH = '0',
whatToShow = 'MIDPOINT',
timeFormat = '1',
file = myfile
)
twsDisconnect(tws)
Another R script:
# /a/ks/spy25/actonit.r
# I use this script to act on predictions written to this file:
# /a/ks/spy25/data/prediction.csv
# The tail end of the csv looks like this:
# 1414625400 197.835 0.594 0.586
# I want to be long or short by this amount:
possize = 3
arow = read.csv('data/prediction.csv', sep=' ', header=FALSE)
ptime = as.integer(arow[1][1])
print(ptime)
etime = as.POSIXct(ptime, origin="1970-01-01")
print(etime)
timediff_minutes = as.integer(difftime(Sys.time(), etime, units = "mins"))
myprediction = arow[4]
if (myprediction > 0.5 & timediff_minutes < 6) {
print('buy')
}
if (myprediction < 0.5 & timediff_minutes < 6) {
print('sell')
}
# Now I make use of the IBrokers package.
# Syntax to install it:
# install.packages("IBrokers", lib="rpackages", repos="http://cran.us.r-project.org")
# Once I install it, I see it in a folder named rpackages/
# Next, tell this script where IBrokers resides:
.libPaths("rpackages")
# Now I can use IBrokers R Package:
library(IBrokers)
myport = 7476
myclientId = 2
tws2 = twsConnect(clientId=myclientId, port=myport)
Sys.sleep(2)
# Order if position small:
myacct = reqAccountUpdates(tws2)
myposition = myacct[[2]][[1]]$portfolioValue$position
# myposition = 1
print(myposition)
twsDisconnect(tws2)
Sys.sleep(10)
tws2 = twsConnect(clientId=myclientId, port=myport)
mytkr = twsFuture("ES","GLOBEX","201412")
Sys.sleep(2)
myorderid = as.integer(reqIds(tws2))
print(myorderid)
Sys.sleep(2)
myorderid = as.integer(difftime(Sys.time(), "2014-10-30", units = "secs"))
if (myposition == -possize & myprediction > 0.5 & timediff_minutes < 6) {
print('Attempting BUY')
IBrokers:::.placeOrder(tws2, mytkr, twsOrder(myorderid,"BUY", 2*possize, "MKT"))
}
if (myposition == possize & myprediction < 0.5 & timediff_minutes < 6) {
print('Attempting SELL')
IBrokers:::.placeOrder(tws2, mytkr, twsOrder(myorderid,"SELL", 2*possize, "MKT"))
}
Sys.sleep(2)
twsDisconnect(tws2)
Thanks Dan!
I just got back home and am ready to dive in the world of IBPy, probably a dumb question, what's R?
R is an interpreted language sharing some behavior we see in Python, Ruby, Perl, bash, Javascript, and Matlab.
Some of the behavior I see in numpy and pandas appears similar to R behavior.
Perhaps most finance-quants know R very well and tend to use R more than Python.
http://www.r-project.org/
https://www.google.com/search?q=R-sig-finance
R is very easy to learn.
Dan
Yeah, IBPy is the way to go if you're using Python. I you want to go the C++ way it gets more complicated.
As it's event driven, you probably want a infinite loop running in a separate thread to wait for events.
Thanks Dan and Morten,
I'm definitely more comfortable with Python at this point. But maybe later can explore R.
None of the python api are good for real development, just for testing and playing around. I have been working with the Java API for a long time always looked for Python alternative, they are a bit limited.
Have used the IB C++ POSIX API before in my semi-highfrequency ATS developed in C. It's fairly convenient to work with.
If you build your own HTTP REST gateway for TWS or IBgateway you can use it from Quantopian for live trading or any platform that can perform a HTTP GET. Just fire way a simple HTTP GET to put an order into IB.
Submitting a market buy order for SPY would be:
http://myserver.foobar.com/ibrest/spy/mkt/buy
Submitting a buy limit order for SPY would be:
http://myserver.foobar.com/ibrest/spy/lmt/buy/price=123.45
Submitting a sell stop loss order would be:
http://myserver.foobar.com/ibrest/spy/stp/sell/price=123.45
I leave the security issues to solved by the implementor. ;-)
If you build your own HTTP REST gateway for TWS or IBgateway you can use it from Quantopian for live trading or any platform that can perform a HTTP GET.
For security reasons, Quantopian does not currently support arbitrary HTTP requests from within algorithms. Our Fetcher feature can be used in initialize() function to fetch data into Quantopian. Fetcher cannot be used from handle_data() or scheduled functions.
We are looking into way to allow more external access from within Quantopian, but we aren't yet at the point where we can share details, and we don't have an ETA. Having said that, while it's possible that new features we add to the platform might allow the use of an external broker as described above, they would not be designed with that use case in mind.
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.
Sorry to bring this thread back from the dead but I wasn't able to find the answer after a couple google searches.
Given that Interactive Brokers doesn't have an official Python API, how does Quantopian interface with IB to send orders, track account stats, etc...?
I'm doubtful that Q uses IBpy or swig, etc.
We launch a separate standalone IB Gateway instance for every live algorithm trading through IB.
We wrote our own, proprietary API glue layer between the IB Gateway and our application.
We manipulate the Gateway (logging the user in, detecting when a CAPTCHA code is requested, detecting the state of the Gateway, etc.) by taking screen captures of the IB Gateway windows and performing optical character recognition combined with fuzzy string matching to determine state, and using xdotool to find Gateway windows and send activation requests, keystrokes and mouse clicks to them. It's not pretty, but it works.
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.
Oh wow, I guess that explains why it is some effort to support iPhone and cryptocard 2-factor auth devices.
wow, that's a straight-forward integration
IbPy is great, and it does offer a wide coverage of most common features. To my understanding the wrapper is automatically generated from IB API, interaction with TWS is conceptually identical, so is syntax.
If you are looking for automating IB login you can try https://github.com/ib-controller/ib-controller
wow, that's a straight-forward integration
Indeed.
If you are looking for automating IB login you can try https://github.com/ib-controller/ib-controller
IB Controller may indeed be useful and effective for people looking to build out their own automated trading rigs connected to IB. As for why Quantopian didn't use it in our integration, we had a number of concerns, including:
At the time we started building our integration, IB Controller had been unmodified for over two years. We did not want to rely on a potentially unmaintained third-party package for a critical piece of our infrastructure.
IB Controller doesn't support two-factor authentication. We are extremely serious about security, so we did not want to have to require our users to disable 2fa to use IB with Quantopian.
We were concerned that IB Controller's method of integrating with IB Gateway might be inconsistent with IB's license agreement. We were reluctant to risk crossing that line, since we take license agreements seriously for both ethical and pragmatic reasons.
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.