在Python中为交互式代理API响应设置变量

2024-05-20 19:36:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些代码,其中我使用交互式经纪人API和Python请求期货合约的实时市场数据,在本例中是VIX合约。我收到一个数据流,通过修补的包装器打印出来。这是使用IB的实际pythonapi,而不是第三方库。在

我想做的是两个步骤:首先,为最后一个价格设置一个变量,即响应(13.0)中的ticktype4。其次,我想停止当前合同的数据流传输,并请求另一个合同的数据(例如,下一个到期日,20170816)。否则,如果我可以同时请求两组数据,并将它们各自设置为一个变量,那么停止流式传输也将是惊人的。这是我迄今为止从IB发出成功请求的代码。假设API已打开,并且您可以访问VIX期货市场数据(CFE交易所),则响应如下:

from ibapi.wrapper import EWrapper
from ibapi.client import EClient
from ibapi.utils import iswrapper
from ibapi.common import *
from ibapi.contract import *
from ibapi.ticktype import *
# Request IB Data in less than 50 lines of code
class BasicApp(EWrapper, EClient):
  def __init__(self):
    EClient.__init__(self,self)

  def error(self, reqId: TickerId, errorCode:int, errorString:str):
    print('Error:', reqId, " ", errorCode, " ", errorString)

  @iswrapper
  def tickPrice(self, reqId: TickerId, tickType: TickType, price: float, attrib: TickAttrib):
    super().tickPrice(reqId, tickType, price, attrib)
    print("Tick Price. Ticker Id:", reqId, "tickType:", tickType, "Price:", price, "CanAutoExecute:", attrib.canAutoExecute, "PastLimit", attrib.pastLimit)

  @iswrapper
  def tickSize(self, reqId: TickerId, tickType: TickType, size: int):
    super().tickSize(reqId, tickType, size)
    print("Tick Size. Ticker Id:", reqId, "tickType:", tickType, "Size:", size)

  @iswrapper
  def tickString(self, reqId: TickerId, tickType: TickType, value: str):
    super().tickString(reqId, tickType, value)
    print("Tick string. Ticker Id:", reqId, "Type:", tickType, "Value:", value)

  @iswrapper
  def tickGeneric(self, reqId: TickerId, tickType: TickType, value: float):
    super().tickGeneric(reqId, tickType, value)
    print("Tick Generic. Ticker Id:", reqId, "tickType:", tickType, "Value:", value)

def main():
  app = BasicApp()
  app.connect("127.0.0.1", 4001, 0)
  contract = Contract();
  contract.symbol = "VIX";
  contract.secType = "FUT";
  contract.exchange = "CFE";
  contract.currency = "USD";
  contract.lastTradeDateOrContractMonth = "20170719";
  app.reqMktData(1001, contract, "", False, False, [])
  app.run()

if __name__ == '__main__':
  main()

这是上面打印IB响应的包装:

^{pr2}$

Tags: 数据fromimportselfvaluedefibprint
1条回答
网友
1楼 · 发布于 2024-05-20 19:36:06

要停止当前合同的流数据,请调用

app.cancelMktData(tickerId); 

对于tickerId,使用与中相同的值app.reqmkt数据(在你的例子中是1001)。在

保持最后的价格应该不是问题。插入

^{pr2}$

按滴答价格法。在

您可以通过调用app.reqmkt数据用不同的tickerId。在这种情况下,lastprice可以存储在一个集合中(例如,使用tickerId作为键的字典)。在

相关问题 更多 >