我已经多次try 编写IB API代码,这些代码都在生成-1 504 Not Connected error
.即使代码直接和准确地来自IBKR学院的培训视频(我已经粘贴在下面).我一遍又一遍地判断了全局设置Enable ActiveX & Socket
,Socket Port#是7497,客户端ID与API代码匹配,选中了Allow Connections from Localhost,在Trusted IP中输入‘127.0.0.1’和Localhost:5000
TWS中的Data Connections表显示侦听7497 Peer—to—Peer Port 127.0.1.60104 Client ID 1的API连接为Accepted;这表明API已连接.然而,当我 Select Run时,什么都没有发生—我只是在VS Code Python终端中得到了文件链接的打印,当我执行Run Python Rugger时—我收到以下消息:
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()