繁体   English   中英

无法使用python连接到Interactive Brokers

[英]Can't connect to Interactive Brokers with python

我想用python连接到IB,这是我的代码:

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)

每当我使用此代码时,我收到此错误,表示我无法连接到服务器:

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

为什么我无法连接到IB?

三件事:

  1. 确保TWS java应用程序正在运行且您已登录。
  2. 在TWS中,转到全局配置> API,并确保选中“启用活动和套接字客户端”。
  3. 在Global Configuration> API中,确保添加“127.0.0.1”作为可信IP地址(这假设您的py代码在运行TWS java应用程序的同一台机器上运行。

嘿所以你需要做的是几件事。 首先,您需要Python 3.5或更高版本。 所以你的print语句应该使用()。 其次,您需要指定一个设置为本地计算机的IP地址。 第三,享受。 我用过这个并得到了:

服务器版本:76

交流时间: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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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