我想请求合同详细信息,并且在我第一次运行代码时它有效,但是当我再次按下run时,它将不会返回任何内容。如果我退出TWS和pycharm并再次尝试我是python的新手,并且不了解它的整体工作原理,它将起作用。
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
from ibapi.contract import *
from ContractSamples import ContractSamples
class TestApp(EClient, EWrapper):
def __init__(self):
EClient.__init__(self, self)
def error(self, reqId:TickerId, errorCode:int, errorString:str):
print("Error: ", reqId, "", errorCode, "", errorString)
def contractDetails(self, reqId:int, contractDetails:ContractDetails):
print("contractDetail: ", reqId, " ", contractDetails)
def main():
app = TestApp()
app.connect("127.0.0.1", 7496, 0)
contract = Contract()
contract.symbol = "AAPL"
contract.secType = "STK"
contract.exchange = "SMART"
contract.currency = "USD"
contract.primaryExchange = "NASDAQ"
app.reqContractDetails(10, contract)
app.run()
if __name__ == "__main__":
main()
没有错误消息,只是没有结果:“进程已完成,退出代码为0”。
答案 0 :(得分:0)
app.run()
启动线程以从套接字读取。您的程序永远不会停止运行,因此始终连接到TWS。尝试单击TWS中的数据菜单按钮。它显示您的所有连接。您将看到客户端0保持连接状态。显然,关闭pyCharm会杀死该程序。
在程序准备就绪之前,您还需要合同细节。您应该等待nextValidId,然后发送请求。接收到数据后,您可以停止程序,这将释放clientId以便将来连接。这是我更改程序的方法。
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
from ibapi.contract import *
from ContractSamples import ContractSamples
class TestApp(EClient, EWrapper):
def __init__(self):
EClient.__init__(self, self)
def nextValidId(self, orderId:int):
print("id", orderId)
contract = Contract()
contract.symbol = "IBKR"
contract.secType = "STK"
contract.exchange = "SMART"
contract.currency = "USD"
contract.primaryExchange = "NASDAQ"
self.reqContractDetails(10, contract)
def error(self, reqId:TickerId, errorCode:int, errorString:str):
print("Error: ", reqId, "", errorCode, "", errorString)
def contractDetails(self, reqId:int, contractDetails:ContractDetails):
print("contractDetail: ", reqId, " ", contractDetails)
def contractDetailsEnd(self, reqId:int):
print("end, disconnecting")
self.disconnect()
def main():
app = TestApp()
app.connect("127.0.0.1", 7496, 0)
app.run()
if __name__ == "__main__":
main()