I want to connect to IB with python, here is my code:
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message
def error_handler(msg):
print "Server Error: %s" % msg
def reply_handler(msg):
print "Server Response: %s, %s" % (msg.typeName, msg)
if __name__ == "__main__":
tws_conn = Connection.create(port=7496, clientId=100)
tws_conn.connect()
tws_conn.register(error_handler, 'Error')
tws_conn.registerAll(reply_handler)
Whenever I use this code I receive this error which indicates that I can't connect to server:
Server Error: <error id=-1, errorCode=504, errorMsg=Not connected>
Server Response: error, <error id=-1, errorCode=504, errorMsg=Not connected>
Why I can't connect to IB?
Three things:
Hey so what you need to do is a couple of things. First off, you need Python 3.5 or above. So your print statements should use (). Second, you need to specify an IP address which is set to your local machine. Third, enjoy. I used this and got:
Server Version: 76
TWS Time at connection:20170613 21:10:55 MST
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message
def error_handler(msg):
print("Server Error: %s" % msg)
def reply_handler(msg):
print("Server Response: %s, %s" % (msg.typeName, msg))
if __name__ == "__main__":
tws_conn = Connection.create("127.0.0.1", port=7496, clientId=100)
tws_conn.connect()
tws_conn.register(error_handler, 'Error')
tws_conn.registerAll(reply_handler)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.