无法用python连接到Interactive Brokers
我想用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呢?
2 个回答
1
嘿,你需要做几件事。首先,你得安装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)
9
三件事:
- 确保你的TWS Java应用程序正在运行,并且你已经登录。
- 在TWS中,进入全局配置 > API,确保勾选了“启用活动和套接字客户端”。
- 在全局配置 > API中,确保将“127.0.0.1”添加为受信任的IP地址(这假设你的Python代码是在与TWS Java应用程序相同的机器上运行的)。