Example #1
0
        // get stock/option historical prices
        public ArrayList GetHistoricalData(string ticker, DateTime start, DateTime end)
        {
            Symbol.Type type = Symbol.Type.Unknown;
            ticker = Symbol.CorrectSymbol(ticker, out type);

            return(yho.GetHistoricalData(ticker, start, end));
        }
Example #2
0
        // get stock latest quote
        public Quote GetQuote(string ticker)
        {
            Symbol.Type type = Symbol.Type.Unknown;
            ticker = Symbol.CorrectSymbol(ticker, out type);

            string mode = config["QuoteDataSource"];

            Quote quote = null;

            switch (mode)
            {
            case "A":
            case "Default":
            default:
                quote = yho.GetQuote(ticker);
                if (quote == null)
                {
                    quote = msn.GetQuote(ticker);
                }
                break;

            case "B":
                quote = msn.GetQuote(ticker);
                if (quote == null)
                {
                    quote = yho.GetQuote(ticker);
                }
                break;
            }

            return(quote);
        }
Example #3
0
        /**
         * Metodos generico
         */
        /**
         * Define uma variavel na tabela de simbolo
         * @param type
         * @param nameToken
         */
        Symbol defineVar(Symbol.Type type, IToken nameToken, ParserRuleContext ctx)
        {
            String varName = nameToken.Text.ToUpper();

            if (!currentScope.existLocalScope(varName))
            {
                VariableSymbol var = new VariableSymbol(nameToken.Text, type);
                currentScope.define(var); // Define symbol in current scope
                var.setContext(ctx);
                return(var);
            }
            else
            {
                /*  String msg = String.format(Messages.DefPhase_2, varName);
                 * Token ec = nameToken;
                 * int st = this.m_converter.convert(ec).getColumn();
                 * String sm = ec.getText();
                 * int et = st + ((sm != null) ? sm.length() : 1);
                 * if (st == -1)
                 *    return null;
                 *
                 * DefaultProblem defaultProblem = new DefaultProblem("", msg, 0,
                 * new String[] { }, ProblemSeverities.Error, st, et,
                 * ec.getLine());
                 * m_reporter.reportProblem(defaultProblem);*/
            }
            return(null);
        }
Example #4
0
 void defineStaticCh(Symbol.Type type, String varName, String value)
 {
     if (!currentScope.existLocalScope(varName))
     {
         VariableSymbol var = new VariableSymbol(varName, type);
         currentScope.define(var); // Define symbol in current scope
     }
 }
Example #5
0
        // get default historical volatility for specified duration [in years]
        public double GetHistoricalVolatility(string ticker, double duration)
        {
            Symbol.Type type = Symbol.Type.Unknown;
            ticker = Symbol.CorrectSymbol(ticker, out type);

            // get historical data
            ArrayList list = GetHistoricalData(ticker, DateTime.Now.AddDays(-duration * 365), DateTime.Now);

            // calculate historical value
            return(100.0 * HistoryVolatility.HighLowParkinson(list));
        }
Example #6
0
 /// <summary>
 /// Finds symbols that overlap with the specified value and width.  If more than one
 /// matching symbol is found, an arbitrary match will be returned.  Comparisons are
 /// only performed between symbols of the same type, so addresses and constants do
 /// not clash.
 /// </summary>
 /// <param name="value">Value to compare.</param>
 /// <param name="width">Width to check, useful when checking for collisions.  When
 ///   doing a simple variable lookup, this should be set to 1.</param>
 /// <returns>One matching symbol, or null if none matched.</returns>
 public DefSymbol GetByValueRange(int value, int width, Symbol.Type type)
 {
     foreach (KeyValuePair <string, DefSymbol> kvp in mVarByLabel)
     {
         if (DefSymbol.CheckOverlap(kvp.Value, value, width, type))
         {
             return(kvp.Value);
         }
     }
     return(null);
 }
Example #7
0
        public override void EnterFuncDeclaration(AdvplParser.FuncDeclarationContext ctx)
        {
            String name          = ctx.identifier().GetText();
            int    typeTokenType = -1;

            if (ctx.modifiersFunction() != null)
            {
                typeTokenType = ctx.modifiersFunction().start.Type;
            }
            Symbol.Type type = CheckSymbols.getType(typeTokenType);

            FunctionSymbol function = new FunctionSymbol(name, type, currentScope);

            function.startFuncionPos = ctx.start.StartIndex;
            function.endFuncionPos   = ctx.stop.StopIndex;
            m_functionsAndMethodsInSource.Add(function);
            currentScope.define(function);
            saveScope(ctx, function);
            currentScope = function;
            allScopes.Add(currentScope);
            treesByScopes.Add(currentScope, ctx);
        }
Example #8
0
        // get stock latest options chain
        public ArrayList GetOptionsChain(string ticker)
        {
            Symbol.Type type = Symbol.Type.Unknown;
            ticker = Symbol.CorrectSymbol(ticker, out type);

            string mode = "Default";

            if (type == Symbol.Type.Stock)
            {
                mode = config["StockOptionChainDataSource"];
            }
            else if (type == Symbol.Type.Fund)
            {
                mode = config["FundOptionChainDataSource"];
            }
            else if (type == Symbol.Type.Index)
            {
                mode = config["IndexOptionChainDataSource"];
            }

            ArrayList list = null;

            switch (mode)
            {
            case "A":
            {
                list = mkw.GetOptionsChain(ticker, type);

                if ((list == null || list.Count == 0) && type == Symbol.Type.Stock)
                {
                    list = mkw.GetOptionsChain(ticker, Symbol.Type.Fund);
                }

                if ((list == null || list.Count == 0) && type == Symbol.Type.Fund)
                {
                    list = mkw.GetOptionsChain(ticker, Symbol.Type.Index);
                }
            }
            break;

            case "B":
            {
                list = mst.GetOptionsChain(ticker, type);
            }
            break;

            case "C":
            {
                list = yho.GetOptionsChain(ticker);
            }
            break;

            case "D":
            {
                list = opt.GetOptionsChain(ticker, type);
            }
            break;

            case "Default":
            default:
                if (type != Symbol.Type.Index)
                {
                    list = mkw.GetOptionsChain(ticker, type);

                    if ((list == null || list.Count == 0))
                    {
                        list = mkw.GetOptionsChain(ticker, Symbol.Type.Fund);
                    }

                    if ((list == null || list.Count == 0))
                    {
                        list = mst.GetOptionsChain(ticker, type);
                    }

                    if ((list == null || list.Count == 0))
                    {
                        list = yho.GetOptionsChain(ticker);
                    }

                    if ((list == null || list.Count == 0))
                    {
                        list = opt.GetOptionsChain(ticker, type);
                    }
                }
                else
                {
                    list = opt.GetOptionsChain(ticker, type);

                    if ((list == null || list.Count == 0))
                    {
                        list = mst.GetOptionsChain(ticker, type);
                    }

                    if ((list == null || list.Count == 0))
                    {
                        list = mkw.GetOptionsChain(ticker, type);
                    }

                    if ((list == null || list.Count == 0) && type == Symbol.Type.Fund)
                    {
                        list = mkw.GetOptionsChain(ticker, Symbol.Type.Index);
                    }

                    if ((list == null || list.Count == 0))
                    {
                        list = yho.GetOptionsChain(ticker);
                    }
                }
                break;
            }

            return(list);
        }
Example #9
0
        /// <summary>
        /// Validates input and updates controls appropriately.
        /// </summary>
        private void UpdateControls()
        {
            if (!IsLoaded)
            {
                return;
            }

            // Label must be valid and not already exist in the table we're editing.  (For project
            // symbols, it's okay if an identical label exists elsewhere.)
            bool labelValid = Asm65.Label.ValidateLabel(Label);
            bool labelUnique;

            // NOTE: should be using Asm65.Label.LABEL_COMPARER?
            if (mDefSymbolList.TryGetValue(Label, out DefSymbol existing))
            {
                // It's okay if it's the same object.
                labelUnique = (existing == mOldSym);
            }
            else
            {
                labelUnique = true;
            }

            // For local variables, do a secondary uniqueness check across the full symbol table.
            if (labelUnique && mSymbolTable != null)
            {
                labelUnique = !mSymbolTable.TryGetValue(Label, out Symbol sym);

                // It's okay if this and the other are both variables.
                if (!labelUnique && IsVariable && sym.IsVariable)
                {
                    labelUnique = true;
                }
            }

            // Value must be blank, meaning "erase any earlier definition", or valid value.
            // (Hmm... don't currently have a way to specify "no symbol" in DefSymbol.)
            //if (!string.IsNullOrEmpty(valueTextBox.Text)) {
            bool valueValid = ParseValue(out int thisValue, out int unused2);
            //} else {
            //    valueValid = true;
            //}

            bool widthValid = true;
            int  thisWidth  = -1;

            if (IsConstant && !IsVariable)
            {
                // width field is ignored
            }
            else if (string.IsNullOrEmpty(VarWidth))
            {
                // blank field is okay if the width is optional
                widthValid = mIsWidthOptional;
            }
            else if (!Asm65.Number.TryParseInt(VarWidth, out thisWidth, out int unusedBase) ||
                     thisWidth < DefSymbol.MIN_WIDTH || thisWidth > DefSymbol.MAX_WIDTH ||
                     (IsVariable && thisWidth > 256))
            {
                // All widths must be between 1 and 65536.  For a variable, the full thing must
                // fit on zero page without wrapping.  We test for 256 here so that we highlight
                // the "bad width" label, rather than the "it doesn't fit on the page" label.
                widthValid = false;
            }

            bool valueRangeValid = true;

            if (IsVariable && valueValid && widthValid)
            {
                // $ff with width 1 is okay, $ff with width 2 is not
                if (thisValue < 0 || thisValue + thisWidth > 256)
                {
                    valueRangeValid = false;
                }
            }

            Symbol.Type symbolType = IsConstant ? Symbol.Type.Constant : Symbol.Type.ExternalAddr;

            // For a variable, the value must also be unique within the table.  Values have
            // width, so we need to check for overlap.
            bool valueUniqueValid = true;

            if (IsVariable && valueValid && widthValid)
            {
                foreach (KeyValuePair <string, DefSymbol> kvp in mDefSymbolList)
                {
                    if (kvp.Value != mOldSym &&
                        DefSymbol.CheckOverlap(kvp.Value, thisValue, thisWidth, symbolType))
                    {
                        valueUniqueValid = false;
                        break;
                    }
                }
            }

            bool rwValid = true;

            if (!IsVariable && IsAddress)
            {
                rwValid = IsReadChecked || IsWriteChecked;
            }

            labelNotesLabel.Foreground  = labelValid ? mDefaultLabelColor : Brushes.Red;
            labelUniqueLabel.Foreground = projectLabelUniqueLabel.Foreground =
                labelUnique ? mDefaultLabelColor : Brushes.Red;
            valueNotesLabel.Foreground     = valueValid ? mDefaultLabelColor : Brushes.Red;
            varValueRangeLabel.Foreground  = valueRangeValid ? mDefaultLabelColor : Brushes.Red;
            varValueUniqueLabel.Foreground = valueUniqueValid ? mDefaultLabelColor : Brushes.Red;
            widthNotesLabel.Foreground     = widthValid ? mDefaultLabelColor : Brushes.Red;
            checkReadWriteLabel.Foreground = rwValid ? mDefaultLabelColor : Brushes.Red;

            IsValid = labelValid && labelUnique && valueValid && valueRangeValid &&
                      valueUniqueValid && widthValid && rwValid;
        }
Example #10
0
        /// <summary>
        /// Validates input and updates controls appropriately.
        /// </summary>
        private void UpdateControls()
        {
            if (!IsLoaded)
            {
                return;
            }

            // Label must be valid and not already exist in the table we're editing.  (For project
            // symbols, it's okay if an identical label exists elsewhere.)
            string trimLabel = Symbol.TrimAndValidateLabel(Label, string.Empty,
                                                           out bool labelValid, out bool unused1, out bool unused2, out bool unused3,
                                                           out Symbol.LabelAnnotation unused4);
            bool labelUnique;

            if (mDefSymbolList.TryGetValue(trimLabel, out DefSymbol existing))
            {
                // We found a match.  See if we're just seeing the symbol we're editing.
                //
                // We only want to check the label, not the entire symbol, because otherwise
                // things can go funny when multiple edits are done without flushing the data
                // back to the symbol table.  For example, when this is invoked from the
                // Edit Project Symbol button in the instruction operand editor, the user might
                // edit the comment field of an existing project symbol, hit OK here, then try
                // to edit it again before closing the operand editor.  In that case we get
                // passed the edited DefSymbol, which no longer fully matches what's in the
                // symbol table.
                //
                // TODO: we still don't handle the case where the user changes the label from
                // FOO to FOO1 and then back to FOO without closing the instruction edit dialog.
                // The problem is that we find a match for FOO in the symbol table without
                // realizing that it was the original name before the edits began.  To fix this
                // we need to pass in the original label as well as the recently-edited symbol,
                // and allow the new name to match either.

                //labelUnique = (existing == mOldSym);
                labelUnique = Asm65.Label.LABEL_COMPARER.Equals(existing.Label, mOldSym.Label);
            }
            else
            {
                labelUnique = true;
            }

            // For local variables, do a secondary uniqueness check across the full symbol table.
            if (labelUnique && mSymbolTable != null)
            {
                labelUnique = !mSymbolTable.TryGetValue(trimLabel, out Symbol sym);

                // It's okay if this and the other are both variables.
                if (!labelUnique && IsVariable && sym.IsVariable)
                {
                    labelUnique = true;
                }
            }

            // Value must be blank, meaning "erase any earlier definition", or valid value.
            // (Hmm... don't currently have a way to specify "no symbol" in DefSymbol.)
            //if (!string.IsNullOrEmpty(valueTextBox.Text)) {
            bool valueValid = ParseValue(out int thisValue, out int unused5);
            //} else {
            //    valueValid = true;
            //}

            bool widthValid = true;
            int  thisWidth  = -1;

            if (IsConstant && !IsVariable)
            {
                // width field is ignored
            }
            else if (string.IsNullOrEmpty(VarWidth))
            {
                // blank field is okay if the width is optional
                widthValid = mIsWidthOptional;
            }
            else if (!Asm65.Number.TryParseInt(VarWidth, out thisWidth, out int unusedBase) ||
                     thisWidth < DefSymbol.MIN_WIDTH || thisWidth > DefSymbol.MAX_WIDTH ||
                     (IsVariable && thisWidth > MAX_VAR_WIDTH))
            {
                // All widths must be between 1 and 65536.  For a variable, the full thing must
                // fit on zero page, except on 65816 where a 16-bit access at $ff can extend
                // off the end of the direct page.
                //
                // We test the variable width here so that we highlight the "width limit" label,
                // rather than the "value range" label.
                widthValid = false;
            }

            bool valueRangeValid = true;

            if (IsVariable && valueValid && widthValid)
            {
                // $ff with width 1 is okay, $ff with width 2 is okay on 65816, width=3 is bad
                if (thisValue < 0 || thisValue + thisWidth > MAX_VAR_WIDTH)
                {
                    valueRangeValid = false;
                }
            }
            else if (IsAddress && valueValid)
            {
                // limit to positive 24-bit integers; use a long for value+width so we
                // don't get fooled by overflow
                long lvalue = thisValue;
                if (thisWidth > 0)
                {
                    lvalue += thisWidth - 1;
                }
                if (thisValue < 0 || lvalue > 0x00ffffff)
                {
                    valueRangeValid = false;
                }
            }

            Symbol.Type symbolType = IsConstant ? Symbol.Type.Constant : Symbol.Type.ExternalAddr;

            // For a variable, the value must also be unique within the table.  Values have
            // width, so we need to check for overlap.
            bool valueUniqueValid = true;

            if (IsVariable && valueValid && widthValid)
            {
                foreach (KeyValuePair <string, DefSymbol> kvp in mDefSymbolList)
                {
                    if (kvp.Value != mOldSym &&
                        DefSymbol.CheckOverlap(kvp.Value, thisValue, thisWidth, symbolType))
                    {
                        valueUniqueValid = false;
                        break;
                    }
                }
            }

            bool rwValid = true;

            if (!IsVariable && IsAddress)
            {
                rwValid = IsReadChecked || IsWriteChecked;
            }

            labelNotesLabel.Foreground  = labelValid ? mDefaultLabelColor : Brushes.Red;
            labelUniqueLabel.Foreground = projectLabelUniqueLabel.Foreground =
                labelUnique ? mDefaultLabelColor : Brushes.Red;
            valueNotesLabel.Foreground     = valueValid ? mDefaultLabelColor : Brushes.Red;
            addrValueRangeLabel.Foreground = valueRangeValid ? mDefaultLabelColor : Brushes.Red;
            varValueRangeLabel.Foreground  = valueRangeValid ? mDefaultLabelColor : Brushes.Red;
            varValueUniqueLabel.Foreground = valueUniqueValid ? mDefaultLabelColor : Brushes.Red;
            widthNotesLabel.Foreground     = widthValid ? mDefaultLabelColor : Brushes.Red;
            checkReadWriteLabel.Foreground = rwValid ? mDefaultLabelColor : Brushes.Red;

            IsValid = labelValid && labelUnique && valueValid && valueRangeValid &&
                      valueUniqueValid && widthValid && rwValid;
        }
Example #11
0
        /// <summary>
        /// Validates input and updates controls appropriately.
        /// </summary>
        private void UpdateControls()
        {
            if (!IsLoaded)
            {
                return;
            }

            // Label must be valid and not already exist in the table we're editing.  (For project
            // symbols, it's okay if an identical label exists elsewhere.)
            string trimLabel = Symbol.TrimAndValidateLabel(Label, string.Empty,
                                                           out bool labelValid, out bool unused1, out bool unused2, out bool unused3,
                                                           out Symbol.LabelAnnotation unused4);
            bool labelUnique;

            if (mDefSymbolList.TryGetValue(trimLabel, out DefSymbol existing))
            {
                // We found a match.  See if we're just seeing the symbol we're editing.
                // If there's no "original" symbol, then the fact that we matched anything
                // means the label is not unique.  Otherwise, we consider it unique if the
                // label matches the original symbol.
                //
                // We only need to check the label.  Since we're comparing the original
                // symbol to the value from the symbol table, it should be a total match,
                // but the other fields don't actually matter.  It's safer to let the Symbol
                // class comparison operators do the work though.
                labelUnique = (existing == mOrigSym);
                //labelUnique = mOrigSym != null &&
                //    Asm65.Label.LABEL_COMPARER.Equals(existing.Label, mOrigSym.Label);
            }
            else
            {
                labelUnique = true;
            }

            // For local variables, do a secondary uniqueness check across the full symbol table.
            if (labelUnique && mSymbolTable != null)
            {
                labelUnique = !mSymbolTable.TryGetValue(trimLabel, out Symbol sym);

                // It's okay if this and the other are both variables.
                if (!labelUnique && IsVariable && sym.IsVariable)
                {
                    labelUnique = true;
                }
            }

            // Value must be blank, meaning "erase any earlier definition", or valid value.
            // (Hmm... don't currently have a way to specify "no symbol" in DefSymbol.)
            //if (!string.IsNullOrEmpty(valueTextBox.Text)) {
            bool valueValid = ParseValue(out int thisValue, out int unused5);
            //} else {
            //    valueValid = true;
            //}

            bool widthValid = true;
            int  thisWidth  = -1;

            if (IsConstant && !IsVariable)
            {
                // width field is ignored
            }
            else if (string.IsNullOrEmpty(VarWidth))
            {
                // blank field is okay if the width is optional
                widthValid = mIsWidthOptional;
            }
            else if (!Asm65.Number.TryParseInt(VarWidth, out thisWidth, out int unusedBase) ||
                     thisWidth < DefSymbol.MIN_WIDTH || thisWidth > DefSymbol.MAX_WIDTH ||
                     (IsVariable && thisWidth > MAX_VAR_WIDTH))
            {
                // All widths must be between 1 and 65536.  For a variable, the full thing must
                // fit on zero page, except on 65816 where a 16-bit access at $ff can extend
                // off the end of the direct page.
                //
                // We test the variable width here so that we highlight the "width limit" label,
                // rather than the "value range" label.
                widthValid = false;
            }

            bool valueRangeValid = true;

            if (IsVariable && valueValid && widthValid)
            {
                // $ff with width 1 is okay, $ff with width 2 is okay on 65816, width=3 is bad
                if (thisValue < 0 || thisValue + thisWidth > MAX_VAR_WIDTH)
                {
                    valueRangeValid = false;
                }
            }
            else if (IsAddress && valueValid)
            {
                // limit to positive 24-bit integers; use a long for value+width so we
                // don't get fooled by overflow
                long lvalue = thisValue;
                if (thisWidth > 0)
                {
                    lvalue += thisWidth - 1;
                }
                if (thisValue < 0 || lvalue > 0x00ffffff)
                {
                    valueRangeValid = false;
                }
            }

            Symbol.Type symbolType = IsConstant ? Symbol.Type.Constant : Symbol.Type.ExternalAddr;

            // For a variable, the value must also be unique within the table.  Values have
            // width, so we need to check for overlap.
            bool valueUniqueValid = true;

            if (IsVariable && valueValid && widthValid)
            {
                foreach (KeyValuePair <string, DefSymbol> kvp in mDefSymbolList)
                {
                    if (kvp.Value != mOrigSym &&
                        DefSymbol.CheckOverlap(kvp.Value, thisValue, thisWidth, symbolType))
                    {
                        valueUniqueValid = false;
                        break;
                    }
                }
            }

            bool rwValid = true;

            if (!IsVariable && IsAddress)
            {
                rwValid = IsReadChecked || IsWriteChecked;
            }

            labelNotesLabel.Foreground  = labelValid ? mDefaultLabelColor : Brushes.Red;
            labelUniqueLabel.Foreground = projectLabelUniqueLabel.Foreground =
                labelUnique ? mDefaultLabelColor : Brushes.Red;
            valueNotesLabel.Foreground     = valueValid ? mDefaultLabelColor : Brushes.Red;
            addrValueRangeLabel.Foreground = valueRangeValid ? mDefaultLabelColor : Brushes.Red;
            varValueRangeLabel.Foreground  = valueRangeValid ? mDefaultLabelColor : Brushes.Red;
            varValueUniqueLabel.Foreground = valueUniqueValid ? mDefaultLabelColor : Brushes.Red;
            widthNotesLabel.Foreground     = widthValid ? mDefaultLabelColor : Brushes.Red;
            checkReadWriteLabel.Foreground = rwValid ? mDefaultLabelColor : Brushes.Red;

            IsValid = labelValid && labelUnique && valueValid && valueRangeValid &&
                      valueUniqueValid && widthValid && rwValid;
        }
Example #12
0
        // get stock latest options chain
        public ArrayList GetOptionsChain(string ticker, Symbol.Type type)
        {
            // create options array list
            ArrayList options_list = new ArrayList();

            options_list.Clear();
            options_list.Capacity = 1024;

            string symbol = ticker.TrimStart(new char[] { '^', '~' }).ToLower();
            string url    = @"http://www.optionetics.com/marketdata/details.asp?symb=" + symbol.ToUpper() + "&page=chain";

            //XmlDocument doc = cap.DownloadXmlPartialWebPage(url, "<body", "</body>", 1, 1);
            //if (doc == null) return null;

            HtmlDocument html = wbf.GetHtmlDocumentWithWebBrowser(url, null, null, null, 60);

            if (html == null)
            {
                return(null);
            }

            XmlDocument doc = cap.ConvertHtmlToXml("<html>" + cap.GetPartialWebPage(html.Body.OuterHtml, "Options Expiration:", "</div>", 1, 1) + "</html>");

            if (doc == null)
            {
                return(null);
            }

            List <DateTime> exp_date_list = new List <DateTime>();
            List <XmlNode>  table_nd_list = new List <XmlNode>();

            XmlNode nd, table_nd;

            for (int i = 1; ; i++)
            {
                table_nd = prs.FindXmlNodeByName(doc.FirstChild, "TABLE", "class=chaintable", i);

                if (table_nd == null)
                {
                    break;
                }

                if (table_nd.PreviousSibling != null)
                {
                    DateTime exp_date;

                    if (DateTime.TryParse(System.Web.HttpUtility.HtmlDecode(table_nd.PreviousSibling.InnerText.Replace("Options Expiration:", "").Trim()), out exp_date))
                    {
                        exp_date_list.Add(exp_date.AddDays(1));
                        table_nd_list.Add(table_nd);
                    }
                }
            }

            for (int e = 0; e < table_nd_list.Count; e++)
            {
                // expiration
                DateTime exp_date = exp_date_list[e];

                for (int r = 3; ; r++)
                {
                    XmlNode row_nd = prs.GetXmlNodeByPath(table_nd_list[e], @"TBODY\TR(" + r.ToString() + @")");
                    if (row_nd == null)
                    {
                        break;
                    }

                    // strike
                    double strike;
                    nd = prs.GetXmlNodeByPath(row_nd, @"TD(7)");
                    if (nd == null || nd.InnerText == null ||
                        !double.TryParse(System.Web.HttpUtility.HtmlDecode(nd.InnerText.Trim()), out strike))
                    {
                        continue;
                    }

                    for (int i = 0; i < 2; i++)
                    {
                        try
                        {
                            Option option = new Option();

                            option.expiration = exp_date;
                            option.strike     = strike;

                            option.stock = ticker;
                            option.stocks_per_contract = 100;
                            option.type             = (i == 0) ? "Call" : "Put";
                            option.update_timestamp = DateTime.Now;

                            // symbol
                            option.symbol = null;
                            nd            = prs.GetXmlNodeByPath(row_nd, (i == 0) ? @"TD(1)\A" : @"TD(13)\A");
                            if (nd != null)
                            {
                                string[] split = System.Web.HttpUtility.HtmlDecode(nd.Attributes["href"].InnerText).Trim().Split(new char[] { '=', '&', '?' });
                                for (int k = 0; k < split.Length; k++)
                                {
                                    if (split[k] == "symbol" && (k + 1) < split.Length)
                                    {
                                        option.symbol = "." + split[k + 1].Replace("^", "");
                                        break;
                                    }
                                }
                            }
                            if (option.symbol == null)
                            {
                                continue;
                            }

                            // bid
                            option.price.bid = double.NaN;
                            nd = prs.GetXmlNodeByPath(row_nd, (i == 0) ? @"TD(5)" : @"TD(8)");
                            if (nd != null && nd.InnerText != null)
                            {
                                double.TryParse(System.Web.HttpUtility.HtmlDecode(nd.InnerText.Trim()), out option.price.bid);
                            }
                            if (option.price.bid == 0)
                            {
                                option.price.bid = double.NaN;
                            }

                            // ask
                            option.price.ask = double.NaN;
                            nd = prs.GetXmlNodeByPath(row_nd, (i == 0) ? @"TD(6)" : @"TD(9)");
                            if (nd != null && nd.InnerText != null)
                            {
                                double.TryParse(System.Web.HttpUtility.HtmlDecode(nd.InnerText.Trim()), out option.price.ask);
                            }
                            if (option.price.ask == 0)
                            {
                                option.price.ask = double.NaN;
                            }

                            // last
                            option.price.last = double.NaN;
                            nd = prs.GetXmlNodeByPath(row_nd, (i == 0) ? @"TD(4)" : @"TD(10)");
                            if (nd != null && nd.InnerText != null)
                            {
                                double.TryParse(System.Web.HttpUtility.HtmlDecode(nd.InnerText.Trim()), out option.price.last);
                            }
                            if (option.price.last == 0)
                            {
                                option.price.last = double.NaN;
                            }

                            option.price.change = double.NaN;

                            // volume
                            option.volume.total = double.NaN;
                            nd = prs.GetXmlNodeByPath(row_nd, (i == 0) ? @"TD(3)" : @"TD(11)");
                            if (nd != null && nd.InnerText != null)
                            {
                                double.TryParse(System.Web.HttpUtility.HtmlDecode(nd.InnerText.Trim()), out option.volume.total);
                            }

                            // open-int
                            option.open_int = 0;
                            nd = prs.GetXmlNodeByPath(row_nd, (i == 0) ? @"TD(2)" : @"TD(12)");
                            if (nd != null && nd.InnerText != null)
                            {
                                int.TryParse(System.Web.HttpUtility.HtmlDecode(nd.InnerText.Trim()), out option.open_int);
                            }

                            options_list.Add(option);
                        }
                        catch { }
                    }
                }
            }

            return(options_list);
        }
Example #13
0
        // get stock latest options chain
        public ArrayList GetOptionsChain(string ticker, Symbol.Type type)
        {
            // create options array list
            ArrayList options_list = new ArrayList();

            options_list.Clear();
            options_list.Capacity = 1024;

            string symbol = ticker.TrimStart(new char[] { '^', '~' }).ToLower();
            string url    = @"http://quote.morningstar.com/Option/Options.aspx?Ticker=" + symbol + @"&chnExpireDate[0]=";

            string page = cap.DownloadHtmlWebPage(url);

            string exp_list = GetJavaScriptVariable(page, "strExpireDateShort");
            string opt_list = GetJavaScriptVariable(page, "strOptions");

            if (exp_list == null || opt_list == null)
            {
                return(null);
            }

            string[] opt_list_split = opt_list.Split('~');
            string[] exp_list_split = exp_list.Split(',');

            for (int i = 0; i < exp_list_split.Length && i < opt_list_split.Length; i++)
            {
                string exp_str = exp_list_split[i].Trim();
                string opt_str = opt_list_split[i].Trim();

                if (exp_str == "" || opt_str == "")
                {
                    continue;
                }

                try
                {
                    int ed_d = int.Parse(exp_str.Substring(2, 2), ci);
                    int ed_m = int.Parse(exp_str.Substring(0, 2), ci);
                    int ed_y = int.Parse(exp_str.Substring(4, 4), ci);

                    DateTime exp_date = new DateTime(ed_y, ed_m, ed_d);

                    foreach (string opt_line in opt_str.Split('|'))
                    {
                        string[] split = opt_line.Trim().Split(',');

                        for (int j = 0; j < 2; j++)
                        {
                            int ofst = j * 10;

                            try
                            {
                                Option option = new Option();

                                option.expiration = exp_date;
                                if (!double.TryParse(split[0], NumberStyles.Number, ci, out option.strike))
                                {
                                    continue;
                                }

                                option.stock = ticker;
                                option.stocks_per_contract = 100;
                                option.type             = (j == 0) ? "Call" : "Put";
                                option.update_timestamp = DateTime.Now;

                                option.symbol = "." + split[2 + ofst];

                                if (!double.TryParse(split[3 + ofst], NumberStyles.Number, ci, out option.price.last))
                                {
                                    option.price.last = double.NaN;
                                }

                                if (!double.TryParse(split[4 + ofst], NumberStyles.Number, ci, out option.price.bid))
                                {
                                    option.price.bid = double.NaN;
                                }

                                if (!double.TryParse(split[5 + ofst], NumberStyles.Number, ci, out option.price.ask))
                                {
                                    option.price.ask = double.NaN;
                                }

                                if (!double.TryParse(split[8 + ofst], NumberStyles.Number, ci, out option.volume.total))
                                {
                                    option.volume.total = double.NaN;
                                }

                                if (!int.TryParse(split[9 + ofst], NumberStyles.Number, ci, out option.open_int))
                                {
                                    option.open_int = (int)option.volume.total;
                                }

                                options_list.Add(option);
                            }
                            catch { }
                        }
                    }
                }
                catch { }
            }

            return(options_list);
        }
Example #14
0
 /// <summary>
 /// Gets the symbol associated with the operand of an instruction.
 /// </summary>
 /// <param name="offset">Offset of start of instruction.</param>
 /// <param name="operandValue">Operand value.</param>
 /// <param name="type">Operand type.  Should be ExternalAddress for DP ops, or
 ///   Constant for StackRel ops.</param>
 /// <returns>Symbol, or null if no match found.</returns>
 public DefSymbol GetSymbol(int offset, int operandValue, Symbol.Type type)
 {
     AdvanceToOffset(offset);
     return(mCurrentTable.GetByValueRange(operandValue, 1, type));
 }
Example #15
0
        // get stock latest options chain
        public ArrayList GetOptionsChain(string ticker, Symbol.Type type)
        {
            string symbol_type;

            switch (type)
            {
            case Symbol.Type.Stock:
                symbol_type = "stock";
                break;

            case Symbol.Type.Index:
                symbol_type = "index";
                break;

            case Symbol.Type.Fund:
                symbol_type = "fund";
                break;

            case Symbol.Type.Future:
            case Symbol.Type.Unknown:
            default:
                return(null);
            }

            // create options array list
            ArrayList options_list = new ArrayList();

            options_list.Clear();
            options_list.Capacity = 1024;

            string symbol = ticker.TrimStart(new char[] { '^', '~' }).ToLower();
            string url    = @"http://www.marketwatch.com/investing/" + symbol_type + "/" + symbol + "/options?countrycode=US&showAll=True";

            string page = cap.DownloadHtmlWebPage(url);

            if (page == null)
            {
                return(null);
            }

            int xb = page.IndexOf("<table class=\"optiontable ");
            int xe = page.LastIndexOf("</table>");

            if (xb == -1 || xe < xb)
            {
                return(null);
            }

            string partial_page = page.Substring(xb, xe - xb) + "</table>";

            XmlDocument xml = cap.ConvertHtmlToXml(partial_page);

            if (xml == null)
            {
                return(null);
            }

            XmlNode table_nd = xml.FirstChild;

            if (table_nd == null)
            {
                return(null);
            }

            // expiration date & strike
            DateTime exp_date = DateTime.MinValue;
            double   strike   = double.NaN;

            for (int r = 1; ; r++)
            {
                XmlNode row_nd = prs.GetXmlNodeByPath(table_nd, @"tr(" + r + ")");
                if (row_nd == null)
                {
                    break;
                }

                try
                {
                    XmlNode tmp_nd = prs.GetXmlNodeByPath(row_nd, @"form\td\h4\a");

                    if (tmp_nd != null)
                    {
                        string row_text = tmp_nd.InnerText.Trim();

                        if (row_text.EndsWith("Options"))
                        {
                            string[] split = row_text.Replace(",", "").Split(' ');
#if (true)
                            if (DateTime.TryParse("1 " + split[0] + " " + split[1], ci, DateTimeStyles.None, out exp_date))
                            {
                                // get the day after the 3rd firday
                                int days_to_1st_friday = (int)DayOfWeek.Friday - (int)exp_date.DayOfWeek;
                                if (days_to_1st_friday < 0)
                                {
                                    days_to_1st_friday += 7;
                                }
                                exp_date = exp_date.AddDays(15 + days_to_1st_friday);
                            }
                            else
                            {
                                exp_date = DateTime.MinValue;
                            }
#else
                            DateTime.TryParse(split[2] + "-" + split[1] + "-" + split[3], ci, DateTimeStyles.None, out exp_date);
#endif
                            continue;
                        }
                    }

                    if (exp_date == DateTime.MinValue)
                    {
                        continue;
                    }

                    // strike price
                    XmlNode cell_nd = prs.GetXmlNodeByPath(row_nd, @"td(8)");
                    if (cell_nd == null || string.IsNullOrEmpty(cell_nd.InnerText))
                    {
                        continue;
                    }

                    string cell_text = cell_nd.InnerText.Trim();
                    if (!double.TryParse(cell_text, NumberStyles.Currency, ci, out strike))
                    {
                        continue;
                    }

                    for (int j = 0; j < 2; j++)
                    {
                        Option option = new Option();

                        option.stock               = ticker;
                        option.expiration          = exp_date;
                        option.strike              = strike;
                        option.stocks_per_contract = 100;
                        option.type = (j == 0) ? "Call" : "Put";

                        // symbol
                        cell_nd = prs.GetXmlNodeByPath(row_nd, @"td(" + (1 + j * 8) + ")");
                        if (cell_nd == null || cell_nd.InnerText == null || cell_nd.FirstChild == null)
                        {
                            continue;
                        }

                        option.symbol = "." + cell_nd.FirstChild.Attributes["title"].Value.Trim().ToUpper();
                        if (option.symbol == ".")
                        {
                            continue;
                        }

                        // last-price
                        cell_nd = prs.GetXmlNodeByPath(row_nd, @"td(" + (2 + j * 8) + ")");
                        if (cell_nd == null || cell_nd.InnerText == null)
                        {
                            continue;
                        }

                        if (!double.TryParse(cell_nd.InnerText.Trim(), NumberStyles.Number, ci, out option.price.last))
                        {
                            option.price.last = double.NaN;
                        }

                        // price-change
                        cell_nd = prs.GetXmlNodeByPath(row_nd, @"td(" + (3 + j * 8) + ")");
                        if (cell_nd == null || cell_nd.InnerText == null)
                        {
                            continue;
                        }

                        if (!double.TryParse(cell_nd.InnerText.Trim(), NumberStyles.Number, ci, out option.price.change))
                        {
                            option.price.change = 0;
                        }

                        // volume
                        cell_nd = prs.GetXmlNodeByPath(row_nd, @"td(" + (4 + j * 8) + ")");
                        if (cell_nd == null || cell_nd.InnerText == null)
                        {
                            continue;
                        }

                        if (!double.TryParse(cell_nd.InnerText.Trim(), NumberStyles.Number, ci, out option.volume.total))
                        {
                            option.volume.total = 0;
                        }

                        // bid-price
                        cell_nd = prs.GetXmlNodeByPath(row_nd, @"td(" + (5 + j * 8) + ")");
                        if (cell_nd == null || cell_nd.InnerText == null)
                        {
                            continue;
                        }

                        if (!double.TryParse(cell_nd.InnerText.Trim(), NumberStyles.Number, ci, out option.price.bid))
                        {
                            option.price.bid = double.NaN;
                        }

                        // ask-price
                        cell_nd = prs.GetXmlNodeByPath(row_nd, @"td(" + (6 + j * 8) + ")");
                        if (cell_nd == null || cell_nd.InnerText == null)
                        {
                            continue;
                        }

                        if (!double.TryParse(cell_nd.InnerText.Trim(), NumberStyles.Number, ci, out option.price.ask))
                        {
                            option.price.ask = double.NaN;
                        }

                        // open-int
                        cell_nd = prs.GetXmlNodeByPath(row_nd, @"td(" + (7 + j * 8) + ")");
                        if (cell_nd == null || cell_nd.InnerText == null)
                        {
                            continue;
                        }

                        if (!int.TryParse(cell_nd.InnerText.Trim(), NumberStyles.Number, ci, out option.open_int))
                        {
                            option.open_int = 0;
                        }

                        options_list.Add(option);
                    }
                }
                catch { }
            }

            return(options_list);
        }