2

我想请求合同详细信息,它在我第一次运行代码时工作,但是当我再次按运行时,它不会返回任何内容。如果我退出 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 完成”。

4

1 回答 1

3

app.run()启动一个线程从套接字读取。您的程序永远不会停止运行,因此始终连接到 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()
于 2019-07-06T20:57:57.083 回答