IB API TWS中出现504未连接错误,尽管API连接显示“已接受”
我尝试了很多次写IB API的代码,但每次都出现-1 504 Not Connected error
的错误。即使是直接从IBKR学院培训视频中复制的代码(我已经粘贴在下面)。我检查了很多遍,确保全局设置中的Enable ActiveX & Socket
选项是勾选的,Socket端口号是7497,客户端ID在API代码和TWS中是匹配的,允许来自本地主机的连接也被选中了,并且我把'127.0.0.1'和localhost:5000输入到了可信IP中。
TWS中的数据连接表显示API连接在7497端口上监听,Peer-to-Peer端口是127.0.0.1.60104,客户端ID是1,状态是已接受;这表明API是连接上的……然而当我选择运行时,什么也没有发生——我只是在VS Code的Python终端中看到文件链接的打印信息,当我执行运行Python调试器时,我收到了以下信息:
PS C:\TWS API\source\pythonclient\ibapi> & 'c:\Users\JV\AppData\Local\Programs\Python\Python312\python.exe' 'c:\Users\JV\.vscode\extensions\ms-python.debugpy-2024.2.0-win32-x64\bundled\libs\debugpy\adapter/../..\debugpy\launcher' '60548' '--' 'c:\TWS API\source\pythonclient\tests\TestApp.py'
ERROR -1 504 Not connected
PS C:\TWS API\source\pythonclient\ibapi>
我在这个和其他论坛上搜索了很多答案。有没有人能帮帮这个新手?我感觉自己被困住了,连IB API的第一步都迈不出去。谢谢。
from ibapi.client import *
from ibapi.wrapper import *
import time
class TestApp(EClient, EWrapper):
def __init__(self):
EClient.__init__(self, self)
def contractDetails(self, reqId, contractDetails):
print(f"contract details: {contractDetails}")
def contractDetailsEnd(self, reqId):
print("End of contractDetails")
self.disconnect()
def main():
app = TestApp()
app.connect("127.0.0.1", 7497, 1)
mycontract = Contract()
mycontract.symbol = "AAPL"
mycontract.secType = "STK"
mycontract.exchange = "SMART"
mycontract.currency = "USD"
mycontract.primaryExchange = "ISLAND"
time.sleep(3)
app.reqContractDetails(1, mycontract)
app.run
if __name__ == "__main__":
main()
1 个回答
1
简单来说,app.run
是一个方法调用,所以应该写成 app.run()
。
你的代码还有其他常见的 ib-api 问题,你可以通过点击我的名字来搜索相关的问题。大多数例子和你的情况类似,但都是不正确的。