Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从交互式代理API获取合同详细信息?_Python_Python 3.x_Interactive Brokers_Ib Api - Fatal编程技术网

Python 如何从交互式代理API获取合同详细信息?

Python 如何从交互式代理API获取合同详细信息?,python,python-3.x,interactive-brokers,ib-api,Python,Python 3.x,Interactive Brokers,Ib Api,以下是我尝试使用以下代码获取合同详细信息: from ibapi.client import EClient from ibapi.wrapper import EWrapper class MyWrapper(EWrapper): def contractDetails(self, reqId, contractDetails): super().contractDetails(reqId, contractDetails) print("Cont

以下是我尝试使用以下代码获取合同详细信息:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper

class MyWrapper(EWrapper):

    def contractDetails(self, reqId, contractDetails):
        super().contractDetails(reqId, contractDetails)

        print("ContractDetails. ReqId:", reqId,
              contractDetails.summary.symbol,
              contractDetails.summary.secType,
              "ConId:", contractDetails.summary.conId,
              "@", contractDetails.summary.exchange)

    def contractDetailsEnd(self, reqId):
        super().contractDetailsEnd(reqId)
        print("ContractDetailsEnd. ", reqId, "\n")


wrapper = MyWrapper()
app = EClient(wrapper)
app.connect("127.0.0.1", 7497, clientId=0)
print("serverVersion:%s connectionTime:%s" % (app.serverVersion(), app.twsConnectionTime()))

from ibapi.contract import Contract
contract = Contract()
contract.symbol = "XAUUSD"
contract.secType = "CMDTY"
contract.exchange = "SMART"
contract.currency = "USD"

app.reqContractDetails(4444, contract)
app.run()
返回的输出为:

serverVersion:148 connectionTime:b'20190117 17:11:38 AEST'

An exception has occurred, use %tb to see the full traceback.

SystemExit


C:\Users\Greg\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py:2969: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
如何从InteractiveBrokersAPI获取合同详细信息?我试着使用
%tb
,但我认为我没有把它放在正确的行上

from ibapi.client import EClient
from ibapi.wrapper import EWrapper


class MyWrapper(EWrapper):

    def nextValidId(self, orderId:int):
        print("setting nextValidOrderId: %d", orderId)
        self.nextValidOrderId = orderId
        # start program here or use threading
        app.reqContractDetails(4444, contract)

    def contractDetails(self, reqId, contractDetails):
        print(reqId, contractDetails.contract)# my version doesnt use summary

    def contractDetailsEnd(self, reqId):
        print("ContractDetailsEnd. ", reqId)
        # this is the logical end of your program
        app.disconnect() # delete if threading and you want to stay connected

    def error(self, reqId, errorCode, errorString):
        print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)


wrapper = MyWrapper()
app = EClient(wrapper)
app.connect("127.0.0.1", 7497, clientId=123)
print("serverVersion:%s connectionTime:%s" % (app.serverVersion(), app.twsConnectionTime()))

from ibapi.contract import Contract
contract = Contract()
contract.symbol = "XAUUSD"
contract.secType = "CMDTY"
contract.exchange = "SMART"
contract.currency = "USD"

app.run() # delete this line if threading

# def runMe():
#     app.run()

# import threading
# thread = threading.Thread(target = runMe)
# thread.start()

# input('enter to disconnect')
# app.disconnect()
在启动消息读取器之前,您正在请求数据。也许你在开始之前就得到了数据

IB建议在收到nextValidId后启动该程序,这样您就知道一切都正常运行。由于pythonapi阻塞在消息读取循环中,因此需要实现线程或构造程序以异步运行

我已经展示了如何做到这一点,这样它就可以在没有用户输入的情况下运行,并且是事件驱动的,或者是异步的。这意味着程序会等待,直到它应该做某件事,然后再去做

我已经包含了线程选项,只需更改注释即可


ContractDetails.summary已更改为合同。我不确定它是否是python中的摘要,不知道从何而来。

使用python 3中的ib_insync包,如果您想获得所有存储在df中的合同列表的详细信息,还可以执行以下操作:

from ib_insync import *
import pandas as pd


def add_contract_details(ib_client, ib_contract, df):
    list_of_contract_details = ib_client.reqContractDetails(contract=ib_contract)
    if list_of_contract_details:
        print(
            f"Found {len(list_of_contract_details)} contract{'s' if len(list_of_contract_details) > 1 else ''} for {ib_contract.symbol}: "
        )
        for contract_details in list_of_contract_details:
            data = {}
            for k, v in contract_details.contract.__dict__.items():
                data[k] = v
            for k, v in contract_details.__dict__.items():
                if k != "contract":
                    data[k] = v
            df = pd.DataFrame([data]) if df is None else df.append(pd.DataFrame([data]))
    else:
        print(f"No details found for contract {ib_contract.symbol}.")
    return df



ib = IB()
ib.connect(host="127.0.0.1", port=7497, clientId=1)
btc_fut_cont_contract = ContFuture("BRR", "CMECRYPTO")
ib.qualifyContracts(btc_fut_cont_contract)
fx_contract_usdjpy = Forex('USDJPY')
ib.qualifyContracts(fx_contract_usdjpy)

df_contract_details = None
for c in [btc_fut_cont_contract, fx_contract_usdjpy]:
    df_contract_details = add_contract_details(ib, c, df_contract_details)
print(df_contract_details)

莫名其妙;在创建
MyWrapper
之前,您是如何在
MyWrapper
内部获得该应用程序的实例的?@stucash我不是python程序员,但我猜该应用程序将是一个全局变量。我还编写了python示例,其中应用程序类继承了EClient和EWrapper,但这不是我用java编写所有内容的方式。@stucash看这里,谢谢回来;是的,您在评论中的回答是IB API连接方式的典型示例;如果你仔细阅读,你会发现
应用程序
需要初始化,就像你在其他示例中所做的那样;而
MyWrapper
app
的父类之一。不幸的是,在最好的情况下,这里的示例是创建循环依赖关系。它工作得非常完美,并且在其他语言中没有多重继承(通常没有全局变量,并且使用大量的中间逻辑)的情况下,它正是这样做的。我个人认为将包装器和客户机分开比较简单,并且认为多继承python示例是错误的。我认为你们所谓的循环逻辑实际上是异步编程。当你要求提供数据时,你需要指定将数据发送到哪里,在交易中,你还需要根据数据采取行动。