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?

sashkello
  • 17,306
  • 24
  • 81
  • 109
Adel
  • 3,542
  • 8
  • 30
  • 31

2 Answers2

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.
Donn Lee
  • 2,962
  • 1
  • 24
  • 16
  • 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 08 '15 at 05:20
  • Worked for me. Thanks!! – Zanam Dec 31 '15 at 22:55
  • its *View -> Data Connections* in TWS in the latest build (10.16.11) – Ammad Khalid Jul 08 '22 at 08:47
0

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)
Jeremy
  • 725
  • 6
  • 11