2011-09-07 6 views
6

Sto cercando di ottenere un'istantanea dal prezzo live da Bloomberg. Net API 3 con C#.Come ottenere un'istantanea del prezzo live in bloomberg?

Posso vedere dagli esempi come ottenere i prezzi storici o iscriversi ai dati, ma non riesco a trovare la richiesta corretta per ottenere un'istantanea di ordine, ovvero Prezzo di offerta/Chiedi/Ultimo commercio e Quantità.

Per una zecca intraday vorrei fare qualcosa di simile:

Service refDataService = d_session.GetService("//blp/refdata"); 
// create intraday tick request 
Request request = refDataService.CreateRequest("IntradayTickRequest"); 
// set request parameters 
request.Set("includeConditionCodes", checkBoxIncludeConditionCode.Checked); 
request.Set("includeExchangeCodes", checkBoxIncludeExchangeCode.Checked); 
Element eventTypes = request.GetElement("eventTypes"); 
eventTypes.AppendValue("TRADE"); 
eventTypes.AppendValue("BID"); 
eventTypes.AppendValue("ASK"); 
request.Set("security", d_requestSecurity); 
request.Set("startDateTime", new BDateTime(startDate.Year, startDate.Month, 
      startDate.Day,startDate.Hour, startDate.Minute, startDate.Second, 0)); 
request.Set("endDateTime", new BDateTime(endDate.Year, endDate.Month, endDate.Day, 
      endDate.Hour, endDate.Minute, endDate.Second, 0)); 

C'è una diversa, richiesta di un'istantanea dal vivo?

+0

Bloomberg API .NET 3 non è un API ampiamente utilizzato, quindi è improbabile che qualcuno qui sarà in grado di aiutare a meno che non si aggiunge un collegamento alle API – ColinE

+0

Non ne sono così sicuro. Hai qualche cifra? – drexiya

risposta

5

minimamente adattato dall'esempio che viene fornito con l'API:

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using Bloomberglp.Blpapi; 

namespace BbServerApiTool 
{ 
    public class GetFields : GetBloombergFields 
    { 
     private static readonly Name EXCEPTIONS = new Name("exceptions"); 
     private static readonly Name FIELD_ID = new Name("fieldId"); 
     private static readonly Name REASON = new Name("reason"); 
     private static readonly Name CATEGORY = new Name("category"); 
     private static readonly Name DESCRIPTION = new Name("description"); 
     private static readonly Name ERROR_CODE = new Name("errorCode"); 
     private static readonly Name SOURCE = new Name("source"); 
     private static readonly Name SECURITY_ERROR = new Name("securityError"); 
     private static readonly Name MESSAGE = new Name("message"); 
     private static readonly Name RESPONSE_ERROR = new Name("responseError"); 
     private static readonly Name SECURITY_DATA = new Name("securityData"); 
     private static readonly Name FIELD_EXCEPTIONS = new Name("fieldExceptions"); 
     private static readonly Name ERROR_INFO = new Name("errorInfo"); 

     public override List<List<string>> GetBbFields(string[] tickers, string[] fieldsParam) 
     { 
      string serverHost = System.Configuration.ConfigurationManager.AppSettings["Host"]; 
      int serverPort = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Port"]); 

      var sessionOptions = new SessionOptions {ServerHost = serverHost, ServerPort = serverPort}; 

      var session = new Session(sessionOptions); 
      session.Start(); 
      session.OpenService("//blp/refdata"); 
      Service refDataService = session.GetService("//blp/refdata"); 
      Request request = refDataService.CreateRequest("ReferenceDataRequest"); 
      Element securities = request.GetElement("securities"); 
      Element fields = request.GetElement("fields"); 
      request.Set("returnEids", true); 

      foreach (var ticker in tickers) 
      { 
       securities.AppendValue(ticker); 
      } 

      foreach (var field in fieldsParam) 
      { 
       fields.AppendValue(field); 
      } 

      var cID = new CorrelationID(1); 
      session.Cancel(cID); 
      Results = new List<List<string>>(); 
      session.SendRequest(request, cID); 

      while (true) 
      { 
       Event eventObj = session.NextEvent(); 
       processEvent(eventObj, session, fieldsParam); 
       if (eventObj.Type == Event.EventType.RESPONSE) 
       { 
        return Results; 
       } 
      } 
     } 

     protected override string GetName() 
     { 
      return "BbServerApiTool"; 
     } 

     private void processEvent(Event eventObj, Session session, string[] fields) 
     { 
      switch (eventObj.Type) 
      { 
       case Event.EventType.RESPONSE: 
       case Event.EventType.PARTIAL_RESPONSE: 
        processRequestDataEvent(eventObj, session, fields); 
        break; 
       default: 
        processMiscEvents(eventObj, session); 
        break; 
      } 
     } 

     private void processMiscEvents(Event eventObj, Session session) 
     { 
      foreach (Message msg in eventObj.GetMessages()) 
      { 
       switch (msg.MessageType.ToString()) 
       { 
        case "RequestFailure": 
         Element reason = msg.GetElement(REASON); 
         string message = string.Concat("Error: Source-", reason.GetElementAsString(SOURCE), 
          ", Code-", reason.GetElementAsString(ERROR_CODE), ", category-", reason.GetElementAsString(CATEGORY), 
          ", desc-", reason.GetElementAsString(DESCRIPTION)); 
         throw new ArgumentException(message); 
        case "SessionStarted": 
        case "SessionTerminated": 
        case "SessionStopped": 
        case "ServiceOpened": 
        default: 
         break; 
       } 
      } 
     } 
     private void processRequestDataEvent(Event eventObj, Session session, string[] fields) 
     { 
      foreach (Message msg in eventObj.GetMessages()) 
      { 
       if (msg.MessageType.Equals(Name.GetName("ReferenceDataResponse"))) 
       { 
        Element secDataArray = msg.GetElement(SECURITY_DATA); 
        int numberOfSecurities = secDataArray.NumValues; 
        for (int index = 0; index < numberOfSecurities; index++) 
        { 
         Element secData = secDataArray.GetValueAsElement(index); 
         Element fieldData = secData.GetElement("fieldData"); 

         if (secData.HasElement(FIELD_EXCEPTIONS)) 
         { 
          // process error 
          Element error = secData.GetElement(FIELD_EXCEPTIONS); 
          if (error.Elements.Count() > 0) 
          { 
           Element errorException = error.GetValueAsElement(0); 
           Element errorInfo = errorException.GetElement(ERROR_INFO); 
           string message = errorInfo.GetElementAsString(MESSAGE); 
           throw new ArgumentException(message); 
          } 
         } 

         var list = new List<string> { secData.GetElement("security").GetValueAsString() }; 
         if (secData.HasElement(SECURITY_ERROR)) 
         { 
          Element error = secData.GetElement(SECURITY_ERROR); 
          string errorMessage = error.GetElementAsString(MESSAGE); 
          //       throw new ArgumentException(errorMessage); 
          //TODO Log 
          logger.WriteLine("Couldn't get a value for " + secData.GetElement("security").GetValueAsString()); 
          foreach (var field in fields) 
          { 
           list.Add("N/A"); 
          } 
         } 
         else 
         { 
          foreach (var field in fields) 
          { 
           Element item = fieldData.GetElement(field); 
           list.Add(item.IsNull ? "N/A" : item.GetValueAsString()); 
          } 
         } 
         Results.Add(list); 
        } 
       } 
      } 
     } 
    } 
} 
+0

Grazie Ross. Ho testato il ReferenceDataRequest ma non ero sicuro di utilizzare questo, in quanto sembra un tipo di dati "statico" o "di riferimento" di richiesta, e non ero totalmente sicuro di ottenere prezzi in tempo reale. Non riesco a trovare alcuna definizione definitiva di ReferenceDataRequest e non conosco la latenza su questo. Potrei provare a confrontare questi prezzi con un abbonamento, ma stavo pensando che potrebbe essere meglio ottenere IntradayTickRequest ma volevo solo l'ultimo, non per un periodo specificato. Sai se si tratta di un'istantanea live/realtime? – drexiya

+1

Se utilizzi un campo come PX_LAST ti darà l'ultimo prezzo. Non ci sarà un ritardo se il tuo account ha le autorizzazioni per i prezzi in tempo reale. Potrebbe esserci un modo per ottenere il prezzo con una latenza migliore, ma questo approccio è abbastanza veloce per i miei scopi. – RossFabricant

2

Se si vuole garantire prezzi assolutamente dal vivo, si sarebbe probabilmente utilizzare il servizio di abbonamento api (// BLP/mktdata), che sarà anche restituire il prezzo con l'ora esatta dell'ultima transazione taggata ad esso.

C'è un buon esempio di questo nella Guida per gli sviluppatori disponibile tramite un terminale Bloomberg nell'appendice C.2 (Il paradigma dell'abbonamento).

+0

Sì, grazie è vero, avevo preso in considerazione un abbonamento, ma al momento non voglio dover aspettare il prossimo scambio, che potrebbe richiedere del tempo in alcuni mercati. Voglio solo essere in grado di richiedere uno snapshot dal vivo con una latenza minima. Questo è qualcosa che sorprendentemente manca nei campioni della libreria desktop e apparentemente oltre la conoscenza del team di supporto di Bloomberg. Stavo più cercando l'esperienza di chiunque provando a farlo, perché non ho trovato gli esempi utili. – drexiya

+0

È sempre possibile utilizzare il campo ReferenceDataService LAST_PRICE come seme e quindi seguire la sottoscrizione per gli aggiornamenti. Questo ti garantirà il prezzo più aggiornato. –

2

Sembra che non ci sia una richiesta Bloomberg specifica per un 'Live Snapshot' del book degli ordini. Gli altri metodi sono ovviamente documentati negli esempi, ma sembra che Bloomberg non li fornisca nella loro API .Net.

Vi sono richieste di dati di riferimento che sembrano essere le più vicine a un tipo di query di istantanea, ma non vi è documentazione sulla latenza nell'aggiornamento di queste variabili. Il nome "riferimento" non ispira grande fiducia in qualcosa che suona come una richiesta in tempo reale.

Un abbonamento è il metodo alternativo a un tipo di richiesta di istantanea e può essere superiore in molte applicazioni. Con un abbonamento, gli aggiornamenti del book degli ordini vengono trasmessi in streaming direttamente al tuo socket. Lo svantaggio di questo approccio è che hai bisogno dell'architettura interna per supportarlo e inoltre potresti dover attendere un intervallo di tempo indeterminato per vedere qualsiasi attività in alcuni mercati.

Con questo in mente, penso che un approccio per tentativi ed errori sia il migliore, e lavorare con un altro fornitore di dati potrebbe essere più proficuo.

1

Se è necessario ottenere prezzi in tempo reale e non quelli statici, è comunque possibile farlo tramite ReferenceDataRequest. L'unica differenza quale campo usare. PX_LAST ti dà l'ultimo prezzo che conta al limite mensile dei tuoi dati di riferimento. LAST_PRICE ti fornisce l'ultimo prezzo in tempo reale che vale per il limite mensile dei dati in tempo reale.

PS:. Ho ottenuto queste informazioni dal nostro Bloomberg Sales Rep