Bloomberg API: how do I associate request with response on IntradayBarRequest?
不幸的是,我在论坛上被引导相信(但没有100%的把握),彭博桌面API一次不允许超过一个IntradayBarreQuest或IntradayTickRequest,这与允许多个同时请求的HistoricalDataRequest或订阅不同。
因此,除非有人告诉我上述情况并非真的,否则这个问题可能毫无意义。
如果为真,那么处理下面问题的唯一方法就是只在处理完前一个请求之后才发送每个新请求。
我正在使用python bloomberg桌面API访问金融证券的订阅(实时更新)和历史每日数据。在这两种情况下,我可以同时发送多个请求,并且当响应出现时(不一定按照请求发送的顺序),我可以使用msg.getelement("securitydata").getelementasstring("security")(对于历史数据)或订阅数据)来确定响应与哪个安全性相关联,通过使用msg.correlationids()[0].value()查询预先设置的correlationid(在订阅请求时)。
但是,我不知道如何处理日间不响应请求(并且WAPI文档没有帮助)。它们似乎没有可设置的correlationid,也没有上面的"securitydata"字段。如果我在一天内发送多个请求,我如何才能找出响应的安全性?
这是我的代码(改编自api python示例)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | import blpapi # interface to bloomberg import time # will need this for time parsing from optparse import OptionParser import pdb # debugger, when necessary import csv # for csv reading import string # for string parsing from pymongo import MongoClient import inspect from datetime import datetime from bson.son import SON def parseCmdLine(): parser = OptionParser(description="Retrieve realtime data.") parser.add_option("-a", "--ip", dest="host", help="server name or IP (default: %default)", metavar="ipAddress", default="localhost") parser.add_option("-p", dest="port", type="int", help="server port (default: %default)", metavar="tcpPort", default=8194) parser.add_option("--me", dest="maxEvents", type="int", help="stop after this many events (default: %default)", metavar="maxEvents", default=100000000000) parser.add_option("--mongohost", dest="mongohost", default="192.168.1.30") parser.add_option("--mongoport", dest="mongoport", type="int", default=27017) (options, args) = parser.parse_args() return options def main(): options = parseCmdLine() # connect to MongoDB MONGO MONGO MONGO MONGO ---------------- print"Connecting to MongoDB" print options.mongohost print options.mongoport client = MongoClient(options.mongohost, options.mongoport) # connect to MongoDB db = client.bb # connect to the DB database bbsecs = db.bbsecs bbticks = db.bbticks # now get the securities list # Fill SessionOptions sessionOptions = blpapi.SessionOptions() sessionOptions.setServerHost(options.host) sessionOptions.setServerPort(options.port) print"connecting to Bloomberg" print"Connecting to %s:%d" % (options.host, options.port) # Create a Session session = blpapi.Session(sessionOptions) # Start a Session if not session.start(): print"Failed to start session." return # open the market data subscription service if not session.openService("//blp/mktbar"): print"Failed to open //blp/mktbar" return if not session.openService("//blp/refdata"): print"Failed to open //blp/refdata" return # now startup the subscription list # Now open the secs.dat file and read it, append each to subscription list maxtimes = bbticks.aggregate([{'$group': {'_id':'$ticker', 'maxtime':{'$max': '$time'}}}]) # get the last updates by ticker refDataService = session.getService("//blp/refdata") # start the ref for i in maxtimes["result"]: ticker = i["_id"] tstamp = i["maxtime"] request = refDataService.createRequest("IntradayBarRequest") request.set("security", ticker) request.set("eventType","TRADE") request.set("interval", 1) request.set("startDateTime", tstamp) request.set("endDateTime", datetime.now()) print"Sending Request:", ticker session.sendRequest(request) subscriptions = blpapi.SubscriptionList() secdic = dict() # a new dictionary for post in bbsecs.find(): print(post["ticker"]) # subscribe tick #subscriptions.add(str(post["ticker"]),"LAST_PRICE", [], blpapi.CorrelationId("TICK:" + str(post["ticker"]))) #subscribe 1 minute bars subscriptions.add("//blp/mktbar/ticker/"+str(post["ticker"]), "LAST_PRICE", "interval=1.0", blpapi.CorrelationId(str(post["ticker"]))) # setup the dictionary secdic[post["bbsecnum"]] = post["ticker"] if not session.openService("//blp/refdata"): print"Failed to open //blp/refdata" return # now subscribe session.subscribe(subscriptions) # HISTORICALHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH # Obtain previously opened service #refDataService = session.getService("//blp/refdata") # Create and fill the request for the historical data #request = refDataService.createRequest("HistoricalDataRequest") #for post in bbsecs.find(): # request.getElement("securities").appendValue(str(post["ticker"])) #request.getElement("fields").appendValue("LAST_PRICE") #request.set("periodicityAdjustment","ACTUAL") #request.set("periodicitySelection","DAILY") #request.set("startDate","20100101") #request.set("endDate","20121231") #request.set("maxDataPoints", 2000) #print"Sending Request:", request # Send the request #session.sendRequest(request) #hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh try: # Process received events eventCount = 0 while(True): # We provide timeout to give the chance to Ctrl+C handling: event = session.nextEvent(500) for msg in event: if event.eventType() == blpapi.Event.SUBSCRIPTION_STATUS: #print"%s - %s" % (msg.correlationIds()[0].value(), msg) print"subscription status" elif event.eventType() == blpapi.Event.SUBSCRIPTION_DATA: key = msg.correlationIds()[0].value() if msg.messageType() =="MarketBarStart": open = msg.getElementAsFloat("OPEN") high = msg.getElementAsFloat("HIGH") low = msg.getElementAsFloat("LOW") close = msg.getElementAsFloat("CLOSE") btstamp = msg.getElementAsDatetime("TIME") tstamp = datetime.now() print"bar", key, close, tstamp bbticks.insert({"type":"BAR","ticker": key,"value": close, \ "open": open,"high": high,"low": low,"close": close, \ "time": tstamp}) elif msg.messageType() =="MarketBarUpdate": close = msg.getElementAsFloat("CLOSE") #print"tick", close, #bbticks.insert({"type":"TICK","ticker": key,"value": close,"time": tstamp}) #if etype =="TRADE": # if msg.hasElement("LAST_TRADE"): # key = msg.correlationIds()[0].value(), # keytype = key[:(key.index(":"))] # key = key[(key.index(":") + 1):] # value = msg.getElementAsString("LAST_TRADE") # timestamp = msg.getElementAsDatetime("TRADE_UPDATE_STAMP_RT") # print key, value, # bbticks.insert({"ticker": key,"value": value,"timestamp": timestamp}) else: if msg.messageType() =="HistoricalDataResponse": securityData = msg.getElement("securityData") security = securityData.getElementAsString("security") fieldDataArray = securityData.getElement("fieldData") for j in range(0, fieldDataArray.numValues()): fieldData = fieldDataArray.getValueAsElement(j) field = fieldData.getElement(0) tstamp = field.getValueAsDatetime() tstamp = datetime(tstamp.year, tstamp.month, tstamp.day) field = fieldData.getElement(1) close = field.getValueAsFloat() #print"history", security, close, #bbticks.insert({"type":"DAILY","ticker": security,"value": close,"close": close, \ # "time": tstamp}) elif msg.messageType() =="IntradayBarResponse": print"IntradayBarResponse" data = msg.getElement("barData").getElement("barTickData") numvals = data.numValues() print numvals if numvals > 0: print data.getValueAsElement(1).getElement(1).getValueAsFloat() if event.eventType() == blpapi.Event.SUBSCRIPTION_DATA: eventCount += 1 if eventCount >= options.maxEvents: break finally: # Stop the session session.stop() if __name__ =="__main__": try: main() except KeyboardInterrupt: print"Ctrl+C pressed. Stopping..." |
我已经查看了EIDData,它是空的,即使我要求它返回。我关注的是货币,而不是股票,因此不需要兑换权利。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | > (Pdb) print eid._Element__dataHolder IntradayBarResponse = { > barData = { > eidData[] = { > } > barTickData[] = { > barTickData = { > time = 2013-08-02T18:36:00.000 > open = 4.233100 > high = 4.233600 > low = 4.233100 > close = 4.233400 > volume = 0 > numEvents = 119 > value = 0.000000 > } > barTickData = { > time = 2013-08-02T18:37:00.000 > open = 4.233400 > high = 4.233700 > low = 4.233100 > close = 4.233500 > volume = 0 > numEvents = 96 > value = 0.000000 > } > barTickData = { > time = 2013-08-02T18:38:00.000 > open = 4.233500 > high = 4.233600 > low = 4.233300 > close = 4.233500 > volume = 0 > numEvents = 135 > value = 0.000000 > } > barTickData = { > time = 2013-08-02T18:39:00.000 |
我仍在寻找一种将请求与响应关联起来的方法,而不必执行效率低下的请求….等待响应….请求等。不过,我不确定彭博是否提供此功能。这种限制似乎也存在于历史刻度数据中。
(P)I don't know the Python api but I do use the Java Api.(p)布尔奇1(P)作为一个被发现的人,你不能为多方面的担保提供便利,而且这种感觉并不影响到担保人(e.g.tickers)向你的愿望提供便利。(p)(P)The easiest solution is to use a correction id.When you submit a request to a session,you can provide your own correction id.The example below is in Java but I would think that the python api is similar:(p)字母名称(P)Then,if you use an asynchronous session,you receive asynchronous messages which have a link to the original correctionID:(p)字母名称
(P)Thomas,you should always use corresionid of a response to find which request it is associated with.IIRC,Reference data and historical data requests support multiple security,but market data and intraday bars may have only one security per request.(p)(P)That is why there is additional"securitydata"field in refdata and historical responses.关于市场数据和国内担保权的相互关系,尚不足以确定担保权的要求和范围。(p)(P)希望如此。(p)
(P)I don't believe you can subscruct to tick or bar data.这是一个原因…为了定价数据,你得到了对价值变化的反应。是否有数据证明这些价格的历史?For bar data,isn't that a history of prices with some detail removed by grouping by a period(IE.10 minutes,1 hour).So if you could subscribe to either,where should you receive each new response from Bloomberg?Essentially,you could create your own listener that does the grouping,and then sends out a response from the listener with a frequency of your own choosing.(p)(P)BTW:I use CLR to talk to the Net BLP object from Python.我的解决办法是掠夺任何对Pyton的血腥支持,无论什么"不能捐赠"。(p)