Example #1
0
        private static List<string> _fields = new string[] { "BID", "ASK"/*, "ZBID"*/ }.ToList(); //the code treats a field that starts with a "Z" as a bad field

        #endregion Fields

        #region Methods

        public static void RunExample()
        {
            SessionOptions sessionOptions = new SessionOptions();
            sessionOptions.ServerHost = "localhost";
            sessionOptions.ServerPort = 8194;

            Session session = new Session(sessionOptions, new EventHandler(MarketDataRequest.ProcessEvent));
            session.StartAsync();
        }
        public static void RunExample()
        {
            SessionOptions soptions = new SessionOptions();
            soptions.ServerHost = "127.0.0.1";
            soptions.ServerPort = 8194;

            Session session = new Session(soptions);
            if (session.Start() && session.OpenService("//blp/refdata"))
            {
                Service service = session.GetService("//blp/refdata");
                Request request = service.CreateRequest("IntradayBarRequest");

                string security = "SPY US EQUITY";
                //security = "ZYZZ US EQUITY";  //the code treats securities that start with a "Z" as non-existent
                request.Set("security", security); //required

                request.Set("eventType", "TRADE"); //optional: TRADE(default), BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK, BID_YIELD, ASK_YIELD, MID_PRICE, AT_TRADE, SETTLE
                request.Set("eventType", "BID"); //A request can have multiple eventTypes
                //Note 1) BID_YIELD, ASK_YIELD, MID_PRICE, AT_TRADE, and SETTLE don't appear in the API documentation, but you will see them if you call "service.ToString()" using the actual Bloomberg API
                //Note 2) If you request an eventType that isn't supported, the API will throw a KeyNotSupportedException at the "request.Set("eventType", "XXX")" line
                //Note 3) eventType values are case-sensitive.  Requesting "bid" instead of "BID" will throw a KeyNotSupportedException at the "request.Set("eventType", "bid")" line

                //data goes back no farther than 140 days (7.2.4)
                DateTime dtStart = DateTime.Today.AddDays(-1); //yesterday
                request.Set("startDateTime", new Datetime(dtStart.AddHours(9.5).ToUniversalTime())); //Required Datetime, UTC time
                request.Set("endDateTime", new Datetime(dtStart.AddHours(16).ToUniversalTime())); //Required Datetime, UTC time

                //(Required) Sets the length of each time bar in the response. Entered as a whole number, between 1 and 1440 in minutes.
                //  One minute is the lowest possible granularity. (despite A.2.8, the interval setting cannot be omitted)
                request.Set("interval", 60);

                //When set to true, a bar contains the previous bar values if there was no tick during this time interval.
                request.Set("gapFillInitialBar", false); //Optional bool. Valid values are true and false (default = false)

                //Option on whether to return EIDs for the security.
                request.Set("returnEids", false); //Optional bool. Valid values are true and false (default = false)

                ////Setting this to true will populate fieldData with an extra element containing a name and value for the relative date. For example RELATIVE_DATE = 2002 Q2
                //request.Set("returnRelativeDate", false); //Optional bool. Valid values are true and false (default = false)

                //Adjust historical pricing to reflect: Regular Cash, Interim, 1st Interim, 2nd Interim, 3rd Interim, 4th Interim, 5th Interim, Income,
                //  Estimated, Partnership Distribution, Final, Interest on Capital, Distribution, Prorated.
                request.Set("adjustmentNormal", false); //Optional bool. Valid values are true and false (default = false)

                //Adjust historical pricing to reflect: Special Cash, Liquidation, Capital Gains, Long-Term Capital Gains, Short-Term Capital Gains, Memorial,
                //  Return of Capital, Rights Redemption, Miscellaneous, Return Premium, Preferred Rights Redemption, Proceeds/Rights, Proceeds/Shares, Proceeds/Warrants.
                request.Set("adjustmentAbnormal", false); //Optional bool. Valid values are true and false (default = false)

                //Adjust historical pricing and/or volume to reflect: Spin-Offs, Stock Splits/Consolidations, Stock Dividend/Bonus, Rights Offerings/Entitlement.
                request.Set("adjustmentSplit", false); //Optional bool. Valid values are true and false (default = false)

                //Setting to true will follow the DPDF<GO> BLOOMBERG PROFESSIONAL service function. True is the default setting for this option..
                request.Set("adjustmentFollowDPDF", false); //Optional bool. Valid values are true and false (default = false)

                session.SendRequest(request, new CorrelationID(-999));

                bool continueLoop = true;
                while (continueLoop)
                {
                    Event evt = session.NextEvent();
                    switch (evt.Type)
                    {
                        case Event.EventType.RESPONSE:
                            ProcessResponse(evt, security);
                            continueLoop = false;
                            break;
                        case Event.EventType.PARTIAL_RESPONSE:
                            ProcessResponse(evt, security);
                            break;
                    }
                }

            }
        }
Example #3
0
        private static void ProcessEvent(Event evt, Session session)
        {
            switch (evt.Type)
            {
                case Event.EventType.SESSION_STATUS: //use this to open the service
                    foreach (Message message in evt.GetMessages())
                    {
                        if (message.MessageType.Equals("SessionStarted"))
                        {
                            try
                            {
                                session.OpenServiceAsync("//blp/mktdata", new CorrelationID(-9999));
                            }
                            catch (Exception)
                            {
                                System.Console.Error.WriteLine("Could not open //blp/mktdata for async");
                            }
                        }
                    }
                    break;

                case Event.EventType.SERVICE_STATUS: //use this to subscribe to ticker feeds
                    List<Subscription> slist = new List<Subscription>();

                    //Conflate the data to show every two seconds.
                    //  Please note that the Bloomberg API Emulator code does not treat this exactly correct: individual subscriptions should each have their own interval setting.
                    //  I have not coded that in the emulator.
                    List<string> options = new string[] { "interval=2" }.ToList(); //2 seconds.  //Comment this line to receive a subscription data event whenever it happens in the market.

                    //slist.Add(new Subscription("ZYZZ US EQUITY", MarketDataRequest._fields, options)); //the code treats securities that start with a "Z" as non-existent
                    slist.Add(new Subscription("SPY US EQUITY", MarketDataRequest._fields, options));
                    slist.Add(new Subscription("AAPL 150117C00600000 EQUITY", MarketDataRequest._fields, options));

                    session.Subscribe(slist);
                    break;

                case Event.EventType.SUBSCRIPTION_DATA:
                case Event.EventType.RESPONSE:
                case Event.EventType.PARTIAL_RESPONSE:
                    MarketDataRequest.ProcessEvent(evt);
                    break;

                case Event.EventType.SUBSCRIPTION_STATUS:
                    foreach (var msg in evt.GetMessages())
                    {
                        bool fieldExceptionsExist = msg.HasElement("exceptions", true);
                        if (fieldExceptionsExist)
                        {
                            Element elmExceptions = msg["exceptions"];
                            for (int i = 0; i < elmExceptions.NumValues; i++)
                            {
                                Element elmException = elmExceptions.GetValueAsElement(i);
                                string fieldId = elmException.GetElementAsString("fieldId");

                                Element elmReason = elmException["reason"];
                                string source = elmReason.GetElementAsString("source");
                                int errorCode = elmReason.GetElementAsInt32("errorCode");
                                string category = elmReason.GetElementAsString("category");
                                string description = elmReason.GetElementAsString("description");

                                Console.WriteLine("field error: ");
                                Console.WriteLine(string.Format("\tfieldId = {0}", fieldId));
                                Console.WriteLine(string.Format("\tsource = {0}", source));
                                Console.WriteLine(string.Format("\terrorCode = {0}", errorCode));
                                Console.WriteLine(string.Format("\tcategory = {0}", category));
                                Console.WriteLine(string.Format("\tdescription = {0}", description));
                            }
                        }

                    }
                    break;
            }
        }
        /// <summary>
        /// This example Bloomberg request starts a session meant for Reference Requests and requests a few fields for several securities.
        /// I pulled this example code almost line-for-line from section C.1 of the Bloomberg API Developer's Guide
        /// </summary>
        public static void RunExample()
        {
            SessionOptions sessionOptions = new SessionOptions();
            sessionOptions.ServerHost = "localhost";
            sessionOptions.ServerPort = 8194;

            Session session = new Session(sessionOptions);
            if (!session.Start())
            {
                System.Console.WriteLine("Could not start session.");
                System.Environment.Exit(1);
            }
            if (!session.OpenService("//blp/refdata"))
            {
                System.Console.WriteLine("Could not open service //blp/refdata");
                System.Environment.Exit(1);
            }
            CorrelationID requestID = new CorrelationID(1);
            Service refDataSvc = session.GetService("//blp/refdata");
            Request request = refDataSvc.CreateRequest("ReferenceDataRequest");

            //request information for the following securities
            request.Append("securities", "SPY US EQUITY");
            //request.Append("securities", "ZYZZ US EQUITY"); //the code treats securities that start with a "Z" as non-existent
            request.Append("securities", "MSFT US EQUITY");
            request.Append("securities", "AAPL 150117C00600000 EQUITY"); //this is a stock option: TICKER yyMMdd[C/P]\d{8} EQUITY

            //include the following simple fields in the result
            //request.Append("fields", "ZPX_LAST"); //the code treats a field that starts with a "Z" as a bad field
            request.Append("fields", "PX_LAST");
            request.Append("fields", "BID");
            request.Append("fields", "ASK");
            request.Append("fields", "TICKER");
            request.Append("fields", "OPT_EXPIRE_DT");

            //request a field that can be overriden and returns bulk data
            request.Append("fields", "CHAIN_TICKERS");
            Element overrides = request["overrides"];

            //request only puts
            Element ovrdPutCall = overrides.AppendElement();
            ovrdPutCall.SetElement("fieldId", "CHAIN_PUT_CALL_TYPE_OVRD");
            ovrdPutCall.SetElement("value", "P"); //accepts either "C" for calls or "P" for puts

            //request 5 options in the result
            Element ovrdNumStrikes = overrides.AppendElement();
            ovrdNumStrikes.SetElement("fieldId", "CHAIN_POINTS_OVRD");
            ovrdNumStrikes.SetElement("value", 5); //accepts a positive integer

            //request options that expire on Dec. 20, 2014
            Element ovrdDtExps = overrides.AppendElement();
            ovrdDtExps.SetElement("fieldId", "CHAIN_EXP_DT_OVRD");
            ovrdDtExps.SetElement("value", "20141220"); //accepts dates in the format yyyyMMdd

            session.SendRequest(request, requestID);

            bool continueToLoop = true;
            while (continueToLoop)
            {
                Event eventObj = session.NextEvent();
                switch (eventObj.Type)
                {
                    case Event.EventType.RESPONSE: // final event
                        continueToLoop = false;
                        handleResponseEvent(eventObj);
                        break;
                    case Event.EventType.PARTIAL_RESPONSE:
                        handleResponseEvent(eventObj);
                        break;
                    default:
                        handleOtherEvent(eventObj);
                        break;
                }
            }
        }
        /// <summary>
        /// This example Bloomberg request starts a session meant for Reference Requests and requests a few fields for several securities.
        /// I pulled this example code almost line-for-line from section C.1 of the Bloomberg API Developer's Guide
        /// </summary>
        public static void RunExample()
        {
            SessionOptions sessionOptions = new SessionOptions();
            sessionOptions.ServerHost = "127.0.0.1";
            sessionOptions.ServerPort = 8194;

            Session session = new Session(sessionOptions);
            session.Start();
            session.OpenService("//blp/refdata");

            Service refDataService = session.GetService("//blp/refdata");
            Request request = refDataService.CreateRequest("IntradayTickRequest");

            string security = "SPY US Equity";
            //security = "ZYZZ US EQUITY";  //the code treats securities that start with a "Z" as non-existent
            request.Set("security", security);

            request.Append("eventTypes", "TRADE"); //One of TRADE (default), BID, ASK, BID_BEST, ASK_BEST, MID_PRICE, AT_TRADE, BEST_BID, BEST_ASK (see documentation A.2.6 for explanations)
            request.Append("eventTypes", "BID"); //A request can have multiple eventTypes
            //Note 1) refDataService.ToString() using the Bloomberg API indicates an additional eventType called "SETTLE".  "SETTLE" doesn't seem to produce any results.
            //Note 2) If you request an eventType that isn't supported, the API will throw a KeyNotSupportedException at the "request.Append("eventType", "XXX")" line
            //Note 3) eventType values are case-sensitive.  Requesting "bid" instead of "BID" will throw a KeyNotSupportedException at the "request.Append("eventType", "bid")" line

            request.Set("startDateTime", new Datetime(DateTime.Today.AddHours(9.5999).ToUniversalTime()));
            request.Set("endDateTime", new Datetime(DateTime.Today.AddHours(9.6).ToUniversalTime())); //goes back at most 140 days (documentation section 7.2.3)

            //A comma delimited list of exchange condition codes associated with the event. Review QR<GO> for more information on each code returned.
            request.Set("includeConditionCodes", false); //Optional bool. Valid values are true and false (default = false)

            //Returns all ticks, including those with condition codes.
            request.Set("includeNonPlottableEvents", false); //Optional bool. Valid values are true and false (default = false)

            //The exchange code where this tick originated. Review QR<GO> for more information.
            request.Set("includeExchangeCodes", false); //Optional bool. Valid values are true and false (default = false)

            //Option on whether to return EIDs for the security.
            request.Set("returnEids", false); //Optional bool. Valid values are true and false (default = false)

            //The broker code for Canadian, Finnish, Mexican, Philippine, and Swedish equities only.
            //  The Market Maker Lookup screen, MMTK<GO>, displays further information on market makers and their corresponding codes.
            request.Set("includeBrokerCodes", false); //Optional bool. Valid values are true and false (default = false)

            //The Reporting Party Side. The following values appear:
            //  -B: A customer transaction where the dealer purchases securities from the customer.
            //  -S: A customer transaction where the dealer sells securities to the customer.
            //  -D: An inter-dealer transaction (always from the sell side).
            request.Set("includeRpsCodes", false); //Optional bool. Valid values are true and false (default = false)

            //The BIC, or Bank Identifier Code, as a 4-character unique identifier for each bank that executed and reported the OTC trade, as required by MiFID.
            //  BICs are assigned and maintained by SWIFT (Society for Worldwide Interbank Financial Telecommunication).
            //  The MIC is the Market Identifier Code, and this indicates the venue on which the trade was executed.
            request.Set("includeBicMicCodes", false); //Optional bool. Valid values are true and false (default = false)

            {
                //refDataService.ToString() using the Bloomberg API specifies several boolean overrides that the API documentation doesn't (doc version 2.40).  These are:
                //   forcedDelay, includeSpreadPrice, includeYield, includeActionCodes, includeIndicatorCodes, includeTradeTime, and includeUpfrontPrice
                //These overrides are optional.  Their meanings may be obvious given their names, but I can't be sure.

                request.Set("forcedDelay", false); //Optional bool. Undocumented. default = ???
                request.Set("includeSpreadPrice", false); //Optional bool. Undocumented. default = ???
                request.Set("includeYield", false); //Optional bool. Undocumented. default = ???
                request.Set("includeActionCodes", false); //Optional bool. Undocumented. default = ???
                request.Set("includeIndicatorCodes", false); //Optional bool. Undocumented. default = ???
                request.Set("includeTradeTime", false); //Optional bool. Undocumented. default = ???
                request.Set("includeUpfrontPrice", true); //Optional bool. Undocumented. default = ???
            }

            CorrelationID corr = new CorrelationID(17);

            session.SendRequest(request, corr);

            bool continueToLoop = true;
            while (continueToLoop)
            {
                Event evt = session.NextEvent();

                switch (evt.Type)
                {
                    case Event.EventType.RESPONSE:
                        IntradayTickDataRequest.ProcessResponse(evt, security);
                        continueToLoop = false;
                        break;
                    case Event.EventType.PARTIAL_RESPONSE:
                        IntradayTickDataRequest.ProcessResponse(evt, security);
                        break;
                }
            }
        }
        public static void RunExample()
        {
            SessionOptions sessionOptions = new SessionOptions();
            sessionOptions.ServerHost = "127.0.0.1";
            sessionOptions.ServerPort = 8194;

            Session session = new Session(sessionOptions);
            session.Start();
            session.OpenService("//blp/refdata");

            Service service = session.GetService("//blp/refdata");

            Request request = service.CreateRequest("HistoricalDataRequest");

            //request information for the following securities
            request.Append("securities", "MSFT US EQUITY");
            //request.Append("securities", "ZYZZ US EQUITY"); //the code treats securities that start with a "Z" as non-existent
            request.Append("securities", "C A COMDTY");
            request.Append("securities", "AAPL 150117C00600000 EQUITY"); //this is a stock option: TICKER yyMMdd[C/P]\d{8} EQUITY

            //include the following simple fields in the result
            //request.Append("fields", "ZBID"); //the code treats a field that starts with a "Z" as a bad field
            request.Append("fields", "BID");
            request.Append("fields", "ASK");

            //Historical requests allow a few overrides.  See the developer's guide A.2.4 for more information.

            request.Set("startDate", DateTime.Today.AddMonths(-1).ToString("yyyyMMdd")); //Request that the information start three months ago from today.  This override is required.
            request.Set("endDate", DateTime.Today.AddDays(10).ToString("yyyyMMdd")); //Request that the information end three days before today.  This is an optional override.  The default is today.

            //Determine the frequency and calendar type of the output. To be used in conjunction with Period Selection.
            request.Set("periodicityAdjustment", "CALENDAR"); //Optional string.  Valid values are ACTUAL (default), CALENDAR, and FISCAL.

            //Determine the frequency of the output. To be used in conjunction with Period Adjustment.
            request.Set("periodicitySelection", "DAILY"); //Optional string.  Valid values are DAILY (default), WEEKLY, MONTHLY, QUARTERLY, SEMI_ANNUALLY, and YEARLY

            //Sets quote to Price or Yield for a debt instrument whose default value is quoted in yield (depending on pricing source).
            request.Set("pricingOption", "PRICING_OPTION_PRICE"); //Optional string.  Valid values are PRICING_OPTION_PRICE (default) and PRICING_OPTION_YIELD

            //Adjust for "change on day"
            request.Set("adjustmentNormal", true); //Optional bool. Valid values are true and false (default = false)

            //Adjusts for Anormal Cash Dividends
            request.Set("adjustmentAbnormal", false); //Optional bool. Valid values are true and false (default = false)

            //Capital Changes Defaults
            request.Set("adjustmentSplit", true); //Optional bool. Valid values are true and false (default = false)

            //The maximum number of data points to return, starting from the startDate
            //request.Set("maxDataPoints", 5); //Optional integer.  Valid values are positive integers.  The default is unspecified in which case the response will have all data points between startDate and endDate

            //Indicates whether to use the average or the closing price in quote calculation.
            request.Set("overrideOption", "OVERRIDE_OPTION_CLOSE"); //Optional string.  Valid values are OVERRIDE_OPTION_GPA for an average and OVERRIDE_OPTION_CLOSE (default) for the closing price

            CorrelationID requestID = new CorrelationID(1);
            session.SendRequest(request, requestID);

            bool continueToLoop = true;
            while (continueToLoop)
            {
                Event eventObj = session.NextEvent();
                switch (eventObj.Type)
                {
                    case Event.EventType.RESPONSE: // final event
                        continueToLoop = false;
                        handleResponseEvent(eventObj);
                        break;
                    case Event.EventType.PARTIAL_RESPONSE:
                        handleResponseEvent(eventObj);
                        break;
                    default:
                        handleOtherEvent(eventObj);
                        break;
                }
            }
        }