Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 939
Adel Avatar asked Mar 12 '14 18:03

Adel


1 Answers

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.
like image 88
Donn Lee Avatar answered Oct 04 '22 23:10

Donn Lee