Exemplo n.º 1
0
        /// <summary>
        /// Initialises the specified URI session and opens the service.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns></returns>
        private bool Initialise(string uri, int requestCount)
        {
            sessionOptions            = new BB.SessionOptions();
            sessionOptions.ServerHost = "localhost";
            sessionOptions.ServerPort = 8194;
            if (requestCount > sessionOptions.MaxPendingRequests)
            {
                sessionOptions.MaxPendingRequests = requestCount;
            }

            UpdateStatus("Starting the Bloomberg session.");
            session = new BB.Session(sessionOptions, new BB.EventHandler(processEvent));

            if (session.Start())
            {
                if (!session.OpenService(uri))
                {
                    throw new Exception("Bloomberg failed to open session " + uri);
                }
                return(true);
            }
            else
            {
                throw new Exception("An error occurred starting the Bloomberg session. Ensure Bloomberg is installed.");
            }
        }
Exemplo n.º 2
0
    /*****************************************************************************
    *  Function    : processSubscriptionStatus
    *  Description : Processes subscription status messages returned from Bloomberg
    *  Arguments   : Event, Session
    *  Returns     : void
    *****************************************************************************/
    private void processSubscriptionStatus(Event eventObj, Session session)
    {
        System.Console.WriteLine("Processing SUBSCRIPTION_STATUS");
        foreach (Message msg in eventObj)
        {
            string topic = (string)msg.CorrelationID.Object;
            System.Console.WriteLine(System.DateTime.Now.ToString("s") +
                                     ": " + topic + " - " + msg.MessageType);

            if (msg.HasElement(REASON))
            {
                // This occurs if a bad security is subscribed to
                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 an
                // invalid field is passed in
                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("");
        }
    }
Exemplo n.º 3
0
        /// <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;
                            }
                        }
                    }
                }
            }
        }
    /*****************************************************************************
    *  Function    : createSession
    *  Description : This function creates a session object and opens the market
    *               bar service.  Returns false on failure of either.
    *  Arguments   : none
    *  Returns     : bool
    *****************************************************************************/
    private bool createSession()
    {
        if (d_session != null)
        {
            d_session.Stop();
        }

        System.Console.WriteLine("Connecting to " + d_sessionOptions.ServerHost +
                                 ":" + d_sessionOptions.ServerPort);
        d_session = new Session(d_sessionOptions, new EventHandler(processEvent));
        if (!d_session.Start())
        {
            System.Console.WriteLine("Failed to start session");
            return(false);
        }
        System.Console.WriteLine("Connected successfully\n");

        if (!d_session.OpenService("//blp/mktbar"))
        {
            System.Console.WriteLine("Failed to open service //blp/mktbar");
            d_session.Stop();
            return(false);
        }

        System.Console.WriteLine("Subscribing...");
        d_session.Subscribe(d_subscriptions);

        return(true);
    }
Exemplo n.º 5
0
 /// <summary>
 /// Initializes the SecurityLookup instance by creating a session and authorizing it so that its
 /// ready to conduct searches. Once initialized multiple searches may be conducted with the same instance.
 /// </summary>
 public void Init()
 {
     try
     {
         SessionOptions sessionOptions = new SessionOptions();
         sessionOptions.ServerHost            = d_host;
         sessionOptions.ServerPort            = d_port;
         sessionOptions.AuthenticationOptions = d_authOptions;
         Console.WriteLine("Connecting to {0}:{1}", d_host, d_port);
         session = new Session(sessionOptions);
         if (!session.Start())
         {
             throw new Exception("Failed to start session");
         }
         identity = null;
         if (d_authOptions != null)
         {
             Authorize(out identity, session);
         }
         if (!session.OpenService(INSTRUMENT_SERVICE))
         {
             throw new Exception(
                       string.Format("Failed to open: {0}", INSTRUMENT_SERVICE));
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(string.Format("Exception: {0}", e.Message));
         Console.WriteLine();
     }
 }
Exemplo n.º 6
0
 /*****************************************************************************
 *  Function    : processMiscEvents
 *  Description : Processes any message returned from Bloomberg
 *  Arguments   : Event, Session
 *  Returns     : void
 *****************************************************************************/
 private void processMiscEvents(Event eventObj, Session session)
 {
     System.Console.WriteLine("Processing " + eventObj.Type);
     foreach (Message msg in eventObj)
     {
         System.Console.WriteLine(System.DateTime.Now.ToString("s") +
                                  ": " + msg.MessageType + "\n");
     }
 }
Exemplo n.º 7
0
    /*****************************************************************************
    *  Function    : processSubscriptionDataEvent
    *  Description : Processes all field data returned from Bloomberg
    *  Arguments   : Event, Session
    *  Returns     : void
    *****************************************************************************/
    private void processSubscriptionDataEvent(Event eventObj, Session session)
    {
        System.Console.WriteLine("Processing SUBSCRIPTION_DATA");
        foreach (Message msg in eventObj)
        {
            string topic = (string)msg.CorrelationID.Object;
            System.Console.WriteLine(System.DateTime.Now.ToString("s")
                                     + ": " + topic + " - " + msg.MessageType);

            CheckAspectFields(msg);
        }
    }
Exemplo n.º 8
0
 public void initializeSession()
 {
     this.session = new BbergAPI.Session(this.sessionOptions);
     if (!this.session.Start())
     {
         System.Console.WriteLine("Could not start session.");
         System.Environment.Exit(1);
     }
     if (!this.session.OpenService("//blp/refdata"))
     {
         System.Console.WriteLine("Could not open service " + "//blp/refdata");
         System.Environment.Exit(1);
     }
 }
Exemplo n.º 9
0
 /// <summary>
 /// Dispose of the API connection.
 /// </summary>
 public void Dispose()
 {
     if (session != null)
     {
         try
         {
             session.Stop();
         }
         catch { }
         finally
         {
             session = null;
         }
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// Send a request to the BLP API. Called by Query().
        /// </summary>
        /// <param name="session"></param>
        /// <param name="identity"></param>
        private void SendRequest(Session session, Identity identity)
        {
            Console.WriteLine("Sending Request: {0}", d_requestType.ToString());
            Service instrumentService = session.GetService(INSTRUMENT_SERVICE);
            Request request;

            try
            {
                request = instrumentService.CreateRequest(d_requestType.ToString());
            }
            catch (NotFoundException e)
            {
                throw new Exception(
                          string.Format("Request Type not found: {0}", d_requestType),
                          e);
            }
            request.Set(QUERY_ELEMENT, d_queryString);
            request.Set(MAX_RESULTS_ELEMENT, d_maxResults);

            foreach (KeyValuePair <string, string> entry in d_filters)
            {
                try
                {
                    request.Set(entry.Key, entry.Value);
                }
                catch (NotFoundException e)
                {
                    throw new Exception(string.Format("Filter not found: {0}", entry.Key), e);
                }
                catch (InvalidConversionException e)
                {
                    throw new Exception(
                              string.Format(
                                  "Invalid value: {0} for filter: {1}",
                                  entry.Value,
                                  entry.Key),
                              e);
                }
            }
            request.Print(Console.Out);
            Console.WriteLine();
            session.SendRequest(request, identity, null);
        }
Exemplo n.º 11
0
        /// <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);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Sets config and other session data to create the session
        /// </summary>
        /// <returns></returns>
        private Session CreateBloombergSession()
        {
            // retrieves the appsettings and fills the config object
            config = new BloombergApiSessionConfig();

            var sessionOptions = new SessionOptions { ServerHost = config.BbHost, ServerPort = config.BbPort };
            var session = new Session(sessionOptions);

            if (!session.Start())
            {
                //_Logging.Error("Unable to initiate Bloomberg session.");
                return null;
            }

            if (!session.OpenService(config.BbService))
            {
                //_Logging.Error("Unable to open Bloomberg service.");
                return null;
            }
            return session;
        }
Exemplo n.º 13
0
    /*****************************************************************************
    *  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());
        }
    }
Exemplo n.º 14
0
        public void Connect()
        {
            string serverHost = "api.bloomberg.com";
            int    serverPort = 0;

            SessionOptions sessionOptions = new SessionOptions();

            sessionOptions.ServerHost = serverHost;
            sessionOptions.ServerPort = serverPort;

            Log("Connecting to " + serverHost + ":" + serverPort);
            session = new Session(sessionOptions);
            bool sessionStarted = session.Start();

            if (!sessionStarted)
            {
                throw new Exception("Failed to start Bloomberg API session.");
            }
            if (!session.OpenService("//blp/refdata"))
            {
                throw new Exception("Failed to open //blp/refdata");
            }
            this.service = session.GetService("//blp/refdata");
        }
Exemplo n.º 15
0
        /// <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");
        }
Exemplo n.º 16
0
    /*****************************************************************************
    *  Function    : createSession
    *  Description : This function creates a session object and opens the market
    *               bar service.  Returns false on failure.
    *  Arguments   : none
    *  Returns     : bool
    *****************************************************************************/
    private bool createSession()
    {
        if (d_session != null)
        {
            d_session.Stop();
        }

        string authOptions = string.Empty;

        d_sessionOptions = new SessionOptions();

        if (d_authOption == "APPLICATION")
        {
            // Set Application Authentication Option
            authOptions  = "AuthenticationMode=APPLICATION_ONLY;";
            authOptions += "ApplicationAuthenticationType=APPNAME_AND_KEY;";
            // ApplicationName is the entry in EMRS.
            authOptions += "ApplicationName=" + d_name;
        }
        else if (d_authOption == "USER_APP")
        {
            // Set User and Application Authentication Option
            authOptions  = "AuthenticationMode=USER_AND_APPLICATION;";
            authOptions += "AuthenticationType=OS_LOGON;";
            authOptions += "ApplicationAuthenticationType=APPNAME_AND_KEY;";
            // ApplicationName is the entry in EMRS.
            authOptions += "ApplicationName=" + d_name;
        }
        else if (d_authOption == "USER_DS_APP")
        {
            // Set User and Application Authentication Option
            authOptions  = "AuthenticationMode=USER_AND_APPLICATION;";
            authOptions += "AuthenticationType=DIRECTORY_SERVICE;";
            authOptions += "DirSvcPropertyName=" + d_dsName + ";";
            authOptions += "ApplicationAuthenticationType=APPNAME_AND_KEY;";
            // ApplicationName is the entry in EMRS.
            authOptions += "ApplicationName=" + d_name;
        }
        else if (d_authOption == "DIRSVC")
        {
            // Authenticate user using active directory service property
            authOptions  = "AuthenticationType=DIRECTORY_SERVICE;";
            authOptions += "DirSvcPropertyName=" + d_dsName;
        }
        else
        {
            // Authenticate user using windows/unix login name (default)
            authOptions = "AuthenticationType=OS_LOGON";
        }

        System.Console.WriteLine("Authentication Options = " + authOptions);
        d_sessionOptions.AuthenticationOptions = authOptions;

        SessionOptions.ServerAddress[] servers = new SessionOptions.ServerAddress[d_hosts.Count];
        int index = 0;

        System.Console.WriteLine("Connecting to port " + d_port.ToString() + " on host(s):");
        foreach (string host in d_hosts)
        {
            servers[index] = new SessionOptions.ServerAddress(host, d_port);
            System.Console.WriteLine(host);
            index++;
        }

        // auto restart on disconnect
        d_sessionOptions.ServerAddresses            = servers;
        d_sessionOptions.AutoRestartOnDisconnection = true;
        d_sessionOptions.NumStartAttempts           = d_hosts.Count;
        // change default subscription service
        d_sessionOptions.DefaultSubscriptionService = MKTBAR_SVC;

        // create session and start
        d_session = new Session(d_sessionOptions, processEvent);
        return(d_session.Start());
    }
Exemplo n.º 17
0
        /// <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;
                }
            }
        }
Exemplo n.º 18
0
        /// <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();
                }
            }
        }