/// <summary> /// Data event /// </summary> /// <param name="eventObj"></param> /// <param name="session"></param> private void processEvent(Event eventObj, Session session) { if (InvokeRequired) { Invoke(new EventHandler(processEvent), new object[] { eventObj, session }); } else { try { switch (eventObj.Type) { case Event.EventType.RESPONSE: // process final respose for request processRequestDataEvent(eventObj, session); setControlStates(); toolStripStatusLabel1.Text = "Completed"; break; case Event.EventType.PARTIAL_RESPONSE: // process partial response processRequestDataEvent(eventObj, session); break; default: processMiscEvents(eventObj, session); break; } } catch (System.Exception e) { toolStripStatusLabel1.Text = e.Message.ToString(); } } }
public void processEvent(Event evt, Session session) { try { switch (evt.Type) { case Event.EventType.SESSION_STATUS: processSessionEvent(evt, session); break; case Event.EventType.SERVICE_STATUS: processServiceEvent(evt, session); break; case Event.EventType.RESPONSE: processResponseEvent(evt, session); break; default: processMiscEvents(evt, session); break; } } catch (Exception e) { System.Console.Error.WriteLine(e); } }
public void processEvent(Event evt, Session session) { switch (evt.Type) { case EventType.ADMIN: processAdminEvent(evt, session); break; case EventType.SESSION_STATUS: processSessionEvent(evt, session); break; case EventType.SERVICE_STATUS: processServiceEvent(evt, session); break; case EventType.SUBSCRIPTION_DATA: processSubscriptionDataEvent(evt, session); break; case EventType.SUBSCRIPTION_STATUS: processSubscriptionStatus(evt, session); break; default: processMiscEvents(evt, session); break; } }
private void initialise() { fields = new SubscriptionFields(this); securities = new Securities(this); SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = this.host; sessionOptions.ServerPort = this.port; this.session = new Session(sessionOptions, new EventHandler(processEvent)); try { this.session.StartAsync(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } while (!this.ready) { ; } }
/// <summary> /// Request status event /// </summary> /// <param name="eventObj"></param> /// <param name="session"></param> private void processRequestStatusEvent(Event eventObj, Session session) { List <string> dataList = new List <string>(); // process status message foreach (Message msg in eventObj) { ListViewGroup group = (ListViewGroup)msg.CorrelationID.Object; if (msg.MessageType.Equals(Bloomberglp.Blpapi.Name.GetName("SubscriptionStarted"))) { // set waiting for subscription to start color setGroupColor(group, Color.Yellow); } else { // check for subscription failure if (msg.MessageType.Equals(Bloomberglp.Blpapi.Name.GetName("SubscriptionFailure"))) { // set exception color setGroupColor(group, Color.Red); if (msg.HasElement(REASON)) { Element reason = msg.GetElement(REASON); string message = reason.GetElementAsString(DESCRIPTION); group.Items[0].SubItems[1].Text = message; } } } } }
private void sendIntradayTickRequest(Session session) { Service refDataService = session.GetService("//blp/refdata"); Request request = refDataService.CreateRequest("IntradayTickRequest"); request.Set("security", d_security); // Add fields to request Element eventTypes = request.GetElement("eventTypes"); for (int i = 0; i < d_events.Count; ++i) { eventTypes.AppendValue((string)d_events[i]); } // All times are in GMT request.Set("startDateTime", d_startDateTime); request.Set("endDateTime", d_endDateTime); if (d_conditionCodes) { request.Set("includeConditionCodes", true); } System.Console.WriteLine("Sending Request: " + request); session.SendRequest(request, null); }
public void Run(String[] args) { if (!ParseCommandLine(args)) { return; } session = CreateSession(); try { if (!session.Start()) { System.Console.WriteLine("Failed to start session."); return; } // Authenticate user using Generate Token Request if (!GenerateToken()) { return; } } finally { session.Stop(); } }
private void processSessionEvent(Event evt, Session session) { Log.LogMessage(LogLevels.BASIC, "Processing " + evt.Type.ToString()); foreach (Message msg in evt) { if (msg.MessageType.Equals(SESSION_STARTED)) { Log.LogMessage(LogLevels.BASIC, "Session started..."); session.OpenServiceAsync(MKTDATA_SERVICE); } else if (msg.MessageType.Equals(SESSION_STARTUP_FAILURE)) { Log.LogMessage(LogLevels.BASIC, "Error: Session startup failed"); } else if (msg.MessageType.Equals(SESSION_TERMINATED)) { Log.LogMessage(LogLevels.BASIC, "Session has been terminated"); } else if (msg.MessageType.Equals(SESSION_CONNECTION_UP)) { Log.LogMessage(LogLevels.BASIC, "Session connection is up"); } else if (msg.MessageType.Equals(SESSION_CONNECTION_DOWN)) { Log.LogMessage(LogLevels.BASIC, "Session connection is down"); } } }
/// <summary> /// Process subscription data /// </summary> /// <param name="eventObj"></param> /// <param name="session"></param> private void processRequestDataEvent(Event eventObj, Session session) { d_data.BeginLoadData(); // process message foreach (Message msg in eventObj) { if (msg.MessageType.Equals(Bloomberglp.Blpapi.Name.GetName("IntradayBarResponse"))) { if (msg.HasElement(RESPONSE_ERROR)) { // process error Element error = msg.GetElement(RESPONSE_ERROR); if (msg.NumElements == 1) { d_data.Rows.Add(new object[] { d_requestSecurity, error.GetElementAsString(MESSAGE) }); return; } } // process bar data Element barDataArray = msg.GetElement("barData"); int numberOfBars = barDataArray.NumValues; foreach (Element barData in barDataArray.Elements) { if (barData.Name.ToString() == "barTickData") { for (int pointIndex = 0; pointIndex < barData.NumValues; pointIndex++) { int fieldIndex = 0; object[] dataValues = new object[d_data.Columns.Count]; Element fields = barData.GetValueAsElement(pointIndex); foreach (DataColumn col in d_data.Columns) { if (fields.HasElement(col.ColumnName)) { // process field data Element item = fields.GetElement(col.ColumnName); dataValues[fieldIndex] = item.GetValueAsString(); } else { if (col.ColumnName == "security") { dataValues[fieldIndex] = d_requestSecurity; } else { dataValues[fieldIndex] = DBNull.Value; } } fieldIndex++; } // end foreach // save bar data d_data.Rows.Add(dataValues); } // end for loop } // end if } // end foreach } // end if } // end foreach d_data.EndLoadData(); }
private void processResponseEvent(Event evt, Session session) { System.Console.WriteLine("Received Event: " + evt.Type); foreach (Message msg in evt) { if (msg.CorrelationID == requestID) { System.Console.WriteLine(msg.MessageType + ">>" + msg.ToString()); if (msg.MessageType.Equals("handle")) { String val = msg.GetElementAsString("value"); System.Console.WriteLine("Response: Value=" + val); } else { System.Console.WriteLine("Unexpected message..."); System.Console.WriteLine(msg.ToString()); } quit = true; } } }
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: lock (d_lock) { processSubscriptionStatus(eventObj, session); } break; case Event.EventType.ADMIN: lock (d_lock) { processAdminEvent(eventObj, session); } break; default: processMiscEvents(eventObj, session); break; } } catch (System.Exception e) { System.Console.WriteLine(e.ToString()); } }
/// <summary> /// Process miscellaneous events /// </summary> /// <param name="eventObj"></param> /// <param name="session"></param> private void processMiscEvents(Event eventObj, Session session) { foreach (Message msg in eventObj) { switch (msg.MessageType.ToString()) { case "SessionStarted": // "Session Started" break; case "SessionTerminated": case "SessionStopped": // "Session Terminated" break; case "ServiceOpened": // "Reference Service Opened" break; 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)); toolStripStatusLabel1.Text = message; break; default: toolStripStatusLabel1.Text = msg.MessageType.ToString(); break; } } }
/// <summary> /// Data Event /// </summary> /// <param name="eventObj"></param> /// <param name="session"></param> private void processEvent(Event eventObj, Session session) { if (InvokeRequired) { Invoke(new EventHandler(processEvent), new object[] { eventObj, session }); } else { try { switch (eventObj.Type) { case Event.EventType.SUBSCRIPTION_DATA: // process subscription data processRequestDataEvent(eventObj, session); break; case Event.EventType.SUBSCRIPTION_STATUS: // process subscription status processRequestStatusEvent(eventObj, session); break; default: processMiscEvents(eventObj, session); break; } } catch (System.Exception e) { toolStripStatusLabel1.Text = e.Message.ToString(); } } }
private void processServiceEvent(Event evt, Session session) { System.Console.WriteLine("\nProcessing " + evt.Type); foreach (Message msg in evt) { if (msg.MessageType.Equals(SERVICE_OPENED)) { System.Console.WriteLine("Service opened..."); Service service = session.GetService(d_service); Request request = service.CreateRequest("GetBrokerSpecForUuid"); request.Set("uuid", 8049857); System.Console.WriteLine("Request: " + request.ToString()); requestID = new CorrelationID(); // Submit the request try { session.SendRequest(request, requestID); } catch (Exception ex) { System.Console.Error.WriteLine("Failed to send the request: " + ex.Message); } } else if (msg.MessageType.Equals(SERVICE_OPEN_FAILURE)) { System.Console.Error.WriteLine("Error: Service failed to open"); } } }
void sendMSG1RecoverRequest(Session session) { Service service = session.GetService(MSG1_SERVICE); Identity id = session.CreateIdentity(); Request request = service.CreateRequest(REPLAY); request.GetElement(START).SetChoice(d_startType); if (d_startType == TIME) { request.GetElement(START).SetChoice(TIME).SetValue(d_startTime); } else if (d_startType == SERIAL) { request.GetElement(START).SetChoice(SERIAL).SetValue(d_startSerial); } if (d_endType == TIME) { request.GetElement(END).SetChoice(TIME).SetValue(d_endTime); } else if (d_endType == SERIAL) { request.GetElement(END).SetChoice(SERIAL).SetValue(d_endSerial); } if (d_eidProvided) { request.GetElement(EID).SetValue(d_eid); } request.GetElement(FILTER).SetValue(Enum.GetName(d_filter.GetType(), d_filter)); System.Console.WriteLine("Sending request: " + request.ToString()); // request data with identity object session.SendRequest(request, d_identity, null); }
/// <summary> /// Function to create subscription list and subscribe to pagedata /// </summary> /// <param name="session"></param> private void subscribe(Session session) { System.Collections.Generic.List <Subscription> subscriptions = new System.Collections.Generic.List <Subscription>(); d_topicTable.Clear(); List <string> fields = new List <string>(); fields.Add("6-23"); // Following commented code shows some of the sample values // that can be used for field other than above // e.g. fields.Add("1"); // fields.Add("1,2,3"); // fields.Add("1,6-10,15,16"); foreach (string topic in d_topics) { subscriptions.Add(new Subscription(PAGEDATA_SVC + "/" + topic, fields, null, new CorrelationID(topic))); d_topicTable.Add(topic, new ArrayList()); } if (d_authOption == "NONE") { session.Subscribe(subscriptions); } else { session.Subscribe(subscriptions, d_identity); } }
private void processResponseEvent(Event evt, Session session) { System.Console.WriteLine("Received Event: " + evt.Type); foreach (Message msg in evt) { System.Console.WriteLine("MESSAGE: " + msg.ToString()); System.Console.WriteLine("CORRELATION ID: " + msg.CorrelationID); if (evt.Type == Event.EventType.RESPONSE && msg.CorrelationID == requestID) { System.Console.WriteLine("Message Type: " + msg.MessageType); if (msg.MessageType.Equals(ERROR_INFO)) { int errorCode = msg.GetElementAsInt32("ERROR_CODE"); String errorMessage = msg.GetElementAsString("ERROR_MESSAGE"); System.Console.WriteLine("ERROR CODE: " + errorCode + "\tERROR MESSAGE: " + errorMessage); } else if (msg.MessageType.Equals(DELETE_ORDER)) { int status = msg.GetElementAsInt32("STATUS"); String message = msg.GetElementAsString("MESSAGE"); System.Console.WriteLine("STATUS: " + status + "\tMESSAGE: " + message); } quit = true; session.Stop(); } } }
// return true if processing is completed, false otherwise private void processResponseEvent(Event eventObj, Session session) { foreach (Message msg in eventObj) { processMessage(msg); } }
private void processResponseEvent(Event evt, Session session) { System.Console.WriteLine("Received Event: " + evt.Type); foreach (Message msg in evt) { System.Console.WriteLine("MESSAGE: " + msg.ToString()); System.Console.WriteLine("CORRELATION ID: " + msg.CorrelationID); if (evt.Type == Event.EventType.RESPONSE && msg.CorrelationID == requestID) { System.Console.WriteLine("Message Type: " + msg.MessageType); if (msg.MessageType.Equals(ERROR_INFO)) { int errorCode = msg.GetElementAsInt32("ERROR_CODE"); String errorMessage = msg.GetElementAsString("ERROR_MESSAGE"); System.Console.WriteLine("ERROR CODE: " + errorCode + "\tERROR MESSAGE: " + errorMessage); } else if (msg.MessageType.Equals(ROUTE_WITH_STRAT)) { int emsx_sequence = msg.GetElementAsInt32("EMSX_SEQUENCE"); int emsx_route_id = msg.GetElementAsInt32("EMSX_ROUTE_ID"); String message = msg.GetElementAsString("MESSAGE"); System.Console.WriteLine("EMSX_SEQUENCE: " + emsx_sequence + "\tEMSX_ROUTE_ID: " + emsx_route_id + "\tMESSAGE: " + message); } quit = true; session.Stop(); } } }
private void processServiceEvent(Event evt, Session session) { System.Console.WriteLine("\nProcessing " + evt.Type); foreach (Message msg in evt) { if (msg.MessageType.Equals(SERVICE_OPENED)) { String serviceName = msg.AsElement.GetElementAsString("serviceName"); System.Console.WriteLine("Service opened [" + serviceName + "]..."); if (serviceName == d_auth) { System.Console.WriteLine("Auth Service opened... Opening EMSX service..."); session.OpenServiceAsync(d_emsx); } else if (serviceName == d_emsx) { System.Console.WriteLine("EMSX Service opened... Sending Authorization requests"); sendAuthRequest(session, d_user, d_ip); } } else if (msg.MessageType.Equals(SERVICE_OPEN_FAILURE)) { System.Console.Error.WriteLine("Error: Service failed to open"); } } }
public string startSession() { string retval = ""; retval += "\nStarting session...\n"; SessionOptions d_sessionOptions = new SessionOptions(); d_sessionOptions.ServerHost = d_host; d_sessionOptions.ServerPort = d_port; session = new Session(d_sessionOptions); if (!session.Start()) { retval += "\nError: failed to start session.\n"; return(retval); } retval += "\nSession started!\n"; if (!session.OpenService(d_service)) { session.Stop(); retval += "\nError: failed to open service.\n"; return(retval); } service = session.GetService(d_service); retval += "\nService opened!\n"; return(retval); }
/// <summary> /// Function to create and send PortfolioDataRequest /// </summary> /// <param name="session"></param> private void sendPortfolioDataRequest(Session session) { Service refDataService = session.GetService("//blp/refdata"); Request request = refDataService.CreateRequest("PortfolioDataRequest"); // Add securities to request Element securities = request.GetElement("securities"); for (int i = 0; i < d_securities.Count; ++i) { securities.AppendValue((string)d_securities[i]); } // Add fields to request Element fields = request.GetElement("fields"); for (int i = 0; i < d_fields.Count; ++i) { fields.AppendValue((string)d_fields[i]); } // If specified, use REFERENCE_DATE override field // to get portfolio information historically. // The date must be in 'YYYYMMDD' format if (d_override != null && d_override.Length != 0) { Element overrides = request["overrides"]; Element override1 = overrides.AppendElement(); override1.SetElement("fieldId", "REFERENCE_DATE"); override1.SetElement("value", d_override); } System.Console.WriteLine("Sending Request: " + request); session.SendRequest(request, null); }
private void run(string[] args) { if (!parseCommandLine(args)) { return; } SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = d_host; sessionOptions.ServerPort = d_port; System.Console.WriteLine("Connecting to " + d_host + ":" + d_port); Session session = new Session(sessionOptions); bool sessionStarted = session.Start(); if (!sessionStarted) { System.Console.Error.WriteLine("Failed to start session."); return; } sendIntradayBarRequest(session); // wait for events from session. eventLoop(session); session.Stop(); }
/// <summary> /// Polls for an event or a message in an event loop /// & Processes the event generated /// </summary> /// <param name="session"></param> private void eventLoop(Session session) { while (true) { Event eventObj = session.NextEvent(); 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 void initialise() { Log.logPrefix = "EasyIOI"; this.iois = new IOIs(this); SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = this.host; sessionOptions.ServerPort = this.port; this.session = new Session(sessionOptions, new EventHandler(processEvent)); try { this.session.StartAsync(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } while (!this.ready) { ; } }
/// <summary> /// Process SubscriptionStatus event /// </summary> /// <param name="eventObj"></param> /// <param name="session"></param> private void processSubscriptionStatus(Event eventObj, Session session) { System.Console.WriteLine("Processing SUBSCRIPTION_STATUS"); foreach (Message msg in eventObj.GetMessages()) { string topic = (string)msg.CorrelationID.Object; System.Console.WriteLine(System.DateTime.Now.ToString("s") + ": " + topic + " - " + msg.MessageType); if (msg.HasElement(REASON)) { // This can occur on SubscriptionFailure. Element reason = msg.GetElement(REASON); System.Console.WriteLine("\t" + reason.GetElement(CATEGORY).GetValueAsString() + ": " + reason.GetElement(DESCRIPTION).GetValueAsString()); } if (msg.HasElement(EXCEPTIONS)) { // This can occur on SubscriptionStarted if at least // one field is good while the rest are bad. Element exceptions = msg.GetElement(EXCEPTIONS); for (int i = 0; i < exceptions.NumValues; ++i) { Element exInfo = exceptions.GetValueAsElement(i); Element fieldId = exInfo.GetElement(FIELD_ID); Element reason = exInfo.GetElement(REASON); System.Console.WriteLine("\t" + fieldId.GetValueAsString() + ": " + reason.GetElement(CATEGORY).GetValueAsString()); } } System.Console.WriteLine(""); } }
private void processResponseEvent(Event evt, Session session) { System.Console.WriteLine("Received Event: " + evt.Type); foreach (Message msg in evt) { System.Console.WriteLine("MESSAGE: " + msg.ToString()); System.Console.WriteLine("CORRELATION ID: " + msg.CorrelationID); if (evt.Type == Event.EventType.RESPONSE && msg.CorrelationID == requestID) { System.Console.WriteLine("Message Type: " + msg.MessageType); if (msg.MessageType.Equals(ERROR_INFO)) { int errorCode = msg.GetElementAsInt32("ERROR_CODE"); String errorMessage = msg.GetElementAsString("ERROR_MESSAGE"); System.Console.WriteLine("ERROR CODE: " + errorCode + "\tERROR MESSAGE: " + errorMessage); } else if (msg.MessageType.Equals(MODIFY_ROUTE_EX)) { // The response has fields for EMSX_SEQUENCE and EMSX_ROUTE_ID, but these will always be zero String message = msg.GetElementAsString("MESSAGE"); System.Console.WriteLine("MESSAGE: " + message); } quit = true; session.Stop(); } } }
/// <summary> /// Request status event /// </summary> /// <param name="eventObj"></param> /// <param name="session"></param> private void processRequestStatusEvent(Event eventObj, Session session) { List <string> dataList = new List <string>(); // process status message foreach (Message msg in eventObj) { DataGridViewRow dataRow = (DataGridViewRow)msg.CorrelationID.Object; if (msg.MessageType.Equals(Bloomberglp.Blpapi.Name.GetName("SubscriptionStarted"))) { // set subscribed color foreach (DataGridViewCell cell in dataRow.Cells) { cell.Style.BackColor = Color.LightGreen; } try { // check for error if (msg.HasElement("exceptions")) { // subscription has error Element error = msg.GetElement("exceptions"); int searchIndex = 0; for (int errorIndex = 0; errorIndex < error.NumValues; errorIndex++) { Element errorException = error.GetValueAsElement(errorIndex); string field = errorException.GetElementAsString(FIELD_ID); Element reason = errorException.GetElement(REASON); string message = reason.GetElementAsString(DESCRIPTION); for (; searchIndex < dataGridViewData.ColumnCount - 1; searchIndex++) { if (field == dataGridViewData.Columns[searchIndex].Name) { dataRow.Cells[searchIndex].Value = message; break; } } } } } catch (Exception e) { toolStripStatusLabel1.Text = e.Message; } } else { // check for subscription failure if (msg.MessageType.Equals(Bloomberglp.Blpapi.Name.GetName("SubscriptionFailure"))) { if (msg.HasElement(REASON)) { Element reason = msg.GetElement(REASON); string message = reason.GetElementAsString(DESCRIPTION); dataRow.Cells[1].Value = message; } } } } }
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.AsElement); if (eventObj.Type == Event.EventType.SESSION_STATUS) { if (msg.MessageType.Equals("SessionTerminated")) { done = true; } } } } } }
void initBloomberg() { string serverHost = "localhost"; int serverPort = 8194; SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = serverHost; sessionOptions.ServerPort = serverPort; System.Console.Error.WriteLine("Connecting to " + serverHost + ":" + serverPort); session = new Session(sessionOptions); bool sessionStarted = session.Start(); if (!sessionStarted) { System.Console.Error.WriteLine("Failed to start session."); return; } if (!session.OpenService("//blp/refdata")) { System.Console.Error.WriteLine("Failed to open //blp/refdata"); return; } refDataService = session.GetService("//blp/refdata"); }
public bool Connect(string user = "", string dataType = "//blp/refdata") { if (connected) goto finish; while (!connected) { reconnectAttempts++; string serverHost = "localhost"; int serverPort = 8194; SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = serverHost; sessionOptions.ServerPort = serverPort; Trace.WriteLine("Connecting to Bloomberg " + dataType + ". Attempt " + reconnectAttempts + "/" + maxReconnectAttempts +"."); session = new Session(sessionOptions); bool sessionStarted = session.Start(); try { session.OpenService(dataType); refDataService = session.GetService(dataType); Trace.WriteLine("Connected to Bloomberg"); connected = true; reconnectAttempts = 0; } catch { Trace.WriteLine("Failed to connect. "); connected = false; if (reconnectAttempts >= maxReconnectAttempts) { Trace.WriteLine("Tried to connect to Bloomberg " + reconnectAttempts + " times."); Trace.WriteLine("Exiting"); Environment.Exit(0); } Trace.WriteLine("Waiting for " + reconnectionInterval + "s before retrying to connect."); Thread.Sleep(reconnectionInterval * 1000); } } finish: return connected; }
// Event handler for the session public void processBBEvent(Event eventObject, Session session) { // We are only interested in market data events related to // our subscription if (eventObject.Type == Event.EventType.SUBSCRIPTION_DATA) { // Each event may have multiple messages. So loop // through all of the messages foreach (Message msg in eventObject) { // For Debugging use the display all of the fields: System.Console.WriteLine(msg); // If we have both LAST_TRADE and SIZE_LAST_TRADE elements then // assign the values to the text boxes if (msg.HasElement("LAST_TRADE") && msg.HasElement("SIZE_LAST_TRADE")) { // Obtain the topic of the message string topic = (string)msg.CorrelationID.Object; try { tbPrice.Invoke(new MethodInvoker(delegate { tbPrice.Text = (string)msg.GetElementAsString("LAST_TRADE"); })); tbVolume.Invoke(new MethodInvoker(delegate { tbVolume.Text = (string)msg.GetElementAsString("SIZE_LAST_TRADE"); })); } catch (Exception e) { // Send an error message to console System.Console.WriteLine("Error: " + e.ToString()); } } // end if msg has both last trade and size } // end loop over Messages in the eventObject } // end if event type is subscription data }
public Result startSession() { string retval = ""; bool succ = true; retval += "\nStarting session...\n"; SessionOptions d_sessionOptions = new SessionOptions(); d_sessionOptions.ServerHost = d_host; d_sessionOptions.ServerPort = d_port; session = new Session(d_sessionOptions); if (!session.Start()) { retval += "\nError: failed to start session.\n"; succ = false; } else { retval += "\nSession started!\n"; if (!session.OpenService(d_service)) { session.Stop(); retval += "\nError: failed to open service.\n"; succ = false; } else { service = session.GetService(d_service); retval += "\nService opened!\n"; } } Result result = new Result { retval = retval, success = succ }; return result; }
private void btnStart_Click(object sender, EventArgs e) { bool result; // Create 2 string variables for the security and fields String security = tbSymbol.Text; String fields = "LAST_PRICE"; //Initialize lists used prices = new List<double>(); prices.Add(0); tickTestsResults = new List<double>(); tickTestsResults.Add(0); // Create an instance of the SessionOptions object to hold the session parameters sessionOptions = new SessionOptions(); // Set the session parameters in the SessionOptions object sessionOptions.ServerHost = "localhost"; sessionOptions.ServerPort = 8194; // Create an instance of the Session object, passing the options and processBBEvent to it session = new Session(sessionOptions, new Bloomberglp.Blpapi.EventHandler(processBBEvent)); // Start the Session try { result = session.Start(); //Display successful connection if (result) lblAppStatus.Text = "Connection Successful!"; // Open up the Market data Service result = session.OpenService("//blp/mktdata"); // Create an instance of the new list of subscriptions subscriptions = new List<Subscription>(); // Add a subscription. Create a new CorrelationID on the fly subscriptions.Add(new Subscription(security, fields, "", new Bloomberglp.Blpapi.CorrelationID(security))); // Send out the subscriptions session.Subscribe(subscriptions); } catch (Exception ex) { System.Console.WriteLine("An error has occurred starting the service!"); lblAppStatus.Text = ("An error has occurred starting the service!"); } }
/// <summary> /// Data Event /// </summary> /// <param name="eventObj"></param> /// <param name="session"></param> private void ProcessEvent(Event eventObj, Session session) { //if (InvokeRequired) //{ // try // { // Invoke(new EventHandler(processEvent), new object[] { eventObj, session }); // } // catch (Exception) // { // Console.WriteLine("Invoke failed"); // } //} //else //{ //try //{ switch (eventObj.Type) { case Event.EventType.SUBSCRIPTION_DATA: // process subscription data ProcessRequestDataEvent(eventObj, session); break; case Event.EventType.SUBSCRIPTION_STATUS: // process subscription status ProcessRequestStatusEvent(eventObj, session); break; default: ProcessMiscEvents(eventObj, session); break; } //} //catch (System.Exception e) //{ // //toolStripStatusLabel1.Text = e.Message.ToString(); //} //} }
/// <summary> /// Request status event /// </summary> /// <param name="eventObj"></param> /// <param name="session"></param> private static void ProcessRequestStatusEvent(Event eventObj, Session session) { List<string> dataList = new List<string>(); // process status message foreach (Message msg in eventObj) { var securityObj = (BloombergSecurity)msg.CorrelationID.Object; DataGridViewRow dataRow = securityObj.DataGridRow; if (msg.MessageType.Equals(Bloomberglp.Blpapi.Name.GetName("SubscriptionStarted"))) { // set subscribed color foreach (DataGridViewCell cell in dataRow.Cells) { cell.Style.BackColor = Color.LightGreen; } //try //{ // check for error if (msg.HasElement("exceptions")) { // subscription has error Element error = msg.GetElement("exceptions"); int searchIndex = 0; for (int errorIndex = 0; errorIndex < error.NumValues; errorIndex++) { Element errorException = error.GetValueAsElement(errorIndex); string field = errorException.GetElementAsString(FIELD_ID); Element reason = errorException.GetElement(REASON); string message = reason.GetElementAsString(DESCRIPTION); //for (; searchIndex < dataGridViewData.ColumnCount - 1; searchIndex++) //{ // if (field == dataGridViewData.Columns[searchIndex].Name) // { // dataRow.Cells[searchIndex].Value = message; // break; // } //} } } //} //catch (Exception e) //{ // //toolStripStatusLabel1.Text = e.Message; //} } else { // check for subscription failure if (msg.MessageType.Equals(Bloomberglp.Blpapi.Name.GetName("SubscriptionFailure"))) { if (msg.HasElement(REASON)) { Element reason = msg.GetElement(REASON); string message = reason.GetElementAsString(DESCRIPTION); dataRow.Cells[1].Value = message; } } } } }
public string startSession() { string retval = ""; retval += "\nStarting session...\n"; SessionOptions d_sessionOptions = new SessionOptions(); d_sessionOptions.ServerHost = d_host; d_sessionOptions.ServerPort = d_port; session = new Session(d_sessionOptions); if (!session.Start()) { retval += "\nError: failed to start session.\n"; return retval; } retval += "\nSession started!\n"; if (!session.OpenService(d_service)) { session.Stop(); retval += "\nError: failed to open service.\n"; return retval; } service = session.GetService(d_service); retval += "\nService opened!\n"; return retval; }
// Event handler for the session public void processBBEvent(Event eventObject, Session session) { //Only use the data coming in related to our subscription data if (eventObject.Type == Event.EventType.SUBSCRIPTION_DATA) { //Loop through the messages in the eventObject foreach (Message msg in eventObject) { // Get only the messages that have the last trade price and size of last trade if (msg.HasElement("LAST_TRADE") && msg.HasElement("SIZE_LAST_TRADE")) { // Obtain the topic of the message string topic = (string)msg.CorrelationID.Object; try { //Creates a new thread for getting the price of last trade tbPrice.Invoke(new MethodInvoker(delegate { tbPrice.Text = (string)msg.GetElementAsString("LAST_TRADE"); })); //Creates a new thread for getting volume or size of trade tbVolume.Invoke(new MethodInvoker(delegate { tbVolume.Text = (string)msg.GetElementAsString("SIZE_LAST_TRADE"); })); // end of tvVolume.Invoke() tbVWAP.Invoke(new MethodInvoker(delegate { String VWAP = calculateVWAP(Convert.ToDouble(msg.GetElementAsString("LAST_TRADE")), Convert.ToDouble(msg.GetElementAsString("SIZE_LAST_TRADE"))); tbVWAP.Text = VWAP; chtPrices.Series[1].Points.AddY(Convert.ToDouble(VWAP)); })); // end of tbVWAP.invoke() chtPrices.Invoke(new MethodInvoker(delegate { double lastTradePrice = Convert.ToDouble(msg.GetElementAsString("LAST_TRADE")); double myVolume = Convert.ToDouble(msg.GetElementAsString("SIZE_LAST_TRADE")); if (firstPointY) { //Set the Y axis range to the lastTradePrice-1 to lastTradePrice+1 chtPrices.ChartAreas[0].AxisY.Minimum = lastTradePrice - 1; chtPrices.ChartAreas[0].AxisY.Maximum = lastTradePrice + 1; //It is no longer the first plotted point from here on out firstPointY = false; } //This will change the primary y axis scale if price is smaller than the minimum y axis else if(lastTradePrice < chtPrices.ChartAreas[0].AxisY.Minimum) chtPrices.ChartAreas[0].AxisY.Minimum = lastTradePrice-0.01; //This will change the primary y axis scale if price is smaller than the minimum y axis else if(lastTradePrice > chtPrices.ChartAreas[0].AxisY.Maximum) chtPrices.ChartAreas[0].AxisY.Maximum = lastTradePrice+0.01; // Get previous tickTest and price double prevTick = tickTestsResults[tickTestsResults.Count - 1]; double prevPrice = prices[prices.Count - 1]; // Calculate the new sum of money flow with tickTest() tickTest(lastTradePrice, myVolume, prevPrice, prevTick); // Plot the money flow first to get the previous trade price chtPrices.Series[2].Points.AddY(sumMF); //Add the lastTradePrice to our prices list prices.Add(lastTradePrice); // Plot the last trade price chtPrices.Series[0].Points.AddY(lastTradePrice); })); //end of chtPrices.Invoke() } catch (Exception e) { // Send an error message to console System.Console.WriteLine("Error: " + e.ToString()); } } // end if msg has both last trade and size } // end loop over Messages in the eventObject } // end if event type is subscription data }
private bool OpenSession() { if (_session == null) { //toolStripStatusLabel1.Text = "Connecting..."; // create new session _session = new Session(_sessionOptions, new EventHandler(ProcessEvent)); } return _session.Start(); }
/// <summary> /// Bloomberg data event /// </summary> /// <param name="eventObj"></param> /// <param name="session"></param> private void processEvent(Event eventObj, Session session) { if (InvokeRequired) { Invoke(new EventHandler(processEvent), new object[] { eventObj, session }); } else { try { switch (eventObj.Type) { case Event.EventType.RESPONSE: // process data processRequestDataEvent(eventObj, session); break; case Event.EventType.PARTIAL_RESPONSE: // process partial data processRequestDataEvent(eventObj, session); break; default: // process misc events processMiscEvents(eventObj, session); break; } } catch (System.Exception e) { logger.Info(e.Message.ToString()); } } }
/// <summary> /// Process subscription data /// </summary> /// <param name="eventObj"></param> /// <param name="session"></param> private void processRequestDataEvent(Event eventObj, Session session) { string securityName = string.Empty; // process message foreach (Message msg in eventObj.GetMessages()) { if (msg.MessageType.Equals(Bloomberglp.Blpapi.Name.GetName("ReferenceDataResponse"))) { // process errors if (msg.HasElement(RESPONSE_ERROR)) { Element error = msg.GetElement(RESPONSE_ERROR); Error(String.Format("{0}, {1}", kKospiIndex, error.GetElementAsString(MESSAGE))); } else { Element secDataArray = msg.GetElement(SECURITY_DATA); int numberOfSecurities = secDataArray.NumValues; if (secDataArray.HasElement(SECURITY_ERROR)) { // security error Element secError = secDataArray.GetElement(SECURITY_ERROR); Element security = secDataArray.GetElement(SECURITY); Error(secError.GetElementAsString(MESSAGE)); Error(security.ToString()); } if (secDataArray.HasElement(FIELD_EXCEPTIONS)) { // field error Element error = secDataArray.GetElement(FIELD_EXCEPTIONS); for (int errorIndex = 0; errorIndex < error.NumValues; errorIndex++) { Element errorException = error.GetValueAsElement(errorIndex); string field = errorException.GetElementAsString(FIELD_ID); Element errorInfo = errorException.GetElement(ERROR_INFO); string message = errorInfo.GetElementAsString(MESSAGE); logger.Warn("{0} has field error.", kKospiIndex); } // end for } // end if // process securities for (int index = 0; index < numberOfSecurities; index++) { Element secData = secDataArray.GetValueAsElement(index); Element fieldData = secData.GetElement("fieldData"); if (fieldData.HasElement(kIndexWeight)) { Element weightField = fieldData.GetElement(kIndexWeight); for (int i = 0; i < weightField.NumValues; ++i) { String memberTicker = ""; double weight = 0.0; Element row = weightField.GetValueAsElement(i); if (row.HasElement("Member Ticker and Exchange Code")) { Element item = row.GetElement("Member Ticker and Exchange Code"); memberTicker = item.GetValueAsString(); } else { continue; } if (row.HasElement("Percentage Weight")) { Element item = row.GetElement("Percentage Weight"); weight = item.GetValueAsFloat64(); } else { continue; } _resultDict.Add(memberTicker + " Equity", weight); } // logger.Info(fieldStr); } } // end for } // end else } // end if } // end foreach }
private bool createSession() { if (d_session != null) { d_session.Stop(); } // create synchronous session d_session = new Session(new SessionOptions()); return d_session.Start(); }
private static void ProcessRequestDataEvent(Event eventObj, Session session) { // process message foreach (Message msg in eventObj) { // get correlation id var securityObj = (BloombergSecurity)msg.CorrelationID.Object; // process market data if (msg.MessageType.Equals(Bloomberglp.Blpapi.Name.GetName("MarketDataEvents"))) { // check for initial paint if (msg.HasElement("SES_START")) { if (msg.GetElementAsBool("IS_DELAYED_STREAM")) { securityObj.SetDelayedStream(); } } // process tick data for (int fieldIndex = 1; fieldIndex < securityObj.SecurityFields.Count; fieldIndex++) { string field = securityObj.SecurityFields[fieldIndex].ToUpper(); if (msg.HasElement(field)) { //msg.GetElementAsDatetime(Element.) // check element to see if it has null value if (!msg.GetElement(field).IsNull) { string value = msg.GetElementAsString(field); securityObj.Setfield(securityObj.SecurityFields[fieldIndex], value); } } } // allow application to update UI Application.DoEvents(); } } }
/// <summary> /// Request status event /// </summary> /// <param name="eventObj"></param> /// <param name="session"></param> private void processMiscEvents(Event eventObj, Session session) { foreach (Message msg in eventObj.GetMessages()) { switch (msg.MessageType.ToString()) { case "SessionStarted": // "Session Started" break; case "SessionTerminated": case "SessionStopped": // "Session Terminated" break; case "ServiceOpened": // "Reference Service Opened" break; 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)); logger.Info(message); break; default: logger.Info(msg.MessageType.ToString()); break; } } }
/// <summary> /// Process subscription data /// </summary> /// <param name="eventObj"></param> /// <param name="session"></param> private void processRequestDataEvent(Event eventObj, Session session) { string securityName = string.Empty; Boolean hasFieldError = false; // clear column tag of field error message. foreach (DataGridViewColumn col in dataGridViewData.Columns) { col.Tag = null; } // process message foreach (Message msg in eventObj.GetMessages()) { if (msg.MessageType.Equals(Bloomberglp.Blpapi.Name.GetName("HistoricalDataResponse"))) { // process errors if (msg.HasElement(RESPONSE_ERROR)) { Element error = msg.GetElement(RESPONSE_ERROR); Error(error.GetElementAsString(MESSAGE)); } else { Element secDataArray = msg.GetElement(SECURITY_DATA); int numberOfSecurities = secDataArray.NumValues; if (secDataArray.HasElement(SECURITY_ERROR)) { // security error Element secError = secDataArray.GetElement(SECURITY_ERROR); Element security = secDataArray.GetElement(SECURITY); Error(secError.GetElementAsString(MESSAGE)); Error(security.ToString()); } if (secDataArray.HasElement(FIELD_EXCEPTIONS)) { // field error Element error = secDataArray.GetElement(FIELD_EXCEPTIONS); for (int errorIndex = 0; errorIndex < error.NumValues; errorIndex++) { Element errorException = error.GetValueAsElement(errorIndex); string field = errorException.GetElementAsString(FIELD_ID); Element errorInfo = errorException.GetElement(ERROR_INFO); string message = errorInfo.GetElementAsString(MESSAGE); dataGridViewData.Columns[field].Tag = message; hasFieldError = true; } // end for } // end if // process securities for (int index = 0; index < numberOfSecurities; index++) { foreach (Element secData in secDataArray.Elements) { switch (secData.Name.ToString()) { case "eidsData": // process security eid data here break; case "security": // security name securityName = secData.GetValueAsString(); break; case "fieldData": if (hasFieldError && secData.NumValues == 0) { // no data but have field error object[] dataValues = new object[dataGridViewData.ColumnCount]; dataValues[0] = securityName; int fieldIndex = 0; foreach (DataGridViewColumn col in dataGridViewData.Columns) { if (col.Tag != null) { dataValues[fieldIndex] = col.Tag.ToString(); } fieldIndex++; } d_data.Rows.Add(dataValues); } else { // get field data d_data.BeginLoadData(); for (int pointIndex = 0; pointIndex < secData.NumValues; pointIndex++) { int fieldIndex = 0; object[] dataValues = new object[dataGridViewData.ColumnCount]; Element fields = secData.GetValueAsElement(pointIndex); foreach (DataGridViewColumn col in dataGridViewData.Columns) { try { if (col.Name == "security") dataValues[fieldIndex] = securityName; else { if (fields.HasElement(col.Name)) { Element item = fields.GetElement(col.Name); if (item.IsArray) { // bulk field data dataValues[fieldIndex] = "Bulk Data"; } else { // field data dataValues[fieldIndex] = item.GetValueAsString(); } } else { // no field value if (col.Tag.ToString().Length > 0) { // field has error dataValues[fieldIndex] = col.Tag.ToString(); } else dataValues[fieldIndex] = DBNull.Value; } } // end if } catch (Exception ex) { // display error dataValues[fieldIndex] = ex.Message; } finally { fieldIndex++; } } // end foreach // add data to data table d_data.Rows.Add(dataValues); } // end for d_data.EndLoadData(); } break; } // end switch } // end foreach } // end for } // end else } // end if } // end foreach }
/// <summary> /// Create session /// </summary> /// <returns></returns> private bool createSession() { if (d_session != null) d_session.Stop(); Write("Connecting..."); // create synchronous session d_session = new Session(new SessionOptions()); return d_session.Start(); }
private void btnStart_Click(object sender, EventArgs e) { bool result; // Define two string constants for the security and the fields // to be read. String security = "IBM US Equity"; String fields = "LAST_PRICE"; // Instantiate the SessionOptions object to hold the session parameters // Note that this was defined at the Form level scope. sessionOptions = new SessionOptions(); // Since this program will run on the same PC as the Bloomberg software, // we use “localhost” as the host name and port 8194 as the default port. sessionOptions.ServerHost = "localhost"; sessionOptions.ServerPort = 8194; // Instantiate the Session object using the sessionOptions and // a reference to the event handler named processBBEvent session = new Session(sessionOptions, new Bloomberglp.Blpapi.EventHandler(processBBEvent)); // Start the Session result = session.Start(); // Open up the Market data Service result = session.OpenService("//blp/mktdata"); // Instantiate the new list of subscriptions subscriptions = new List<Subscription>(); // Get the symbol from tbSymbol text box security = tbSymbol.Text; // Add a subscription. Create a new CorrelationID on the fly subscriptions.Add(new Subscription(security, fields, "", new Bloomberglp.Blpapi.CorrelationID(security))); // Kick off the subscriptions session.Subscribe(subscriptions); }