Cannot connect to Interactive Brokers using python

I want to connect to IB using 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 get this error, which indicates that I can not connect to the server:

Server Error: <error id=-1, errorCode=504, errorMsg=Not connected>
Server Response: error, <error id=-1, errorCode=504, errorMsg=Not connected>

Why can't I connect to IB?

+4
source share
2 answers

Three things:

  • Make sure the TWS java application is running and you are logged in.
  • In TWS, go to Global Configuration> API and make sure the "Enable Active and Socket Clients" checkbox is selected.
  • > API , "127.0.0.1" IP- ( , py , Java TWS.
+4

, , . -, Python 3.5 . (). -, IP-, . -, . :

: 76

TWS : 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)
0

Source: https://habr.com/ru/post/1531412/


All Articles