private List <T> ParseResponse() { List <T> output = new List <T>(); bool isProcessing = true; while (isProcessing) { BbergAPI.Event response = this.session.NextEvent(); switch (response.Type) { case BbergAPI.Event.EventType.PARTIAL_RESPONSE: output = ParseEvent(response, output); // ----------->> THIS HAS BEEN MODIFIED, PREVIOUS VERSION : ParseEvent_OLD break; case BbergAPI.Event.EventType.RESPONSE: output = ParseEvent(response, output); // ----------->> THIS HAS BEEN MODIFIED, PREVIOUS VERSION : ParseEvent_OLD isProcessing = false; break; default: break; } } return(output); }
/// <summary> /// Process responses from the BLP API. /// </summary> /// <param name="session"></param> private void EventLoop(Session session) { bool done = false; while (!done) { Event eventObj = session.NextEvent(); if (eventObj.Type == Event.EventType.PARTIAL_RESPONSE) { System.Console.WriteLine("Processing Partial Response"); ProcessResponseEvent(eventObj); } else if (eventObj.Type == Event.EventType.RESPONSE) { System.Console.WriteLine("Processing Response"); ProcessResponseEvent(eventObj); done = true; } else { foreach (Message msg in eventObj) { System.Console.WriteLine(msg); if (eventObj.Type == Event.EventType.SESSION_STATUS) { if (msg.MessageType.Equals(SESSION_TERMINATED) || msg.MessageType.Equals(SESSION_FAILURE)) { done = true; } } } } } }
/// <summary> /// Processes responses from the BLP API. Called by the EventLoop. /// </summary> /// <param name="eventObj"></param> private void ProcessResponseEvent(Event eventObj) { foreach (Message msg in eventObj) { if (msg.MessageType == ERROR_RESPONSE) { String description = msg.GetElementAsString(DESCRIPTION_ELEMENT); Console.WriteLine("Received error: " + description); } else if (msg.MessageType == INSTRUMENT_LIST_RESPONSE) { ProcessInstrumentListResponse(msg); } else if (msg.MessageType == CURVE_LIST_RESPONSE) { ProcessCurveListResponse(msg); } else if (msg.MessageType == GOVT_LIST_RESPONSE) { ProcessGovtListResponse(msg); } else { Console.Error.WriteLine("Unknown MessageType received"); } } }
private void ProcessAdminMessage(Bloomberglp.Blpapi.Event argvEvent) { InterfaceEventArgs tArgs = new InterfaceEventArgs(InterfaceEventArgs.xBbgMsgType.Error); // Loop over all of the messages in this Event foreach (Bloomberglp.Blpapi.Message msg in argvEvent) { tArgs.mMsg += msg.ToString(); } mBbgMsgEvent(this, tArgs); }
private List <T> ParseEvent_OLD(BbergAPI.Event response, List <T> outputContainer) { foreach (BbergAPI.Message message in response.GetMessages()) { // Extract security BbergAPI.Element security = message.GetElement(SECURITY_DATA); string currentSec = (string)security.GetElementAsString(TICKER); // Extract fields BbergAPI.Element fields = security.GetElement(FIELD_DATA); int sequenceNumber = security.GetElementAsInt32(SEQUENCE_NUMBER); Dictionary <string, int> skipFields = this.initializeSkipFields(); // Loop through all observation dates for (int i = 0; i < fields.NumValues; i++) { // Determine type of <T> and create instance var Ttype = typeof(T); var thisLine = (T)Activator.CreateInstance(Ttype); // extract all field data for a single observation date BbergAPI.Element observationDateFields = fields.GetValueAsElement(i); string currentStringDate = observationDateFields.GetElementAsString(DATE); DateTime currentDate = DateTime.ParseExact(currentStringDate, "yyyy-MM-dd", CultureInfo.CurrentCulture); // Determine type of <T> and create instance thisLine.SetDate(currentDate); thisLine.SetDBID(dbid); // Fill the line skipFields = thisLine.SetFromBloomberg(ref observationDateFields, skipFields); // Add to output container outputContainer.Add(thisLine); } } // This kills the data inside the response object... this.CloseConnection(); return(outputContainer); }
/// <summary> /// Processes the Bloomberg event. /// </summary> /// <param name="eventObj">The event obj.</param> /// <param name="session">The session.</param> private void processEvent(BB.Event eventObj, BB.Session session) { try { switch (eventObj.Type) { case BB.Event.EventType.RESPONSE: case BB.Event.EventType.PARTIAL_RESPONSE: processSubscriptionDataEvent(eventObj, session); break; default: processMiscEvents(eventObj, session); break; } } catch (System.Exception e) { Maple.Logger.Log(e.Message); Maple.Logger.Log(e.StackTrace); } }
private void ProcessSessionStatusChange(Bloomberglp.Blpapi.Event argvEvent) { foreach (Bloomberglp.Blpapi.Message msg in argvEvent) { mBbgMsgEvent(this, new InterfaceEventArgs(InterfaceEventArgs.xBbgMsgType.Print, msg.ToString())); if (msg.MessageType == Bloomberglp.Blpapi.Name.FindName("SessionTerminated") || msg.MessageType == Bloomberglp.Blpapi.Name.FindName("SessionConnectionDown")) { isSessionRunning = false; mBbgMsgEvent(this, new InterfaceEventArgs(InterfaceEventArgs.xBbgMsgType.LoginFail, msg.ToString())); this.ShutDown(); } if (msg.MessageType == Bloomberglp.Blpapi.Name.FindName("SessionStarted")) { isSessionRunning = true; mBbgMsgEvent(this, new InterfaceEventArgs(InterfaceEventArgs.xBbgMsgType.LoginSuccess, "LoginSuccess")); } } }
private void ProcessRequestResponse(Bloomberglp.Blpapi.Event argvEvent) { // Loop over all of the messages in this Event foreach (Bloomberglp.Blpapi.Message tMsg in argvEvent) { Bloomberglp.Blpapi.Element tElementMsg = tMsg.AsElement; System.Data.DataTable tResponseErrorTable = this.ExtractValueByName(tElementMsg, mRequestResponseErrorAttributes); if (tResponseErrorTable.Rows.Count > 0) { string tErrorMsg = "Message Type: " + tMsg.MessageType.ToString() + Environment.NewLine; for (int i = 0; i < tResponseErrorTable.Rows.Count; i++) { tErrorMsg += "Error Message: " + tResponseErrorTable.Rows[i]["MESSAGE"] + ", Category: " + tResponseErrorTable.Rows[i]["SUBCATEGORY"] + Environment.NewLine; } InterfaceEventArgs tEventArgvs = new InterfaceEventArgs(InterfaceEventArgs.xBbgMsgType.Error, tErrorMsg); mBbgMsgEvent(this, tEventArgvs); } if (tMsg.MessageType.Equals(new Bloomberglp.Blpapi.Name("HistoricalDataResponse"))) { this.ProcessHistoricalDataResponse(tMsg); } else if (tMsg.MessageType.Equals(new Bloomberglp.Blpapi.Name("IntradayTickResponse"))) { this.ProcessIntradayTickResponse(tMsg); } else if (tMsg.MessageType.Equals(new Bloomberglp.Blpapi.Name("IntradayBarResponse"))) { this.ProcessIntradayBarResponse(tMsg); } else if (tMsg.MessageType.Equals(new Bloomberglp.Blpapi.Name("ReferenceDataResponse"))) { this.ProcessReferenceDataResponse(tMsg); } else { mBbgMsgEvent(this, new InterfaceEventArgs(InterfaceEventArgs.xBbgMsgType.Print, tMsg.ToString())); } } }
private void ProcessSubscriptionStatus(Bloomberglp.Blpapi.Event argEvent) { foreach (Bloomberglp.Blpapi.Message tMsg in argEvent) { foreach (CorrelationID tId in tMsg.CorrelationIDs) { if (tMsg.MessageType.ToString() == "SubscriptionFailure") { string tTicker = string.Empty; if (mSubscriptionByCorrelationId.ContainsKey(tId.Value)) { tTicker = mSubscriptionByCorrelationId[tId.Value].mTicker; } InterfaceEventArgs tArgs = new InterfaceEventArgs(InterfaceEventArgs.xBbgMsgType.Error); tArgs.mMsg = "SubscriptionFailure: Ticker '" + tTicker + "'"; mBbgMsgEvent(this, tArgs); } } } }
public List <String> SearchTicker(String ticker) { List <String> listTicker = new List <string>(); // request.AsElement.SetElement("partialMatch", true); request.AsElement.SetElement("query", ticker);// this plus the previous line permits to retrieve all the thicker that begins with T request.AsElement.SetElement("languageOverride", "LANG_OVERRIDE_NONE"); request.AsElement.SetElement("maxResults", 10); session.SendRequest(request, null); bool done = false; while (!done) { // Grab the next Event object Event eventObject = session.NextEvent(); // If this event type is Response then process the messages if (eventObject.Type == Event.EventType.RESPONSE) { // Loop over all of the messages in this Event foreach (Message msg in eventObject.GetMessages()) { Console.WriteLine(msg); Element secDataArray = msg.GetElement("results"); for (int index = 0; index < secDataArray.NumValues - 1; index++) { Element fieldData = secDataArray.GetValueAsElement(index); if (fieldData.HasElement("security")) { listTicker.Add(fieldData.GetElementAsString("security")); } } } done = true; } } return(listTicker); }
private void ProcessSubscriptionData(Bloomberglp.Blpapi.Event argEvent) { foreach (Bloomberglp.Blpapi.Message tMsg in argEvent) { Bloomberglp.Blpapi.Element tElementMsg = tMsg.AsElement; string[] tTargetAttributes = mSubscriptionByCorrelationId[tMsg.CorrelationID.Value].GetFieldList(); System.Data.DataTable tExtractedValues = this.ExtractValueByName(tElementMsg, tTargetAttributes); System.Data.DataColumn tNewColumn = new System.Data.DataColumn("SECURITY"); tNewColumn.DefaultValue = tMsg.TopicName; tExtractedValues.Columns.Add(tNewColumn); tNewColumn.SetOrdinal(0); //mOutput.PrintDataTable(tExtractedValues); if (tExtractedValues.Rows.Count == 1) { mMarketData[tMsg.CorrelationID.Value].UpdateMarketData(tExtractedValues); InterfaceEventArgs tArgs = new InterfaceEventArgs(InterfaceEventArgs.xBbgMsgType.SubscriptionResponse); tArgs.mCorrelationId = tMsg.CorrelationID.Value; tArgs.mData = tExtractedValues; mBbgMsgEvent(this, tArgs); } } }
/***************************************************************************** * Function : processEvent * Description : Processes session events * Arguments : Event, Session * Returns : void *****************************************************************************/ public void processEvent(Event eventObj, Session session) { try { switch (eventObj.Type) { case Event.EventType.SUBSCRIPTION_DATA: processSubscriptionDataEvent(eventObj, session); break; case Event.EventType.SUBSCRIPTION_STATUS: processSubscriptionStatus(eventObj, session); break; default: processMiscEvents(eventObj, session); break; } } catch (System.Exception e) { System.Console.WriteLine(e.ToString()); } }
private List <T> ParseEvent(BbergAPI.Event response, List <T> outputContainer) { foreach (BbergAPI.Message message in response.GetMessages()) { // Extract security BbergAPI.Element security = message.GetElement(SECURITY_DATA); string currentSec = (string)security.GetElementAsString(TICKER); // Extract fields BbergAPI.Element fields = security.GetElement(FIELD_DATA); int sequenceNumber = security.GetElementAsInt32(SEQUENCE_NUMBER); // Loop through all observation dates for (int i = 0; i < fields.NumValues; i++) { // Determine type of <T> and create instance var Ttype = typeof(T); var thisLine = (T)Activator.CreateInstance(Ttype); // extract all field data for a single observation date BbergAPI.Element observationDateFields = fields.GetValueAsElement(i); string currentStringDate = observationDateFields.GetElementAsString(DATE); DateTime currentDate = DateTime.ParseExact(currentStringDate, "yyyy-MM-dd", CultureInfo.CurrentCulture); // Set the date and DBID to identify the line thisLine.SetDate(currentDate); thisLine.SetDBID(dbid); // Fill the line with data foreach (string localKey in this.fieldNames.Keys) { if (skip[localKey] < 10000) { try { // Warning : Bloomberg displays interest rates in percentage terms thisLine[localKey] = scaling[localKey] * (double)observationDateFields.GetElementAsFloat64(fieldNames[localKey]); } catch { // Some log ? skip[localKey] += 1; // thisLine[localKey] = System.DBNull.Value; thisLine[localKey] = null; //thisLine[localKey] = 0.0; } } } // Add to output container outputContainer.Add(thisLine); } } // This kills the data inside the response object... this.CloseConnection(); return(outputContainer); }
/// <summary> /// Processes the Bloomberg subscription data event. /// </summary> /// <param name="eventObj">The event obj.</param> /// <param name="session">The session.</param> private void processSubscriptionDataEvent(BB.Event eventObj, BB.Session session) { try { // process message foreach (BB.Message msg in eventObj.GetMessages()) { #region find instrument Guid reqGUID = (Guid)msg.CorrelationID.Object; // check for duplicate replies just in case if (guids.Contains(reqGUID)) { return; } else { guids.Add(reqGUID); } // find the correct instrument BloombergDataInstrument bbdi = FindSentInstrumentByGuid(reqGUID); if (bbdi == null) { UpdateStatus("Unable to find received instrument by Guid - " + reqGUID.ToString()); continue; } #endregion UpdateStatus(string.Format("Received {0} of {1} requests : {2}", guids.Count, sentToBB.Count, bbdi.Ticker)); if (msg.HasElement("responseError")) { BB.Element error = msg.GetElement(RESPONSE_ERROR); string responseError = error.GetElementAsString(SUBCATEGORY); UpdateStatus("Response error : " + error.GetElementAsString(MESSAGE)); CheckForLimits(responseError); bbdi.HasFieldErrors = true; continue; } BB.Element secDataArray = msg.GetElement(SECURITY_DATA); #region process security data // process security data int numberOfSecurities = secDataArray.NumValues; for (int index = 0; index < numberOfSecurities; index++) { if (msg.MessageType.Equals(Bloomberglp.Blpapi.Name.GetName(BLP_REFERENCE_RESPONSE))) { // just contains the one element, which is actually a sequence BB.Element secData = secDataArray.GetValueAsElement(index); BB.Element fields = secData.GetElement(FIELD_DATA); GetData(bbdi, fields, secData); } else if (msg.MessageType.Equals(Bloomberglp.Blpapi.Name.GetName(BLP_HISTORICAL_RESPONSE))) { // Historical is handled slightly different. Can contain many elements each with possibly multiple values foreach (BB.Element secData in secDataArray.Elements) { if (secData.Name != FIELD_DATA) { continue; } for (int pointIndex = 0; pointIndex < secData.NumValues; pointIndex++) { BB.Element fields = secData.GetValueAsElement(pointIndex); GetData(bbdi, fields, secData); } } } } #endregion ShowCompletionPercentage(guids.Count, sentToBB.Count); ShowCompletedInstrument(bbdi); } } catch (Exception ex) { UpdateStatus("Error occurred processing reply : " + ex.Message); } finally { if (guids.Count == sentToBB.Count) // we are done { ShowCompletionPercentage(1, 1); ProcessComplete(); } } }
/// <summary> /// Processes misc Bloomberg events. /// </summary> /// <param name="eventObj">The event obj.</param> /// <param name="session">The session.</param> private void processMiscEvents(BB.Event eventObj, BB.Session session) { foreach (BB.Message msg in eventObj.GetMessages()) { UpdateStatus(msg.MessageType.ToString()); switch (msg.MessageType.ToString()) { case "SessionStarted": break; case "SessionTerminated": case "SessionStopped": break; case "ServiceOpened": break; case "RequestFailure": UpdateStatus("*** REQUEST FAILURE ***"); BB.Element reason = msg.GetElement(REASON); string reasonText = string.Format("Error: Source-[{0}], Code-[{1}], Category-[{2}], Desc-[{3}]", reason.GetElementAsString(SOURCE), reason.GetElementAsString(ERROR_CODE), reason.GetElementAsString(CATEGORY), reason.GetElementAsString(DESCRIPTION)); UpdateStatus(reasonText); UpdateStatus("Error message body : " + msg.ToString()); bool hasGUID = false; bool hasResponseError = false; try { Guid reqGUID = (Guid)msg.CorrelationID.Object; hasGUID = true; hasResponseError = msg.HasElement("responseError"); } catch { hasGUID = false; hasResponseError = false; } if (hasGUID & hasResponseError) { UpdateStatus("GUID and responseError found - handling normally"); // has both a GUID and a response error so can be handled normally processSubscriptionDataEvent(eventObj, session); } else if (hasGUID) { UpdateStatus("GUID found - updating GUID list."); Guid reqGUID = (Guid)msg.CorrelationID.Object; // only has a GUID so add to the list of returned GUIDs if (!guids.Contains(reqGUID)) { guids.Add(reqGUID); } } else { // ok, email out that a timeout has occurred Maple.Email email = new Maple.Email(); email.SendEmail(emailErrorsTo, "Bloomberg Request Failure", "A RequestFailure response has been returned from Bloomberg." + Environment.NewLine + reasonText + Environment.NewLine + msg.ToString(), false); } break; default: UpdateStatus("*** Unhandled Misc Event ***"); break; } } }
/// <summary> /// Authorize should be called before any requests are sent. Called by init. /// </summary> /// <param name="identity"></param> /// <param name="session"></param> private static void Authorize(out Identity identity, Session session) { identity = session.CreateIdentity(); if (!session.OpenService(AUTH_SERVICE)) { throw new Exception( string.Format("Failed to open auth service: {0}", AUTH_SERVICE)); } Service authService = session.GetService(AUTH_SERVICE); EventQueue tokenEventQueue = new EventQueue(); session.GenerateToken(new CorrelationID(tokenEventQueue), tokenEventQueue); string token = null; // Generate token responses will come on the dedicated queue. There would be no other // messages on that queue. Event eventObj = tokenEventQueue.NextEvent( Convert.ToInt32(WAIT_TIME.TotalMilliseconds)); if (eventObj.Type == Event.EventType.TOKEN_STATUS || eventObj.Type == Event.EventType.REQUEST_STATUS) { foreach (Message msg in eventObj) { System.Console.WriteLine(msg); if (msg.MessageType == TOKEN_SUCCESS) { token = msg.GetElementAsString(TOKEN_ELEMENT); } } } if (token == null) { throw new Exception("Failed to get token"); } Request authRequest = authService.CreateAuthorizationRequest(); authRequest.Set(TOKEN_ELEMENT, token); session.SendAuthorizationRequest(authRequest, identity, null); TimeSpan ts = WAIT_TIME; for (DateTime startTime = DateTime.UtcNow; ts.TotalMilliseconds > 0; ts = ts - (DateTime.UtcNow - startTime)) { eventObj = session.NextEvent(Convert.ToInt32(ts.TotalMilliseconds)); // Since no other requests were sent using the session queue, the response can // only be for the Authorization request if (eventObj.Type != Event.EventType.RESPONSE && eventObj.Type != Event.EventType.PARTIAL_RESPONSE && eventObj.Type != Event.EventType.REQUEST_STATUS) { continue; } foreach (Message msg in eventObj) { System.Console.WriteLine(msg); if (msg.MessageType != AUTHORIZATION_SUCCESS) { throw new Exception("Authorization Failed"); } } return; } throw new Exception("Authorization Failed"); }