Exemplo n.º 1
0
        static public void Bind(string Symbol, Panel pnQuotes, Label lSymbol, Unit width,
                                Label lChangePercentChange, Label lVolume, Label lAverageDailyVolume, Label lDividendYield
                                )
        {
            if (lSymbol == null || lSymbol.Text != Symbol)
            {
                StringBuilder sb = new StringBuilder();
                foreach (Control c in pnQuotes.Controls)
                {
                    if (c is Label)
                    {
                        string s = (c as Label).ID.Substring(1);
                        if (htYahooMap.ContainsKey(s))
                        {
                            sb.Append((string)htYahooMap[s]);
                        }
                    }
                }

                string r = YahooDataManager.TryDownloadRealtimeFromYahoo(Symbol, sb.ToString());

                if (r != null)
                {
                    string[] rr = r.Trim().Split('\r');
                    if (rr.Length > 0)
                    {
                        BindData(rr[0], pnQuotes, lChangePercentChange, lVolume, lAverageDailyVolume, lDividendYield);
                    }
                }
            }
            pnQuotes.Width = width;
        }
Exemplo n.º 2
0
        protected void btnOK_Click(object sender, System.EventArgs e)
        {
            BindData();

            FormulaBase fb = FormulaBase.GetFormulaByName(CurrentFullName);

            foreach (string s in Request.Form)
            {
                if (s.StartsWith("__Param"))
                {
                    fb.SetParam(s.Substring(7), Request.Form[s]);
                }
            }

            YahooDataManager ydm = new YahooDataManager();

            ydm.CacheRoot = HttpRuntime.AppDomainAppPath + "Cache\\";
            CommonDataProvider DataProvider = (CommonDataProvider)ydm[tbCode.Text];

            FormulaChart fc = new FormulaChart();

            fc.AddArea("MAIN", 2);
            if (CurrentProgram.IsMainView)
            {
                fc[0].AddFormula(fb);
            }
            else
            {
                fc.AddArea(fb);
            }
            fc.LatestValueType = LatestValueType.StockOnly;

            fc.SetSkin(Config.DefaultSkin);

            try
            {
                fc.DataProvider = DataProvider;
                FormulaData fdDate = DataProvider["DATE"];
                string      s      = tbCode.Text;
                if (fdDate.Length > 0)
                {
                    s += " (" + DateTime.FromOADate(fdDate[fdDate.Length - 1]).ToString("yyyy-MMM-dd", DateTimeFormatInfo.InvariantInfo) + ")";
                }

                fc[0].Formulas[0].Name          = s;
                fc[0].Formulas[0].TextInvisible = false;
                fc.StartTime = DateTime.Now.AddMonths(-8);
                fc.EndTime   = DateTime.Now;
            }
            catch (Exception ee)
            {
                Bitmap   b = new Bitmap(640, 480);
                Graphics g = Graphics.FromImage(b);
                g.FillRectangle(Brushes.WhiteSmoke, 0, 0, 640, 480);
                g.DrawRectangle(Pens.Black, 0, 0, 639, 479);
                g.DrawString(ee.Message, new Font("verdana", 10), Brushes.Red, 1, 1);
            }

            lChart.Text = "<img src=ImageFromCache.aspx?CacheId=" + fc.SaveToImageStream(640, 400, ImageFormat.Png, 0, 0) + ">";
        }
Exemplo n.º 3
0
        public static void UpdateForNewSymbol(string Code, CommonDataProvider cdp, bool Save)
        {
            Utils.UpdateRealtime(Code, cdp);

            if (Save)
            {
                Impersonate.ChangeToAdmin();
                cdp.SaveBinary(GetHisDataFile(Code));
            }
            RefreshSymbolList();

            string[] ss = YahooDataManager.GetStockName(Code);
            if (ss.Length == 3)
            {
                try
                {
                    DB.DoCommand("insert into StockData (QuoteCode,QuoteName,Exchange) values (?,?,?)",
                                 new DbParam[] {
                        new DbParam("@Code", DbType.String, Code),
                        new DbParam("@Name", DbType.String, ss[1]),
                        new DbParam("@Exchange", DbType.String, ss[2]),
                    });
                }
                catch
                {
                }
            }
            cdp.SetStringData("Code", ss[0]);
            cdp.SetStringData("Name", ss[1]);
            cdp.SetStringData("Exchange", ss[2]);
        }
Exemplo n.º 4
0
 static public void SetYahooCacheRoot(IDataManager idm)
 {
     if (idm is YahooDataManager)
     {
         YahooDataManager ydm = idm as YahooDataManager;
         ydm.CacheRoot = HttpRuntime.AppDomainAppPath + "Cache\\";
     }
 }
Exemplo n.º 5
0
        private void btnOK_Click(object sender, System.EventArgs e)
        {
            //Create a Formula namespace
            FormulaSpace fms = new FormulaSpace("FML");

            //Create a Formula program , set Formula name and script code on the fly
            FormulaProgram fp = new FormulaProgram();

            fp.Name = tbFormulaName.Text;
            fp.Code = tbProgramScript.Text;

            //Add the script program to the Formula namespace
            fms.Programs.Add(fp);

            //Add parameters to Formula program
            for (int i = 1; i < 5; i++)
            {
                if (Request.Form["tbParamName" + i] != "")
                {
                    fp.Params.Add(new FormulaParam(
                                      Request.Form["tbParamName" + i],
                                      Request.Form["tbDefValue" + i],
                                      Request.Form["tbMinValue" + i],
                                      Request.Form["tbMaxValue" + i], FormulaParamType.Double));
                }
            }

            try
            {
                //Compile the Formula script on the fly
                Assembly    a  = fms.CompileInMemory();
                FormulaBase fb = FormulaBase.GetFormulaByName(a, fms.Name + "." + fp.Name);

                //Create YahooDataManager , Get stock data from yahoo.
                YahooDataManager ydm = new YahooDataManager();
                ydm.CacheRoot = HttpRuntime.AppDomainAppPath + "Cache\\";
                CommonDataProvider DataProvider = (CommonDataProvider)ydm[tbCode.Text];

                //Create financial chart instance
                FormulaChart fc = new FormulaChart();
                fc.PriceLabelFormat = "{CODE}";
                fc.LatestValueType  = LatestValueType.Custom;
                fc.AddArea("MAIN", 3);
                fc.AddArea(fb);
                fc.DataProvider = DataProvider;
                fc.SetSkin(Config.DefaultSkin);

                //Show the temp image just created
                lChart.Text = "<img src=ImageFromCache.aspx?CacheId=" + fc.SaveToImageStream(440, 440, ImageFormat.Png, 0, 0) + ">";
            }
            catch (FormulaErrorException fee)
            {
                //Show the compile result if the script has some errors
                lChart.Text = fee.ToHtml();
            }
        }
Exemplo n.º 6
0
        private void miUpdate_Click(object sender, EventArgs e)
        {
            YahooDataManager ydm = new YahooDataManager();

            ydm.CacheRoot = FormulaHelper.Root + "Cache";

            ChartForm.DataManager = ydm;
            string code = (string)dgList[dgList.CurrentRowIndex, 1];

            ChartForm.OpenChartForm(code, MainForm.MdiMainForm, true);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Load stock data from yahoo finance
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mmLoadFromYahoo_Click(object sender, System.EventArgs e)
        {
            string s = InputBox.ShowInputBox("Quote:", "MSFT");

            if (s != "")
            {
                YahooDataManager ydm = new YahooDataManager();
                ydm.CacheRoot            = FormulaHelper.Root + "Cache";
                ChartControl.DataManager = ydm;
                ChartControl.EndTime     = DateTime.MinValue;
                ChartControl.Symbol      = s;
            }
        }
Exemplo n.º 8
0
        //private YahooDataManager DataManager = new YahooDataManager();
        //https://medium.com/@daniel.sagita/backgroundservice-for-a-long-running-work-3debe8f8d25b
        protected override async Task ExecuteAsync(CancellationToken stopToken)
        {
            var DataManager = new YahooDataManager();

            //await DataManager.StartService();

            //Do your preparation (e.g. Start code) here
            while (!stopToken.IsCancellationRequested)
            {
                await DataManager.StartService();
            }
            //Do your cleanup (e.g. Stop code) here
        }
        private void menusubLoadYhoo_Click(object sender, System.EventArgs e)
        {
            string s = InputBox.ShowInputBox("Quote:", "^IXIC");

            if (s != "")
            {
                YahooDataManager ydm = new YahooDataManager();
                ydm.CacheRoot        = FormulaHelper.Root + "Cache";
                Designer.DataManager = ydm;
                Designer.EndTime     = DateTime.MinValue;
                Designer.Symbol      = s;
            }
        }
Exemplo n.º 10
0
        private void submnuYhoo_Click(object sender, System.EventArgs e)
        {
            string s = InputBox.ShowInputBox("Quote:", "FFIV");

            if (s != string.Empty)
            {
                YahooDataManager ydm = new YahooDataManager();
                ydm.CacheRoot        = FormulaHelper.Root + "Cache";
                Designer.DataManager = ydm;
                Designer.EndTime     = DateTime.MaxValue;
                Designer.Symbol      = s;
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Load data from yahoo, and start a streaming data thread to update current price.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miLoadFromYahooStreaming_Click(object sender, System.EventArgs e)
        {
            //Use yahoo data manager as inner data manager
            YahooDataManager ydm = new YahooDataManager();

            ydm.CacheRoot = FormulaHelper.Root + "Cache";

            //MemoryDataManager manage stock data in memory,
            //Use AddNewPacket to add streaming data packet to it.
            //Use RemoveSymbol to remove data from memory.
            //It takes an inner data manager, all historical data is from the inner data manager
            MemoryDataManager mdm = new MemoryDataManager(ydm);

            //Assign memory data manager to the chart control.
            string s = LoadDataManager(mdm, "MSFT", DataCycle.Day, 200);

            //Avoid flicker when refresh the chart
            ChartControl.MemoryCrossCursor = true;

            //Show 15 days future bar.
            ChartControl.EndTime = DateTime.Today.AddDays(15);
            //Show chart from 8 months ago.
            ChartControl.StartTime = DateTime.Today.AddMonths(-8);

            //You can use mdm.AddNewPacket to add a single bar
            //mdm.AddNewPacket(new DataPacket("MSFT",DateTime.Now,25,28,24,26,100000,26));

            //dcbStream is a DataClientBase class,
            //It will let you add streaming data to MemoryDataManager in a thread.
            if (dcbStream == null)
            {
                dcbStream = new YahooDataClient();
                //You can use other data client,
                //dcbStream = new ProphetDataClient();
                //dcbStream.Login("...","...");

                //When streaming packet arrive, call  dcb_OnStreamingData
                dcbStream.OnStreamingData += new StreamingDataChanged(dcb_OnStreamingData);
                dcbStream.UtcStreamingTime = false;

                //Start the download thread
                dcbStream.StartStreaming(s);
            }
            else
            {
                //SetStreamingSymbol will set symbol for downloading
                //You can use AddSymbol for multi-symbols downloading
                dcbStream.SetStreamingSymbol(s);
            }
        }
Exemplo n.º 12
0
        private void miQuickAdd_Click(object sender, EventArgs e)
        {
            string text1 = InputBox.ShowInputBox("Symbol", "");

            if (text1 != "")
            {
                if (StockDB.GetSymbol(text1) == null)
                {
                    string[] textArray1 = YahooDataManager.GetStockName(text1);
                    if (textArray1.Length == 3)
                    {
                        StockDB.LoadSymbolRow(text1, textArray1[1], textArray1[2]);
                        StockDB.RecreateFolders();
                        ListForm.Current.SymbolChanged = true;
                        ListForm.Current.RefreshList();
                    }
                }
            }
            ListForm.Current.GotoSymbol(text1);
        }
Exemplo n.º 13
0
        public override IDataProvider GetData(string Code, int Count)
        {
            CommonDataProvider cdp = (CommonDataProvider)htHistorical[Code];

            if (cdp == null)
            {
                YahooDataManager ydm = new YahooDataManager();
                ydm.StartTime      = this.StartTime;
                ydm.EndTime        = this.EndTime;
                ydm.CacheRoot      = FormulaHelper.Root + "Cache";
                cdp                = (CommonDataProvider)ydm[Code, Count];
                htHistorical[Code] = cdp;
            }
            DataPacket dp = (DataPacket)htPacket[Code];

            if (dp != null)
            {
                cdp.Merge(dp);
            }
            return(cdp);
        }
Exemplo n.º 14
0
        public static void UpdateDateAndOpenChartForm(string code, Form Owner, bool NewWindow)
        {
            YahooDataManager ydm = new YahooDataManager();

            ydm.CacheRoot = FormulaHelper.Root + "Cache";
            CommonDataProvider cdp = new CommonDataProvider(ydm);

            if (mCurrentChartForm == null || NewWindow)
            {
                mCurrentChartForm           = new ChartForm();
                mCurrentChartForm.MdiParent = Owner;
                mCurrentChartForm.Show();
                FormList.Add(mCurrentChartForm);
            }

            mCurrentChartForm.m_code = code;
            mCurrentChartForm.om.SaveObject(mCurrentChartForm.m_code);
            ((ChartWinControl)mCurrentChartForm.om.Canvas).ShowChart(cdp);
            mCurrentChartForm.Activate();
            mCurrentChartForm.om.LoadObject(code);
        }
Exemplo n.º 15
0
        static public void DownloadYahooHistory(string Symbol, bool Force, bool AddRealtime)
        {
            string FileName = DBDataManager.GetHisDataFile(Symbol);

            if (Force || !File.Exists(FileName))
            {
                DateTime           d    = DateTime.Now.AddDays(3);
                string             URL  = "http://table.finance.yahoo.com/table.csv?s={0}&d=" + (d.Month - 1) + "&e=" + d.Day + "&f=" + d.Year + "&g=d&a=6&b=30&c=" + Config.HistoricalDataYear + "&ignore=.csv";
                string             s    = string.Format(URL, Symbol);
                byte[]             bs   = DownloadData(s);
                CommonDataProvider cdpn = new YahooDataManager().LoadYahooCSV(bs);
                if (AddRealtime)
                {
                    cdpn.Merge(DataPacket.DownloadFromYahoo(Symbol));
                }
                UpdateRealtime(Symbol, cdpn);
                if (File.Exists(FileName))
                {
                    File.Delete(FileName);
                }
                cdpn.SaveBinary(FileName);
            }
        }
Exemplo n.º 16
0
        private void Bind()
        {
            Control tbSymbol = Parent.FindControl(symbolControl);

            if (tbSymbol is TextBox)
            {
                string Symbol = (tbSymbol as TextBox).Text;
                if (lSymbol.Text != Symbol)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (Control c in pnQuotes.Controls)
                    {
                        if (c is Label)
                        {
                            string s = (c as Label).ID.Substring(1);
                            if (htYahooMap.ContainsKey(s))
                            {
                                sb.Append((string)htYahooMap[s]);
                            }
                        }
                    }

                    string r = YahooDataManager.TryDownloadRealtimeFromYahoo(Symbol, sb.ToString());

                    if (r != null)
                    {
                        string[] rr = r.Trim().Split('\r');
                        if (rr.Length > 0)
                        {
                            BindData(rr[0]);
                        }
                    }
                }
            }
            pnQuotes.Width = width;
        }
Exemplo n.º 17
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            int    Height = 800;
            int    Width  = 600;
            Bitmap B;

            try
            {
                long Start = DateTime.Now.Ticks;

                ExchangeIntraday ei        = null;
                DateTime         StartTime = DateTime.Today.AddMonths(-6);
                DateTime         EndTime   = DateTime.Today;

                string Param = Request.QueryString["Span"];
                if (Param != null && Param != "")
                {
                    DataCycle dc;
                    if (Param.Length > 2)
                    {
                        dc = DataCycle.Parse(Param);
                    }
                    else
                    {
                        dc = new DataCycle(DataCycleBase.MONTH, Tools.ToIntDef(Param, 6));
                    }
                    StartTime = EndTime - dc;
                    //StartTime = EndTime.AddMonths(-Tools.ToIntDef(Param,6));
                }

                //Create financial chart instance
                FormulaChart fc = new FormulaChart();

                string Main = Request.QueryString["Main"];
                if (Main == null || Main == "")
                {
                    fc.AddArea("MAIN", 3);
                }
                else
                {
                    fc.AddArea(Main, 3);
                }

                string QuoteCode = Request.QueryString["Code"];
                if (QuoteCode == null)
                {
                    QuoteCode = "";
                }

                DataManagerBase dmb;
                Param = Request.QueryString["Provider"];
                if (Param == null)
                {
                    Param = "";
                }
                if (string.Compare(Param, "DB", true) == 0)
                {
                    //Create DBDataManager , Get stock data from sql server.
                    dmb = new DBDataManager();
                    ((DBDataManager)dmb).AutoYahooToDB =
                        Request.QueryString["His"] != "0" && Config.AutoYahooToDB == 1;
                    if (Request.QueryString["RT"] == "1")
                    {
                        ((DataManagerBase)dmb).DownloadRealTimeQuote = true;
                    }
                }
                else if (Param == "" || string.Compare(Param, "Yahoo", true) == 0)
                {
                    //Create YahooDataManager , Get stock data from yahoo.
                    dmb = new YahooDataManager();
                    ((YahooDataManager)dmb).CacheRoot = HttpRuntime.AppDomainAppPath + "Cache\\";
                    if (Config.IncludeTodayQuote == 1)
                    {
                        ((DataManagerBase)dmb).DownloadRealTimeQuote = true;
                    }
                }
                else
                {
                    string ManagerName = "WebDemos." + Param + "DataManager";
                    Type   t           = Type.GetType(ManagerName);
                    if (t == null)
                    {
                        throw new Exception(ManagerName + " not found!");
                    }
                    dmb = (DataManagerBase)Activator.CreateInstance(t);
                    if (dmb is IntraDataManagerBase)
                    {
                        ei = ExchangeIntraday.GetExchangeIntraday(Utils.GetExchange(QuoteCode));
                        ((CacheDataManagerBase)dmb).CacheTimeSpan = TimeSpan.FromMilliseconds(Config.IntradayCacheTime * 1000);
                        //((CacheDataManagerBase)dmb).EnableFileCache = false;

                        StartTime = ei.GetCurrentTradingDay();
                        EndTime   = StartTime.AddSeconds(3600 * 24 - 1);
                        QuoteCode = Utils.GetPart1(QuoteCode);
                    }
                    dmb.EndTime   = Utils.ToDateDef(Request.QueryString["End"], EndTime);
                    dmb.StartTime = Utils.ToDateDef(Request.QueryString["Start"], StartTime);
                }

                int MainIndex = 0;

                if (Config.SymbolCase == "Upper")
                {
                    QuoteCode = QuoteCode.ToUpper();
                }
                else if (Config.SymbolCase == "Lower")
                {
                    QuoteCode = QuoteCode.ToLower();
                }

                string[] QuoteCodes = QuoteCode.Split(',');
                string   Over       = "";
                QuoteCode = QuoteCodes[0];
                for (int i = 1; i < QuoteCodes.Length; i++)
                {
                    if (Over != "")
                    {
                        Over += ";";
                    }
                    Over += "Compare(" + QuoteCodes[i] + ")";
                }

                Param = Request.QueryString["IND"];
                string[] Inds = null;
                if (Param != null && Param != "")
                {
                    Inds = Param.Split(';');
                }

                //Set stock chart size
                Param = Request.QueryString["Size"];
                try
                {
                    if (Param != null && Param != "")
                    {
                        int i = Param.IndexOf('*');
                        if (i > 0)
                        {
                            Width  = int.Parse(Param.Substring(0, i));
                            Height = int.Parse(Param.Substring(i + 1));
                        }
                        else
                        {
                            Width  = int.Parse(Param);
                            Height = Width * 3 / 4;
                            if (Inds != null && Inds.Length > 1)
                            {
                                Height += Height / 5 * (Inds.Length - 2);
                            }
                            Height += 36;
                        }
                    }
                }
                catch
                {
                }

                CommonDataProvider DataProvider = (CommonDataProvider)dmb[QuoteCode];
                if (DataProvider == null)
                {
                    throw new Exception(QuoteCode + " not found!");
                }
                if (dmb is IntraDataManagerBase)
                {
                    fc.FixedTime = object.Equals(Request.QueryString["Fix"], "1");
                    if (fc.FixedTime)
                    {
                        DataProvider.IntradayInfo = ei;
                    }
                }

                if (DataProvider.Count == 0)
                {
                    throw new Exception("No data found!");
                }
                fc[MainIndex].Formulas[0].Name = QuoteCode;

                //Add MA lines to main stock view
                Param = Request.QueryString["MA"];
                if (Param != null && Param != "")
                {
                    foreach (string s in Param.Split(';'))
                    {
                        if (s != "")
                        {
                            fc[MainIndex].AddFormula("FML.MA(" + s + ")");
                        }
                    }
                }

                //Add EMA lines to main stock view
                Param = Request.QueryString["EMA"];
                if (Param != null && Param != "")
                {
                    foreach (string s in Param.Split(';'))
                    {
                        if (s != "")
                        {
                            fc[MainIndex].AddFormula("FML.EMA(" + s + ")");
                        }
                    }
                }

                //Add override lines to main stock view
                Param = Request.QueryString["OVER"];
                if (Param != null && Param != "")
                {
                    if (Over != "")
                    {
                        Param = Param + ";" + Over;
                    }
                }
                else
                {
                    Param = Over;
                }

                if (dmb is IntraDataManagerBase)
                {
                    string s = DataProvider.GetStringData("LastPrice");
                    if (s != null && s != "")
                    {
                        double d = double.Parse(s);
                        s = "DotLine(" + d.ToString("f2") + ")";
                        if (Param != null && Param != "")
                        {
                            Param += ";" + s;
                        }
                        else
                        {
                            Param = s;
                        }
                    }
                }

                if (Param != null && Param != "")
                {
                    //foreach(string s in Param.Split(';'))
                    string[] ss = Param.Split(';');
                    for (int i = 0; i < ss.Length; i++)
                    {
                        string s = ss[i].ToUpper();
                        if (s != "")
                        {
                            if (s == "AreaBB")
                            {
                                fc[MainIndex].InsertFormula(0, "FML." + s);
                            }
                            else
                            {
                                fc[MainIndex].AddFormula("FML." + s);
                            }
                        }
                    }
                }

                //Add indicators to stock chart
                if (Inds != null)
                {
                    foreach (string s in Inds)
                    {
                        if (s != "")
                        {
                            int k = s.IndexOf("{U}");
                            if (k > 0)
                            {
                                fc.InsertArea(MainIndex, "FML." + s.Substring(0, k));
                                MainIndex++;
                            }
                            else
                            {
                                fc.AddArea("FML." + s);
                            }
                        }
                    }
                }

                //Apply build-in stock chart skin
                Param = Request.QueryString["Skin"];
                if (Param == null || Param == "")
                {
                    Param = Config.DefaultSkin;
                }
                FormulaSkin fs = FormulaSkin.GetSkinByName(Param);
                if (fs != null)
                {
                    if (Config.YAxisFormat != "")
                    {
                        fs.AxisY.Format = Config.YAxisFormat;
                    }

                    if (Config.ShowXAxisInLastArea)
                    {
                        fs.ShowXAxisInLastArea = true;
                    }

                    fc.SetSkin(fs);
                }

                try
                {
                    fc.LatestValueType = (LatestValueType)Enum.Parse(typeof(LatestValueType), Config.LatestValueType, true);
                }
                catch
                {
                }

                //Add compare line to other stocks
                Param = Request.QueryString["COMP"];
                if (Param != null && Param != "")
                {
                    foreach (string s in Param.Split(';', ','))
                    {
                        if (s != "")
                        {
                            fc[MainIndex].AddFormula("COMPARE(" + s + ")");
                        }
                    }
                    fc[MainIndex].AxisY.ShowAsPercent = true;
                    fc[MainIndex].AxisY.Format        = "p1";
                    fc.LatestValueType = LatestValueType.None;
                }

                //Set stock chart time period
                fc.EndTime             = Utils.ToDateDef(Request.QueryString["End"], EndTime);
                fc.StartTime           = Utils.ToDateDef(Request.QueryString["Start"], StartTime);
                DataProvider.DataCycle = DataCycle.Parse(Request.QueryString["Cycle"]);

                //Set X-Axis format
                string XFormat = Request.QueryString["XFormat"];
                if (XFormat != null && XFormat != "")
                {
                    fc.AxisXFormat = XFormat;
                    fc.AllXFormats = null;
                }

                //Set Y-Axis format
                string YFormat = Request.QueryString["YFormat"];
                if (YFormat != null && YFormat != "")
                {
                    fc.AxisYFormat = YFormat;
                }

                //Set X-Axis cycle
                string XCycle = Request.QueryString["XCycle"];
                if (XCycle != null && XCycle != "")
                {
                    fc.DataCycle = DataCycle.Parse(XCycle);
                }

                //Set render type : Bar , Candle or Line
                Param = Request.QueryString["Type"];
                if (Param != null && Param != "")
                {
                    StockRenderType srt;
                    if (Param.Length == 1)
                    {
                        srt = (StockRenderType)int.Parse(Param);
                    }
                    else
                    {
                        srt = (StockRenderType)Enum.Parse(typeof(StockRenderType), Param, true);
                    }
                    fc[MainIndex].StockRenderType = srt;
                }

                //Set Scale type : Normal or Log
                Param = Request.QueryString["Scale"];
                if (Param != null && Param != "")
                {
                    ScaleType st;
                    if (Param.Length == 1)
                    {
                        st = (ScaleType)int.Parse(Param);
                    }
                    else
                    {
                        st = (ScaleType)Enum.Parse(typeof(ScaleType), Param, true);
                    }
                    fc[MainIndex].AxisY.Scale = st;
                }

                //Bottom margin
                Param = Request.QueryString["BMargin"];
                if (Param != null && Param != "")
                {
                    fc[MainIndex].BottomMargin = Tools.ToDoubleDef(Param, 0);
                }

                //Bind stock data
                fc.DataProvider = DataProvider;

                for (int i = 1; i < fc[MainIndex].FormulaDataArray.Count; i++)
                {
                    if (fc[MainIndex][i].ParentFormula.FormulaName.StartsWith("COMPARE"))
                    {
                        FormulaAxisY fay = fc[MainIndex].AddNewAxisY(AxisPos.Left);
                        FormulaData  fd  = fc[MainIndex][i];
                        fd.Transform  = Transform.Normal;
                        fd.AxisYIndex = 1;
                        break;
                    }
                }

                fc[MainIndex].AxisY.MajorTick.ShowLine = Config.ShowMainAreaLineY;
                fc[MainIndex].AxisX.MajorTick.ShowLine = Config.ShowMainAreaLineX;

                //Set indicator line width
                Param = Request.QueryString["Width"];
                if (Param != null && Param != "")
                {
                    float LineWidth = float.Parse(Param);
                    for (int i = 0; i < fc.Areas.Count; i++)
                    {
                        fc[i].LinePen.Width = LineWidth;
                    }
                }
                fc[MainIndex].AxisY.AutoMultiply = false;

                if (Request.QueryString["SV"] == "0")
                {
                    fc.ShowValueLabel = false;
                }
                fc.StickRenderType = Config.StickRenderType;

                Rectangle Rect = new Rectangle(0, 0, Width, Height);
                Param = Request.QueryString["Layout"];
                if (Param == null || Param == "")
                {
                    Param = "Default";
                }
                string[] Layouts = Param.Split(';', ',');
                Layout   L       = Layout.ParseString(Config.Read(Layouts[0] + "Layout", "ChartRect=(0,0,0,0)"), Rect);    //,DataProvider);
                for (int j = 1; j < Layouts.Length; j++)
                {
                    L.Merge(Layout.ParseString(Config.Read(Layouts[j] + "Layout", "ChartRect=(0,0,0,0)"), Rect));                //,DataProvider));
                }
                L.CompanyName = Config.CompanyName;
                L.URL         = Config.URL;
                L.StartTick   = Start;
                fc.Rect       = L.ChartRect;
                B             = fc.GetBitmap(Width, Height, fc.Rect);
                Graphics g = Graphics.FromImage(B);
                L.Render(g, Rect, fc);


                int X = Tools.ToIntDef(Request.QueryString["X"], 0);
                int Y = Tools.ToIntDef(Request.QueryString["Y"], 0);
                if (X > 0 && Y > 0)
                {
                    fc.Rect            = new Rectangle(0, 0, Width, Height);
                    fc.ShowCursorLabel = true;
                    fc.DrawCursor(g, X, Y);
                }
            }
            catch (Exception ex)
            {
                B = new Bitmap(Width, Height);
                Graphics g = Graphics.FromImage(B);

                g.Clear(Color.White);

                StringFormat sf = new StringFormat();
                sf.Alignment     = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;
                g.DrawString(ex.Message, new Font("Verdana", 12),
                             new SolidBrush(Color.FromArgb(196, Color.Black)), new Rectangle(0, 0, Width, Height), sf);
            }

            //Create stock image to Bitmap
            Response.ContentType = "Image/" + Config.ImageFormat;

            //Create chart stream
            MemoryStream ms = new MemoryStream();

            if (Config.ImageFormat == "Gif")
            {
                Type tQuantization = (Type)Application["Quantization"];
                if (tQuantization == null)
                {
                    Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies();
                    foreach (Assembly a in ass)
                    {
                        if (a.FullName.StartsWith("ImageQuantization"))
                        {
                            tQuantization = a.GetType("ImageQuantization.OctreeQuantizer");
                        }
                    }
                    Application["Quantization"] = tQuantization;
                }

                if (tQuantization != null)
                {
                    object[] os;
                    if (Config.TransparentColor.IsEmpty)
                    {
                        os = new object[] { B, ms, Config.GifColors }
                    }
                    ;
                    else
                    {
                        os = new object[] { B, ms, Config.GifColors, Config.TransparentColor }
                    };

                    tQuantization.InvokeMember("Save",
                                               BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, os);
                }

                if (ms.Length == 0)
                {
                    B.Save(ms, ImageFormat.Png);
                }
            }
            else if (Config.ImageFormat == "Png")
            {
                B.Save(ms, ImageFormat.Png);
            }
            else if (Config.ImageFormat == "Jpeg")
            {
                B.Save(ms, ImageFormat.Jpeg);
            }

            //Output the chart stream to web browser
            ms.WriteTo(Response.OutputStream);
        }
Exemplo n.º 18
0
        public override IDataProvider GetData(string Code, int Count)
        {
            Code = Code.Trim();
            Hashtable          htList = GetSymbolListHashtable();
            string             s      = (string)htList[Code];
            CommonDataProvider cdpn   = new CommonDataProvider(this);


            byte[]   bs = new byte[] {};
            string[] ss = null;

            if (s != null)
            {
                ss = s.Split(',');
                if (ss[3] != "")
                {
                    string r = (string)htList[ss[3]];
                    if (r != null)
                    {
                        ss = r.Split(',');
                    }
                }
                if (Count > 0)
                {
                    // Load data from file
                    bs = LoadHisDataFromFile(Code, Count * DataPacket.PacketByteSize);
                    if (DownloadRealTimeQuote)
                    {
                        try
                        {
                            DataPacket dp = DataPacket.DownloadFromYahoo(Code);

                            if (dp != null && !dp.IsZeroValue)
                            {
                                bs = CommonDataProvider.MergeOneQuote(bs, dp);
                            }
                        }
                        catch
                        {
                        }
                    }

                    cdpn.LoadByteBinary(bs);

                    // Update data from yahoo
                    if (AutoYahooToDB)
                    {
                        string   FileName = GetHisDataFile(Code);
                        DateTime d        = new DateTime(1900, 1, 1);
                        try
                        {
                            d = File.GetLastWriteTime(FileName);                            // GetLastAccessTime(FileName);
                        }
                        catch
                        {
                        }
                        DateTime d1 = DateTime.Now.Date;
                        DateTime d2 = d.Date;
                        TimeSpan ts = d1 - d2;
                        if (ts.TotalDays > 0)
                        {
                            YahooDataManager   ydm      = new YahooDataManager();
                            CommonDataProvider cdpDelta = (CommonDataProvider)ydm[Code, ts.Days + 5];
                            cdpDelta.Adjusted = false;
                            if (cdpDelta.Count > 0)
                            {
                                double[] dd1 = cdpDelta["DATE"];
                                double[] dd2 = cdpn["DATE"];
                                if (cdpn.Count == 0 || (int)dd2[dd2.Length - 1] < (int)dd1[dd1.Length - 1])
                                {
                                    cdpn.Merge(cdpDelta);
                                    Impersonate.ChangeToAdmin();
                                    Utils.UpdateRealtime(Code, cdpn);
                                }
                            }
                            cdpn.SaveBinary(FileName);
                        }
                    }
                }
            }
            else
            {
                try
                {
                    // Download data from yahoo
                    if (AutoYahooToDB)
                    {
                        YahooDataManager ydm = new YahooDataManager();
                        cdpn = (CommonDataProvider)ydm[Code];
                        if (cdpn.Count > 0)
                        {
                            UpdateForNewSymbol(Code, cdpn, true);
                        }
                        else
                        {
                            throw new Exception("Invalid Quote : " + Code);
                        }
                    }
                    else
                    {
                        cdpn.LoadByteBinary(bs);
                    }
                }
                catch (Exception e)
                {
                    Tools.Log(e.Message);
                    cdpn.LoadByteBinary(bs);
                }
            }
            //cdpn = TrimToEndTime(cdpn);

            cdpn.SetStringData("Code", Code);
            if (ss != null && ss.Length > 2)
            {
                cdpn.SetStringData("Code", ss[0]);
                cdpn.SetStringData("Name", ss[1]);
                cdpn.SetStringData("Exchange", ss[2]);
            }
            return(cdpn);
        }
Exemplo n.º 19
0
        protected void btnOK_Click(object sender, System.EventArgs e)
        {
            //Create a Formula namespace
            FormulaSpace fms = new FormulaSpace("FML");

            //Create a Formula program , set Formula name and script code on the fly
            FormulaProgram fp = new FormulaProgram();

            fp.Name = tbFormulaName.Text;
            fp.Code = tbProgramScript.Text;

            //Add the script program to the Formula namespace
            fms.Programs.Add(fp);

            //Add parameters to Formula program
            for (int i = 1; i < 5; i++)
            {
                if (Request.Form["tbParamName" + i] != "")
                {
                    fp.Params.Add(new FormulaParam(
                                      Request.Form["tbParamName" + i],
                                      float.Parse(Request.Form["tbDefValue" + i]),
                                      float.Parse(Request.Form["tbMinValue" + i]),
                                      float.Parse(Request.Form["tbMaxValue" + i])));
                }
            }

            try
            {
                //Compile the Formula script on the fly
                Assembly    a  = fms.CompileInMemory(HttpRuntime.BinDirectory);
                FormulaBase fb = FormulaBase.GetFormulaByName(a, fms.Name + "." + fp.Name);

                //Create YahooDataManager , Get stock data from yahoo.
                YahooDataManager ydm = new YahooDataManager();
                ydm.CacheRoot = HttpRuntime.AppDomainAppPath + "Cache\\";
                CommonDataProvider DataProvider = (CommonDataProvider)ydm[tbCode.Text];

                //Create financial chart instance
                FormulaChart fc = new FormulaChart();
                fc.AddArea("MAIN", 3);
                fc.AddArea(fb);
                fc.DataProvider = DataProvider;
                fc.SetSkin(Config.DefaultSkin);


                //Show the temp image just created
                lChart.Text = "<img src=ImageFromCache.aspx?CacheId=" + fc.SaveToImageStream(440, 440, ImageFormat.Png, 0, 0) + ">";
            }
            catch (FormulaErrorException fee)
            {
                //Show the compile result if the script has some errors
                lChart.Text = "<font color=red>";
                foreach (System.CodeDom.Compiler.CompilerError ce in fee.ces)
                {
                    FormulaProgram fpa = fms.GetProgramByLineNum(ce.Line);
                    if (fpa != null)
                    {
                        fpa.AdjustErrors(ce);
                        lChart.Text += string.Format("Name:{0} line:{1} column:{2} error:{3} {4}<br>", fpa.Name, ce.Line, ce.Column, ce.ErrorNumber, ce.ErrorText);
                    }
                }
                lChart.Text += "</font>";
            }
        }