示例#1
0
文件: XL_RTD.cs 项目: uaqeel/ZeusXL
        public static object GetMarket(string Contract, string TickType)
        {
            try
            {
                // Check to make sure it's a valid tick type...
                Enum.Parse(typeof(IBTickType), TickType);

                Contract cc = XLOM.Get <Contract>(Contract);

                object x = "Error, no contract with key '" + Contract + "'!";
                if (cc != null)
                {
                    x = XlCall.RTD("XL.TickServer", null, Contract, TickType);
                }

                return(x);
            }
            catch (ArgumentException ae)
            {
                Debug.WriteLine("GetMarket: " + ae.ToString());
                return("Error: Couldn't parse tick type. " + ae.ToString());
            }
            catch (Exception e)
            {
                Debug.WriteLine("GetMarket: " + e.ToString());
                return(e.ToString());
            }
        }
示例#2
0
        public static object CreateMarketDataSource(string ContractHandle, object[] Timestamps, object[] MidPrices, object SpreadOpt)
        {
            double spread = Utils.GetOptionalParameter(SpreadOpt, 0.0);

            Contract cc = XLOM.Get <Contract>(ContractHandle);

            object[] timestamps = Utils.GetVector <object>(Timestamps);
            double[] midprices  = Utils.GetVector <double>(MidPrices);

            int  nData  = timestamps.Length;
            bool oaDate = (timestamps[0].GetType() == typeof(double));

            List <ITimestampedDatum> DataSource = new List <ITimestampedDatum>(nData);

            for (int i = 0; i < nData; ++i)
            {
                DateTimeOffset now = new DateTimeOffset((oaDate ? DateTime.FromOADate((double)timestamps[i]) : DateTime.Parse(timestamps[i].ToString())), new TimeSpan(0, 0, 0));
                DataSource.Add(new Market(now, cc.Id, (decimal)(midprices[i] * (1 - 0.5 * spread)), (decimal)(midprices[i] * (1 + 0.5 * spread))));
            }

            DataSourceInfo dsi = new DataSourceInfo("InMemoryMarketDataSource", cc.Id, cc.Symbol);

            if (XLOM.Contains(dsi.ToString()))
            {
                XLOM.Remove(dsi.ToString());
            }

            return(XLOM.Add(dsi.ToString(), DataSource));
        }
示例#3
0
        public static object[,] DisplayHandle(string Handle)
        {
            object o = XLOM.Get <object>(Handle);

            Type t = o.GetType();

            if (o is IEnumerable <double> )
            {
                IEnumerable <double> oo = o as IEnumerable <double>;

                object[,] data = new object[oo.Count(), 1];
                int i = 0;
                foreach (double dd in oo)
                {
                    data[i++, 0] = dd;
                }

                return(data);
            }
            else if (t == typeof(double[, ]))
            {
                double[,] oo = o as double[, ];
                int nRows = oo.GetLength(0), nCols = oo.GetLength(1);

                object[,] data = new object[nRows, nCols];
                for (int i = 0; i < nRows; ++i)
                {
                    for (int j = 0; j < nCols; ++j)
                    {
                        data[i, j] = oo[i, j];
                    }
                }

                return(data);
            }
            else if (t == typeof(object[, ]))
            {
                return(o as object[, ]);
            }
            else if (o is IEnumerable <ITimestampedDatum> )
            {
                IEnumerable <ITimestampedDatum> oo = o as IEnumerable <ITimestampedDatum>;

                object[,] data = new object[oo.Count(), 1];
                int i = 0;
                foreach (ITimestampedDatum dd in oo)
                {
                    data[i++, 0] = dd.ToString();
                }

                return(data);
            }

            throw new Exception("Error, unrecognised handle type in DisplayHandle()!");
        }
示例#4
0
        public static object GetOptionStrikes(string Underlying, string Expiry)
        {
            string omKey = Underlying + "_" + Expiry + "_Strikes";

            if (XLOM.Contains(omKey))
            {
                return(XLOM.Get(omKey));
            }

            object[,] ret = getOptionStrikes(Underlying, Expiry).ToRange();
            XLOM.Add(omKey, ret);

            return(ret);
        }
示例#5
0
文件: XL_RTD.cs 项目: uaqeel/ZeusXL
        public object ConnectData(int TopicId, ref Array Strings, ref bool GetNewValues)
        {
            if (Strings.Length != 2)
            {
                throw new Exception("Error: Must supply ContractId and TickType!");
            }

            string   contractKey = Strings.GetValue(0) as string;                                                           // The key in OM.
            Contract cc          = XLOM.Get <Contract>(contractKey);
            int      contractId  = cc.Id;
            string   contractCcy = cc.Currency;

            IBTickType tickType = (IBTickType)Enum.Parse(typeof(IBTickType), Strings.GetValue(1) as string, true);

            // If we're not already subscribed to this contract, crank up TWSSource.
            if (!(TopicsToContractIds.ContainsKey(TopicId) && TopicsToTickTypes.ContainsKey(TopicId)))
            {
                TopicsToContractIds.Add(TopicId, contractId);
                TopicsToTickTypes.Add(TopicId, tickType);

                if (!ContractsToMarkets.ContainsKey(contractId))
                {
                    ContractsToMarkets.Add(contractId, new Market(DateTimeOffset.UtcNow, contractId, -1, -1));
                    ContractsUpdated.Add(contractId, true);

                    XL_RTD.DataSource.Subscribe(cc);
                    XL_RTD.Ether.AsObservable <Market>().Where(x => x.ContractId == contractId).Subscribe(x =>
                    {
                        ContractsToMarkets[x.ContractId] = x;
                        ContractsUpdated[x.ContractId]   = true;

                        try
                        {
                            RTDCallback.UpdateNotify();
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine(e.StackTrace);
                        }
                    },
                                                                                                          e =>
                    {
                        Debug.WriteLine(e.ToString());
                    });
                }
            }

            return("(WAITING)");
        }
示例#6
0
文件: Utils.cs 项目: uaqeel/ZeusXL
        public static SerialisableDictionary CreateConfigDictionary(object[,] ConfigMatrix)
        {
            SerialisableDictionary cd = new SerialisableDictionary();

            int r = ConfigMatrix.GetLength(0);
            int c = ConfigMatrix.GetLength(1);

            if (c == 2)
            {
                for (int x = 0; x < r; ++x)
                {
                    if (!ConfigMatrix[x, 0].Equals(ExcelDna.Integration.ExcelEmpty.Value))
                    {
                        if (XLOM.Contains(ConfigMatrix[x, 1].ToString(), true))
                        {
                            cd[ConfigMatrix[x, 0].ToString()] = XLOM.Get(ConfigMatrix[x, 1].ToString());
                        }
                        else
                        {
                            cd[ConfigMatrix[x, 0].ToString()] = ConfigMatrix[x, 1];
                        }
                    }
                }
            }
            else if (c > 2)
            {
                for (int cc = 1; cc < c; ++cc)
                {
                    string colName = ConfigMatrix[0, cc].ToString();
                    Dictionary <string, object> cdd = new Dictionary <string, object>();
                    for (int x = 1; x < r; ++x)
                    {
                        cdd[ConfigMatrix[x, 0].ToString()] = ConfigMatrix[x, cc];
                    }

                    cd.Add(colName, cdd);
                }
            }

            return(cd);
        }
示例#7
0
        public static object CreateKeyValueMap(object[] Keys, object[] Values, object HandleNameOpt)
        {
            string handleName = Utils.GetOptionalParameter(HandleNameOpt, "KeyValueMap");

            string[] keys   = Utils.GetVector <string>(Keys);
            object[] values = Utils.GetVector <object>(Values);

            Dictionary <string, object> map = new Dictionary <string, object>();

            for (int i = 0; i < keys.Length; ++i)
            {
                if (XLOM.Contains(values[i].ToString(), true))
                {
                    map.Add(keys[i], XLOM.Get(values[i].ToString()));
                }
                else
                {
                    map.Add(keys[i], values[i]);
                }
            }

            return(XLOM.Add(handleName, map));
        }
示例#8
0
        public ObjectDisplayForm(string key)
        {
            InitializeComponent();

            object oo = XLOM.Get(key);

            var    serializer = new DataContractSerializer(oo.GetType());
            string xmlString;

            using (var sw = new StringWriter())
            {
                using (var writer = new XmlTextWriter(sw))
                {
                    writer.Formatting = Formatting.Indented;
                    serializer.WriteObject(writer, oo);
                    writer.Flush();
                    xmlString = sw.ToString();
                }
            }


            var xd = new XmlDocument();

            xd.LoadXml(xmlString);

            treeView1.Nodes.Clear();
            treeView1.Nodes.Add(new TreeNode(xd.DocumentElement.Name));

            TreeNode tNode = new TreeNode();

            tNode = treeView1.Nodes[0];

            AddNode(xd.DocumentElement, tNode);
            tNode.Expand();
            //treeView1.ExpandAll();
        }
示例#9
0
        public static object LoadFixings(string ticker, object BaseURLOpt, object ForceReloadOpt)
        {
            string baseURl        = Utils.GetOptionalParameter(BaseURLOpt, @"http://cg028486/jupiter/data/fixings");
            bool   forceReloadOpt = Utils.GetOptionalParameter(ForceReloadOpt, false);

            string key = ticker + "_fixings";
            SortedDictionary <DateTime, Tuple <double, double, double, double, string> > fixings = XLOM.Get <SortedDictionary <DateTime, Tuple <double, double, double, double, string> > >(key);

            if (forceReloadOpt || fixings == null)
            {
                fixings = new SortedDictionary <DateTime, Tuple <double, double, double, double, string> >();

                // Eg, http://cg028486/jupiter/data/fixings/ES1.xml
                string url = string.Format(@"{0}/{1}.xml", baseURl, ticker);

                XmlDocument xml = new XmlDocument();
                xml.Load(new XmlTextReader(url));

                var fixingNodes = xml.DocumentElement.SelectNodes("FixingSchedules/FixingSchedule/Fixings/EqFixing");
                foreach (XmlNode fixingNode in fixingNodes)
                {
                    DateTime date    = DateTime.Parse(fixingNode["Date"].InnerText);
                    string   comment = fixingNode["Comments"].InnerText;

                    double open = -1;
                    double.TryParse(fixingNode["Open"].InnerText, out open);

                    double low = -1;
                    double.TryParse(fixingNode["Low"].InnerText, out low);

                    double high = -1;
                    double.TryParse(fixingNode["High"].InnerText, out high);

                    double close = -1;
                    double.TryParse(fixingNode["Close"].InnerText, out close);

                    if (close != 0)
                    {
                        fixings.Add(date, new Tuple <double, double, double, double, string>(open, low, high, close, comment));
                    }
                }

                XLOM.Add(ticker + "_fixings", fixings);
            }

            object[,] ret = new object[fixings.Count + 1, 6];
            ret[0, 0]     = "Date";
            ret[0, 1]     = "Open";
            ret[0, 2]     = "Low";
            ret[0, 3]     = "High";
            ret[0, 4]     = "Close";
            ret[0, 5]     = "Comment";

            int i = 1;

            foreach (var fixing in fixings)
            {
                ret[i, 0] = fixing.Key;
                ret[i, 1] = fixing.Value.Item1;
                ret[i, 2] = fixing.Value.Item2;
                ret[i, 3] = fixing.Value.Item3;
                ret[i, 4] = fixing.Value.Item4;
                ret[i, 5] = fixing.Value.Item5;

                i++;
            }

            return(ret);
        }
示例#10
0
        public static object ZEval(object[] Expressions, string StartDate, object EndDateOpt,
                                   [ExcelArgument(Description = "Use 'TR' to attempt to use total return indices. BBG limited to 5k data points.")]
                                   object FieldOpt, object PeriodicityOpt,
                                   object ReverseOpt, object NoLabelsOpt, object[] NamesOpt)
        {
            if (ExcelDnaUtil.IsInFunctionWizard())
            {
                return("#N/A");
            }

            string[] expressionSet = Utils.GetVector <string>(Expressions);
            string   field         = Utils.GetOptionalParameter(FieldOpt, "PX_LAST");

            if (field.ToLower().StartsWith("tr"))
            {
                field = "TOT_RETURN_INDEX_NET_DVDS";
            }

            string periodicity = Utils.GetOptionalParameter(PeriodicityOpt, "Daily").ToUpper();

            string startDate = Utils.GetDate(StartDate, DateTime.Now).ToString("yyyyMMdd");
            string endDate   = Utils.GetDate(EndDateOpt, DateTime.Now).ToString("yyyyMMdd");

            bool reverse  = Utils.GetOptionalParameter(ReverseOpt, false);
            bool noLabels = Utils.GetOptionalParameter(NoLabelsOpt, false);

            string[] names = Utils.GetVector <string>(NamesOpt);

            Stopwatch sw1 = new Stopwatch();

            sw1.Start();

            // Identify tickers.
            Regex regex = new Regex(@"(?<=\{).*?(?=\})");
            Dictionary <string, string> tickersToVariables = new Dictionary <string, string>();

            // We're going to decorate naked expressions with curlies UNLESS the expression set contains '=' signs, which signify
            // variable declarations.
            bool needsBracesDefault = true;

            if (expressionSet.Where(x => x.Contains('=')).Count() > 0)
            {
                needsBracesDefault = false;
            }

            int i = 0;

            foreach (string expression in expressionSet)
            {
                bool needsBraces = needsBracesDefault;

                foreach (Match match in regex.Matches(expression))
                {
                    string ticker = match.Value;
                    if (ticker.Contains("r@") || ticker.Contains("d@") || ticker.Contains("l@"))
                    {
                        ticker = ticker.Replace("r@", "");
                        ticker = ticker.Replace("d@", "");
                        ticker = ticker.Replace("l@", "");
                    }

                    needsBraces = false;

                    if (tickersToVariables.ContainsKey(ticker))
                    {
                        continue;
                    }
                    else
                    {
                        tickersToVariables[ticker] = "group" + (i++);
                    }
                }

                // If no matches found, assume the whole expression is one ticker.
                if (needsBraces)
                {
                    expressionSet[i] = "{" + expression + "}";
                    tickersToVariables[expression] = "group" + (i++);
                }
            }

            // Assemble raw data.
            string[] tickersToRetrieve = tickersToVariables.Keys.Where(x =>
            {
                string key = MakeKey(x, startDate, endDate, field, periodicity);
                return(!XLOM.Contains(key));
            }).ToArray();

            if (tickersToRetrieve.Length != 0)
            {
                bool ok = GetBBGData(tickersToRetrieve, startDate, endDate, field, periodicity);

                if (!ok)
                {
                    throw new Exception("Error retrieving data from Bloomberg!");
                }
            }

            Debug.Write("Got data in " + sw1.ElapsedMilliseconds + "ms; ");
            sw1.Restart();

            Dictionary <string, SortedDictionary <DateTime, double> > data = new Dictionary <string, SortedDictionary <DateTime, double> >();
            SortedSet <DateTime> dates = new SortedSet <DateTime>();

            DateTime firstDate = new DateTime(9999, 1, 1);

            foreach (string ticker in tickersToVariables.Keys)
            {
                string key = MakeKey(ticker, startDate, endDate, field, periodicity);
                data[ticker] = XLOM.Get(key) as SortedDictionary <DateTime, double>;

                DateTime startDate1 = data[ticker].Keys.FirstOrDefault();
                if (startDate1 < firstDate)
                {
                    firstDate = startDate1;
                }

                if (data[ticker] != null)
                {
                    dates.UnionWith(data[ticker].Keys.Where(x => x >= firstDate));
                }
            }

            dates.RemoveWhere(x => x < firstDate);

            Debug.Write("assembled data in " + sw1.ElapsedMilliseconds + "ms; ");
            sw1.Restart();

            return(ZEvalOnData(expressionSet, reverse, noLabels, names, sw1, tickersToVariables, data, dates));
        }
示例#11
0
        public static object GetOptionTicker(string Underlying, string Expiry, double Strike, int PutOrCall)
        {
            DateTime expiry;

            if (!DateTime.TryParse(Expiry, out expiry))
            {
                expiry = DateTime.FromOADate(int.Parse(Expiry));
            }

            string type = Underlying.Split(' ').Last();

            string omKey = Underlying + "_OptionTickerTemplate";

            if (XLOM.Contains(omKey))
            {
                string ticker = XLOM.Get(omKey).ToString().Replace("___TYPE___", PutOrCall == -1 ? " P" : " C")
                                .Replace("___STRIKE___", Strike.ToString())
                                .Replace("___EXPIRY___", expiry.ToString("MM/dd/yy"));
                return(ticker);
            }

            session = new Session();
            bool sessionStarted = session.Start();

            if (!sessionStarted || !session.OpenService("//blp/refdata"))
            {
                throw new Exception("Failed to connect to Bloomberg!");
            }

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

            Element securities = request.GetElement("securities");

            securities.AppendValue(Underlying);

            Element fields = request.GetElement("fields");

            fields.AppendValue("CHAIN_FULL");

            session.SendRequest(request, null);

            while (true)
            {
                Event eventObj = session.NextEvent();
                foreach (Message msg in eventObj)
                {
                    if (msg.HasElement("securityData"))
                    {
                        Element securityData  = msg["securityData"].GetValueAsElement(0);
                        Element structureData = (Element)securityData["fieldData"].GetElement(0);
                        for (int i = 0; i < structureData.NumValues; ++i)
                        {
                            double   strike     = ((Element)structureData[i])["Strike"].GetValueAsFloat64();
                            string   expiration = ((Element)structureData[i])["Expiration"].GetValueAsString();
                            DateTime dt         = DateTime.Parse(expiration);

                            if (dt == expiry && strike == Strike)
                            {
                                string ticker;
                                if (PutOrCall == -1)
                                {
                                    ticker = ((Element)structureData[i])["Put Ticker"].GetValueAsString() + " " + type;
                                }
                                else
                                {
                                    ticker = ((Element)structureData[i])["Call Ticker"].GetValueAsString() + " " + type;
                                }

                                string template = ticker.Replace(dt.ToString("MM/dd/yy"), "___EXPIRY___").Replace(strike.ToString(), "___STRIKE___");
                                template = template.Replace(PutOrCall == -1 ? " P" : " C", " ___TYPE___");
                                XLOM.Add(omKey, template);

                                return(ticker);
                            }
                        }
                    }
                }

                if (eventObj.Type == Event.EventType.RESPONSE)
                {
                    break;
                }
            }

            return("Error, no such listed option!");
        }
示例#12
0
        public static object ZDH(object[] Tickers, string StartDate, object EndDateOpt, object FieldOpt, object PeriodicityOpt,
                                 object ReverseOpt, object NoLabelsOpt, object[] NamesOpt, object NormaliseOpt)
        {
            if (ExcelDnaUtil.IsInFunctionWizard())
            {
                return("#N/A");
            }

            string[] tickers     = Utils.GetVector <string>(Tickers);
            string   periodicity = Utils.GetOptionalParameter(PeriodicityOpt, "Daily").ToUpper();
            string   field       = Utils.GetOptionalParameter(FieldOpt, "PX_LAST");

            if (field.ToLower().StartsWith("tr"))
            {
                field = "TOT_RETURN_INDEX_NET_DVDS";
            }

            string startDate = Utils.GetDate(StartDate, DateTime.Now).ToString("yyyyMMdd");
            string endDate   = Utils.GetDate(EndDateOpt, DateTime.Now).ToString("yyyyMMdd");

            bool reverse  = Utils.GetOptionalParameter(ReverseOpt, false);
            bool noLabels = Utils.GetOptionalParameter(NoLabelsOpt, false);

            string[] names     = Utils.GetVector <string>(NamesOpt);
            bool     normalise = Utils.GetOptionalParameter(NormaliseOpt, false);

            // Retrieve required data.
            string[] tickersToRetrieve = tickers.Where(x =>
            {
                string key = MakeKey(x, startDate, endDate, field, periodicity);
                return(!XLOM.Contains(key));
            }).ToArray();

            if (tickersToRetrieve.Length != 0)
            {
                bool ok = GetBBGData(tickersToRetrieve, startDate, endDate, field, periodicity);

                if (!ok)
                {
                    throw new Exception("Error retrieving data from Bloomberg!");
                }
            }

            // Assemble data.
            Dictionary <string, SortedDictionary <DateTime, double> > data = new Dictionary <string, SortedDictionary <DateTime, double> >();
            SortedSet <DateTime> dates = new SortedSet <DateTime>();

            foreach (string ticker in tickers)
            {
                string key = MakeKey(ticker, startDate, endDate, field, periodicity);
                data[ticker] = XLOM.Get(key) as SortedDictionary <DateTime, double>;

                if (data[ticker] != null)
                {
                    dates.UnionWith(data[ticker].Keys);
                }
            }

            object[,] ret = new object[dates.Count + (noLabels ? 0 : 1), tickers.Length + (noLabels ? 0 : 1)];
            ret[0, 0]     = "Date";

            double[] normalisationFactors = new double[tickers.Length];
            for (int x = 0; x < tickers.Length; ++x)
            {
                normalisationFactors[x] = normalise ? data[tickers[x]].First().Value : 1;
            }

            int i = 1;

            foreach (DateTime date in (reverse ? dates.Reverse() : dates))
            {
                ret[i, 0] = date;

                int j = 0;
                foreach (string ticker in tickers)
                {
                    if (i == 1 && !noLabels)
                    {
                        ret[0, j + 1] = (names.Length == 0 ? ticker : names[j]);
                    }

                    if (data[ticker].ContainsKey(date))
                    {
                        ret[i, j + 1] = data[ticker][date] / normalisationFactors[j];
                    }
                    else
                    {
                        ret[i, j + 1] = data[ticker].Where(x => x.Key < date).OrderBy(x => x.Key).LastOrDefault().Value / normalisationFactors[j];
                    }

                    j++;
                }

                i++;
            }

            return(ret);
        }
示例#13
0
        public static object GetImpliedForwardCurve(string Underlying, object ExcludeZeroVolumeOptions)
        {
            bool excludeOnZeroVolume = Utils.GetOptionalParameter <bool>(ExcludeZeroVolumeOptions, false);

            string omKey = Underlying + "_ForwardFactors";

            if (XLOM.Contains(omKey))
            {
                return(XLOM.Get(omKey));
            }

            SortedDictionary <DateTime, SummaryContainer> forwardFactors = new SortedDictionary <DateTime, SummaryContainer>();

            string type = Underlying.Split(' ').Last();

            // Get call and put tickers.
            session = new Session();
            bool sessionStarted = session.Start();

            if (!sessionStarted || !session.OpenService("//blp/refdata"))
            {
                return("Failed to connect to Bloomberg!");
            }

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

            Element securities = request.GetElement("securities");

            securities.AppendValue(Underlying);

            Element fields = request.GetElement("fields");

            fields.AppendValue("PX_LAST");
            fields.AppendValue("CHAIN_FULL");

            session.SendRequest(request, null);

            double        spot    = 0;
            List <string> tickers = new List <string>();

            while (true)
            {
                Event eventObj = session.NextEvent();
                foreach (Message msg in eventObj)
                {
                    if (msg.HasElement("securityData"))
                    {
                        Element securityData = msg["securityData"].GetValueAsElement(0);

                        if (securityData["fieldData"].HasElement("PX_LAST"))
                        {
                            spot = securityData["fieldData"].GetElement("PX_LAST").GetValueAsFloat64();
                        }

                        Element structureData = (Element)securityData["fieldData"].GetElement("CHAIN_FULL");

                        for (int i = 0; i < structureData.NumValues; ++i)
                        {
                            string   expiration = ((Element)structureData[i])["Expiration"].GetValueAsString();
                            DateTime dt         = DateTime.Parse(expiration);

                            if (!forwardFactors.ContainsKey(dt))
                            {
                                forwardFactors.Add(dt, new SummaryContainer());
                            }

                            double strike = ((Element)structureData[i])["Strike"].GetValueAsFloat64();

                            if (spot == 0 || Math.Abs(strike / spot - 1) < 0.3)
                            {
                                string call = ((Element)structureData[i])["Call Ticker"].GetValueAsString();

                                tickers.Add(call);
                            }
                        }
                    }
                }

                if (eventObj.Type == Event.EventType.RESPONSE)
                {
                    break;
                }
            }

            // Get implied forwards.
            if (tickers.Count > 0)
            {
                Request req2        = refDataService.CreateRequest("ReferenceDataRequest");
                Element securities2 = req2.GetElement("securities");
                tickers.ForEach(x => securities2.AppendValue(x + " " + type));

                Element fields2 = req2.GetElement("fields");
                fields2.AppendValue("OPT_EXPIRE_DT");
                fields2.AppendValue("PARITY_FWD_MID");
                fields2.AppendValue("VOLUME");

                session.SendRequest(req2, null);

                while (true)
                {
                    Event eventObj = session.NextEvent();
                    foreach (Message msg in eventObj)
                    {
                        if (msg.HasElement("securityData"))
                        {
                            int numValues = msg["securityData"].NumValues;
                            for (int i = 0; i < numValues; ++i)
                            {
                                Element securityData = msg["securityData"].GetValueAsElement(i);
                                if (securityData.HasElement("fieldData") && securityData["fieldData"].NumElements > 0)
                                {
                                    int volume = 0;
                                    if (securityData["fieldData"].HasElement("VOLUME"))
                                    {
                                        volume = securityData["fieldData"].GetElement("VOLUME").GetValueAsInt32();
                                    }

                                    DateTime expiration = DateTime.Now;
                                    if (securityData["fieldData"].HasElement("OPT_EXPIRE_DT"))
                                    {
                                        string exp = ((Element)securityData["fieldData"]).GetElement("OPT_EXPIRE_DT").GetValueAsString();
                                        expiration = DateTime.Parse(exp);
                                    }

                                    Element structureData = (Element)securityData["fieldData"].GetElement("PARITY_FWD_MID");

                                    if (structureData.NumValues > 0)
                                    {
                                        double forward = structureData.GetValueAsFloat64();
                                        if (volume > 0 || !excludeOnZeroVolume)
                                        {
                                            forwardFactors[expiration].Add(forward / spot);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (eventObj.Type == Event.EventType.RESPONSE)
                    {
                        break;
                    }
                }
            }

            object[,] ret = new object[forwardFactors.Count, 2];
            int j = 0;

            foreach (KeyValuePair <DateTime, SummaryContainer> kv in forwardFactors)
            {
                ret[j, 0] = kv.Key;

                if (kv.Value.Average == 0)
                {
                    ret[j, 1] = ExcelDna.Integration.ExcelError.ExcelErrorNA;
                }
                else
                {
                    ret[j, 1] = kv.Value.Average;
                }

                j++;
            }

            // Save the forward factors.
            XLOM.Add(omKey, ret);

            return(ret);
        }
示例#14
0
        public static object GetOptionExpiries(string Underlying, object ExpiryTypeOpt)
        {
            string expirytype = Utils.GetOptionalParameter(ExpiryTypeOpt, string.Empty);

            string omKey = Underlying + "_" + expirytype + "_Expiries";

            if (XLOM.Contains(omKey))
            {
                return(XLOM.Get(omKey));
            }

            session = new Session();
            bool sessionStarted = session.Start();

            if (!sessionStarted || !session.OpenService("//blp/refdata"))
            {
                return("Failed to connect to Bloomberg!");
            }

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

            Element securities = request.GetElement("securities");

            securities.AppendValue(Underlying);

            Element fields = request.GetElement("fields");

            fields.AppendValue("CHAIN_STRUCTURE");

            session.SendRequest(request, null);

            List <DateTime> expiries = new List <DateTime>();

            while (true)
            {
                Event eventObj = session.NextEvent();
                foreach (Message msg in eventObj)
                {
                    if (msg.HasElement("securityData"))
                    {
                        Element securityData  = msg["securityData"].GetValueAsElement(0);
                        Element structureData = (Element)securityData["fieldData"].GetElement(0);
                        for (int i = 0; i < structureData.NumValues; ++i)
                        {
                            string   expiry = ((Element)structureData[i])["Expiration"].GetValueAsString();
                            DateTime dt     = DateTime.Parse(expiry);

                            if (expirytype == string.Empty || expirytype == "All" || ((Element)structureData[i])["Periodicity"].GetValueAsString() == expirytype)
                            {
                                expiries.Add(dt);
                            }
                        }
                    }
                }

                if (eventObj.Type == Event.EventType.RESPONSE)
                {
                    break;
                }
            }

            object[,] ret = expiries.Distinct().Select(x => x.ToOADate()).OrderBy(x => x).ToArray().ToRange();
            XLOM.Add(omKey, ret);

            return(ret);
        }
示例#15
0
        public static object GetContractId(string ContractHandle)
        {
            Contract cc = XLOM.Get <Contract>(ContractHandle);

            return(cc.Id);
        }