6

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?

0

2 Answers 2

9

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.
3
  • 1
    I was stuck on the same problem for a couple hours. Just to add to Donna's answer, make sure you use the same socket port and client ID as your TWS. You could also monitor API connections under Help -> Data Connections in TWS.
    – chogall
    Dec 8, 2015 at 5:20
  • Worked for me. Thanks!!
    – Zanam
    Dec 31, 2015 at 22:55
  • its View -> Data Connections in TWS in the latest build (10.16.11) Jul 8, 2022 at 8:47
1

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.