Can someone help me to figure out how to do basic request by using IB API Python socket? (I am using the latest IB API and it seems it support Python so should not need the Ibpy which people used to use)
My code like this can simply work and make it connect to TWS. The problem is : I have no idea how to "see" the message sending back from IB.
from ibapi import wrapper
from ibapi.client import EClient
from ibapi.contract import *
w = wrapper.EWrapper()
myTWS = EClient(w)
myTWS.connect(host='localhost', port=7496, clientId=100)
print("serverVersion:%s connectionTime:%s" % (myTWS.serverVersion(),
myTWS.twsConnectionTime()))
myTWS.startApi()
c = Contract()
c.m_symbol = "AAPL"
c.m_secType = "STK"
c.m_exchange = "ISLAND"
c.m_currency = "USD"
myTWS.reqRealTimeBars(999, c, 5, "MIDPOINT", True, [])
I know that it was something like Register() before with IBPy. I just don't know how to do it in this current IB original python API. Can someone help by giving me a simple example? Thanks in advance.
You have to subclass/override/implement the wrapper.EWrapper. That's where you're telling
EClient
to send the data received from TWS.I removed almost everything from the sample program and this runs.
Once you call
app.run()
the program starts an almost infinite loop reading messages so you'll need some other way to structure your program since the loop must be started.There is a new project which simplifies work with Python TWS Api.
It is called IB-insync and it allows both sync and async processing. It looks very great for newbies in TWS API. Link to Project Page
Example of requesting historical data using IB-insync:
I have looked for the way how to process sequence of requests outside of app object.
This is my little modification of Brian's code (thanks Brian for the introduction how to work with it), which gets two contract details, first it requests contractdetails for MSFT, then for IBM.
when app.done is set to True, the client disconnects in EClient.run() method. I did not figured out how to quit the EClient.run() method without disconnecting, so I changed exiting in the source code in the client.py EClient.run() method:
If someone knows better way without changing API source code, I'll be glad if you give me an advice.
Here is the code:
This is example how to process API messages using multithreading. The app.run() is started as separate thread and it is listening to TWS API responses. The main program then sends 5 requests for ContractDetails and then main program is 10 seconds waiting for responses. TWS API messages are stored within app instance and simple semaphore signals when the response is ready to be processed.
It is my first multithreading program, any comments are welcome.