2010-01-05 67 views
9

有誰知道如何通過彭博社的新數據API(COM v3)與Python獲取異步數據?我在wilmott.com上發現了下面的代碼,它工作得很好,但是它適用於舊的API版本。通過彭博的新數據API(COM v3)與Python的異步數據?

有誰知道新版本的相應代碼?

from win32com.client import DispatchWithEvents 
from pythoncom import PumpWaitingMessages, Empty, Missing 
from time import time 

class BBCommEvent: 
    def OnData(self, Security, cookie, Fields, Data, Status): 
     print 'OnData: ' + `Data` 

    def OnStatus(self, Status, SubStatus, StatusDescription): 
     print 'OnStatus' 

class TestAsync: 
    def __init__(self): 
     clsid = '{F2303261-4969-11D1-B305-00805F815CBF}' 
     progid = 'Bloomberg.Data.1' 

     print 'connecting to BBComm'   
     blp = DispatchWithEvents(clsid, BBCommEvent) 
     blp.AutoRelease = False 
     blp.Subscribe('EUR Curncy', 1, 'LAST_PRICE', Results = Empty) 
     blp.Flush() 

     end_time = time() + 5 

     while 1: 
      PumpWaitingMessages() 
      if end_time < time(): 
       print 'timed out' 
       break 

if __name__ == "__main__": 
    ta = TestAsync() 

回答

19

我終於想通了。我做了一些combrowse.py的偵探工作,並將其與BBG API下載中的JAVA,C,C++和.NET示例進行了比較。有趣的是,布隆伯格服務檯的人員對這些事情幾乎一無所知,或者我只是在與錯誤的人交談。

這是我的代碼。

asynchronousHandler.py:

import win32com.client 
from pythoncom import PumpWaitingMessages 
from time import time, strftime 
import constants 

class EventHandler: 
    def OnProcessEvent(self, result): 
     event = win32com.client.gencache.EnsureDispatch(result) 
     if event.EventType == constants.SUBSCRIPTION_DATA: 
      self.getData(event) 
     elif event.EventType == constants.SUBSCRIPTION_STATUS: 
      self.getStatus(event) 
     else: 
      self.getMisc(event) 
    def getData(self, event): 
     iterator = event.CreateMessageIterator() 
     while iterator.Next(): 
      message = iterator.Message 
      dataString = '' 
      for fieldIndex, field in enumerate(constants.fields):   
       if message.AsElement.HasElement(field): 
        element = message.GetElement(field) 
        if element.IsNull: 
         theValue = '' 
        else: 
         theValue = ', Value: ' + str(element.Value) 
        dataString = dataString + ', (Type: ' + element.Name + theValue + ')' 
      print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + dataString 
    def getMisc(self, event): 
     iterator = event.CreateMessageIterator() 
     while iterator.Next(): 
      message = iterator.Message 
      print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString 
    def getStatus(self, event): 
     iterator = event.CreateMessageIterator() 
     while iterator.Next(): 
      message = iterator.Message 
      if message.AsElement.HasElement('reason'): 
       element = message.AsElement.GetElement('reason') 
       print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + ', Category: ' + element.GetElement('category').Value + ', Description: ' + element.GetElement('description').Value 
      if message.AsElement.HasElement('exceptions'): 
       element = message.AsElement.GetElement('exceptions') 
       exceptionString = '' 
       for n in range(element.NumValues): 
        exceptionInfo = element.GetValue(n) 
        fieldId = exceptionInfo.GetElement('fieldId') 
        reason = exceptionInfo.GetElement('reason') 
        exceptionString = exceptionString + ', (Field: ' + fieldId.Value + ', Category: ' + reason.GetElement('category').Value + ', Description: ' + reason.GetElement('description').Value + ') ' 
       print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + exceptionString 

class bloombergSource: 
    def __init__(self): 
     session = win32com.client.DispatchWithEvents('blpapicom.Session' , EventHandler) 
     session.Start() 
     started = session.OpenService('//blp/mktdata') 
     subscriptions = session.CreateSubscriptionList() 
     for tickerIndex, ticker in enumerate(constants.tickers): 
      if len(constants.interval) > 0: 
       subscriptions.AddEx(ticker, constants.fields, constants.interval, session.CreateCorrelationId(tickerIndex)) 
      else: 
       subscriptions.Add(ticker, constants.fields, session.CreateCorrelationId(tickerIndex)) 
     session.Subscribe(subscriptions) 
     endTime = time() + 2 
     while True: 
      PumpWaitingMessages() 
      if endTime < time():     
       break    

if __name__ == "__main__": 
    aBloombergSource = bloombergSource() 

constants.py:

ADMIN = 1 
AUTHORIZATION_STATUS = 11 
BLPSERVICE_STATUS = 9 
PARTIAL_RESPONSE = 6 
PUBLISHING_DATA = 13 
REQUEST_STATUS = 4 
RESOLUTION_STATUS = 12 
RESPONSE = 5 
SESSION_STATUS = 2 
SUBSCRIPTION_DATA = 8 
SUBSCRIPTION_STATUS = 3 
TIMEOUT = 10 
TOKEN_STATUS = 15 
TOPIC_STATUS = 14 
UNKNOWN = -1 
fields = ['BID'] 
tickers = ['AUD Curncy'] 
interval = '' #'interval=5.0' 

歷史數據我用這個簡單的腳本:

import win32com.client 

session = win32com.client.Dispatch('blpapicom.Session') 
session.QueueEvents = True 
session.Start() 
started = session.OpenService('//blp/refdata') 
dataService = session.GetService('//blp/refdata') 
request = dataService.CreateRequest('HistoricalDataRequest') 
request.GetElement('securities').AppendValue('5 HK Equity') 
request.GetElement('fields').AppendValue('PX_LAST') 
request.Set('periodicitySelection', 'DAILY') 
request.Set('startDate', '20090119') 
request.Set('endDate', '20090130') 
cid = session.SendRequest(request) 
ADMIN = 1 
AUTHORIZATION_STATUS = 11 
BLPSERVICE_STATUS = 9 
PARTIAL_RESPONSE = 6 
PUBLISHING_DATA = 13 
REQUEST_STATUS = 4 
RESOLUTION_STATUS = 12 
RESPONSE = 5 
SESSION_STATUS = 2 
SUBSCRIPTION_DATA = 8 
SUBSCRIPTION_STATUS = 3 
TIMEOUT = 10 
TOKEN_STATUS = 15 
TOPIC_STATUS = 14 
UNKNOWN = -1 
stayHere = True 
while stayHere: 
    event = session.NextEvent(); 
    if event.EventType == PARTIAL_RESPONSE or event.EventType == RESPONSE: 
     iterator = event.CreateMessageIterator() 
     iterator.Next() 
     message = iterator.Message 
     securityData = message.GetElement('securityData') 
     securityName = securityData.GetElement('security') 
     fieldData = securityData.GetElement('fieldData') 
     returnList = [[0 for col in range(fieldData.GetValue(row).NumValues+1)] for row in range(fieldData.NumValues)] 
     for row in range(fieldData.NumValues): 
      rowField = fieldData.GetValue(row) 
      for col in range(rowField.NumValues+1): 
       colField = rowField.GetElement(col) 
       returnList[row][col] = colField.Value 
     stayHere = False 
     break 
element = None 
iterator = None 
message = None 
event = None 
session = None 
print returnList 
+0

太棒了!我一直在到處找這個。 現在我所需要的只是爲了處理歷史數據請求!如果你有第二個,請打電話給bberg終端。 – 2010-03-01 20:50:55

+0

我在上面添加了歷史數據腳本。我沒有看過這些片刻,我敢打賭他們可以簡化一下。 – c00kiemonster 2010-03-02 08:05:24

+0

滑板車評論:「截至2012年1月24日,常數發生了變化,'RESPONSE = 6'PARTIAL_RESPONSE = 7',我通過反覆試驗確定了這一點。 – 2012-01-25 00:47:01

0

對於它的工作,你需要安裝彭博桌面v3 API SDK,我這樣做,重新啓動我的機器,似乎工作。沒有重新啓動,它只是墜毀。

如果您使用COM資源管理器,你會看到現在的彭博元素存在