简体   繁体   中英

Can't connect to Interactive Brokers with python

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:

  1. Make sure the TWS java app is running and you are logged in.
  2. In TWS, go to Global Configuration > API, and make sure "Enable Active and Socket Clients" is checked.
  3. In Global Configuration > API, make sure you add "127.0.0.1" as a Trusted IP Address (this assumes your py code is running on the same machine that is running the TWS java app.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM