gpt4 book ai didi

python - IbPy : How to extract API response into a variable

转载 作者:太空狗 更新时间:2023-10-29 20:59:15 26 4
gpt4 key购买 nike

我正在研究 IbPy 是否可以成为我连接到 Interactive Brokers 交易 API 的好方法。作为测试,我现在正在尝试收集一些股票价格快照,看看我是否能让 IbPy 为我工作。我正在使用 Brokertron 网关连接 IB。

我从 IB API 得到了请求的股票价格(来 self 发现的一些带有错误处理的示例代码,见下文),所以从技术上讲它适用于 IB API,但我无法弄清楚如何将特定字段(下图field=4,price=175.95)提取到变量中供以后使用。

关于如何将字段 4 内容放入变量的任何想法?谢谢!

Python 示例脚本:

import ib
from ib.ext.Contract import Contract
from ib.opt import ibConnection, message
from time import sleep

class Downloader(object):
def __init__(self,debug=False):
self.tws = ibConnection('localhost', 4001, 0)

if debug:
self.tws.registerAll(self.debugHandler)

self.tws.connect()
self._reqId = 1 # current request id

def debugHandler(self,msg):
print '[debug]', msg

def requestData(self,contract):
self.tws.reqMktData(self._reqId,c,'',1)
self._reqId+=1
return "???"

if __name__=='__main__':
dl = Downloader(debug=True)
c = Contract()
c.m_symbol = 'SPY'
c.m_secType = 'STK'
c.m_exchange = 'SMART'
c.m_currency = 'USD'
laststockpricefield4 = dl.requestData(c)
print laststockpricefield4
sleep(3)
print 'Done.'

命令行输出:

01-Nov-12 22:30:43 DEBUG Server Version: 65
01-Nov-12 22:30:43 DEBUG TWS Time at connection: 20121101 22:30:43 GMT
???
[debug] ManagedAccounts accountsList=DU15144>
[debug] NextValidId orderId=1>
[debug] TickString tickerId=1, tickType=45, value=1351808899>
[debug] TickPrice tickerId=1, field=4, price=175.95, canAutoExecute=0>
[debug] TickSize tickerId=1, field=5, size=1>
[debug] TickGeneric tickerId=1, tickType=49, value=0.0>
[debug] TickPrice tickerId=1, field=1, price=176.03, canAutoExecute=1>
[debug] TickSize tickerId=1, field=0, size=378>
[debug] TickPrice tickerId=1, field=2, price=176.05, canAutoExecute=1>
[debug] TickSize tickerId=1, field=3, size=344

最佳答案

这有效!

import re
import ib
from ib.ext.Contract import Contract
from ib.opt import ibConnection, message
from time import sleep

class Downloader(object):
field4price = ''

def __init__(self):
self.tws = ibConnection('localhost', 4001, 0)
self.tws.register(self.tickPriceHandler, 'TickPrice')
self.tws.connect()
self._reqId = 1 # current request id

def tickPriceHandler(self,msg):
if msg.field == 4:
self.field4price = msg.price
#print '[debug]', msg

def requestData(self,contract):
self.tws.reqMktData(self._reqId, contract, '', 1)
self._reqId+=1

if __name__=='__main__':
dl = Downloader()
c = Contract()
c.m_symbol = 'SPY'
c.m_secType = 'STK'
c.m_exchange = 'SMART'
c.m_currency = 'USD'
dl.requestData(c)
sleep(3)
print 'Price - field 4: ', dl.field4price

关于python - IbPy : How to extract API response into a variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13204686/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com