asp.net 制作K线图——highstock

highcharts是一款非常不错的开源的js绘图工具,我们所需要做的就是用他能听懂的语言告诉他怎么做,剩下的事情就交给highcharts了。

废话不多说步入正题。

1.从highcharts官网下载Highstock.js

2.在自己的网站引用jquery.min.js和highstock.js(jquery.min.js要放在highstock前面)

3.前台网站代码编写,直接贴代码

<head runat="server">
    <title>
        股票走势图
    </title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="js/jquery.min.js">
    </script>
    <script type="text/javascript" src="js/highstock.js">
    </script>
    <script type="text/javascript">
        $(function() {
            //官方例子获取json数据地址(经常无法访问)
            //http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=?
            $.getJSON('JsonData/StockData.ashx?callback=?', //通过后台获取数据库中股票phlc数据
            function(data) {

                //把获取的数据放入ohlc 中
                var ohlc = [],
                volume = [],
                avg5 = [],
                avg10 = [],
                avg20 = [],
                dataLength = data.length;

                for (i = 20; i < dataLength; i++) {
                    ohlc.push([data[i][0], // the date
                    data[i][1], // open
                    data[i][2], // high
                    data[i][3], // low
                    data[i][4] // close
                    ]);
                    //5日均线
                    var temp5 = (parseFloat(data[i][4]) + parseFloat(data[i - 1][4]) + parseFloat(data[i - 2][4]) + parseFloat(data[i - 3][4]) + parseFloat(data[i - 4][4])) / 5;
                    avg5.push([data[i][0], temp5]);
                    //10日均线
                    var temp10 = (parseFloat(data[i][4]) + parseFloat(data[i - 1][4]) + parseFloat(data[i - 2][4]) + parseFloat(data[i - 3][4]) + parseFloat(data[i - 4][4]) + parseFloat(data[i - 5][4]) + parseFloat(data[i - 6][4]) + parseFloat(data[i - 7][4]) + parseFloat(data[i - 8][4]) + parseFloat(data[i - 9][4])) / 10;
                    avg10.push([data[i][0], temp10]);
                    //20日均线
                    var temp20 = (parseFloat(data[i][4]) + parseFloat(data[i - 1][4]) + parseFloat(data[i - 2][4]) + parseFloat(data[i - 3][4]) + parseFloat(data[i - 4][4]) + parseFloat(data[i - 5][4]) + parseFloat(data[i - 6][4]) + parseFloat(data[i - 7][4]) + parseFloat(data[i - 8][4]) + parseFloat(data[i - 9][4]) + parseFloat(data[i - 10][4]) + parseFloat(data[i - 11][4]) + parseFloat(data[i - 12][4]) + parseFloat(data[i - 13][4]) + parseFloat(data[i - 14][4]) + parseFloat(data[i - 15][4]) + parseFloat(data[i - 16][4]) + parseFloat(data[i - 17][4]) + parseFloat(data[i - 18][4]) + parseFloat(data[i - 19][4])) / 20;
                    avg20.push([data[i][0], temp20]);
                    //volume
                    volume.push([data[i][0], // 日期
                    data[i][5] // volume
                    ])
                }

                // 创建图表
                $('#container').highcharts('StockChart',
                /**
                * 域选择配置
                * 
                * @param {array} buttons 缩放选择按钮
                * @param {int} selected 默认选择缩放按钮中的第几个
                * @param {boolean} inputEnabled 是否允许input标签选框
                */
                rangeSelector: {
                    // 缩放选择按钮,是一个数组。
                    // 其中type可以是: 'millisecond', 'second', 'minute', 'day', 'week', 'month', 'ytd' (year to date), 'year' 和 'all'。
                    // 其中count是指多少个单位type。
                    // 其中text是配置显示在按钮上的文字
                    buttons: [{
                        type: 'year',
                        count: 1,
                        text: '1年'
                    }],
                    // 默认选择域:0(缩放按钮中的第一个)、1(缩放按钮中的第二个)……
                    selected: 1,
                    enabled: false
                    // 是否允许input标签选框
                    // inputEnabled: false
                },
                navigator: {
                    enabled: true
                },

                /**
                    * X轴坐标配置
                    * 
                    * @param {object} dateTimeLabelFormats x轴日期时间格式化,不用修改直接使用
                    */
                xAxis: {
                    // 如果X轴刻度是日期或时间,该配置是格式化日期及时间显示格式
                    dateTimeLabelFormats: {
                        second: '%Y-%m-%d %H:%M:%S',
                        minute: '%Y-%m-%d %H:%M',
                        hour: '%Y-%m-%d %H:%M',
                        day: '%Y-%m',
                        week: '%Y-%m',
                        month: '%Y-%m',
                        year: '%Y'
                    }
                },
                credits: {
                    text: 'xxx公司',
                    href: 'http://xxxxx.com'
                },

                title: {
                    align: 'left',
                    text: 'xxx股票'
                },

                yAxis: [{
                    title: {
                        text: 'OHLC'
                    },
                    height: 200,
                    lineWidth: 1
                },
                {
                    title: {
                        text: 'Volume'
                    },
                    top: 290,
                    height: 100,
                    offset: 0,
                    lineWidth: 1
                }],

                /**
                        * 气泡示说明标签
                        * 
                        * @param {string} xDateFormat 日期时间格式化
                        */
                tooltip: {
                    valueDecimals: 2,
                    useHTML: true,
                    formatter: function() {
                        var s = '<b>' + Highcharts.dateFormat('%Y-%m-%d', this.x) + '</b><br/>';
                        s += '开盘价:' + this.points[0].point.open + '<br/>最高价:' + this.points[0].point.high + '<br/>最低价:' + this.points[0].point.low + '<br/>收盘价:' + this.points[0].point.close + '<br/>市值:' + this.points[1].y + '<br/><font color="' + this.points[2].series.color + '">MA5:' + Math.round(this.points[2].y * 100) / 100 + '</font>' + '<br/><font color="' + this.points[3].series.color + '">MA5:' + Math.round(this.points[3].y * 100) / 100 + '</font>' + '<br/><font color="' + this.points[4].series.color + '">MA5:' + Math.round(this.points[4].y * 100) / 100 + '</font>';

                        return s;
                    }
                },
                chart: {
                    height: 500
                    //width: 100%
                },
                exporting: {
                    url: 'http://127.0.0.1:2415/ExportServer.aspx'
                },
                plotOptions: {
                    candlestick: {
                        color: 'green',
                        upColor: 'red',
                        lineColor: 'green',
                        upLineColor: 'red'
                    },
                    column: {
                        colorByPoint: false
                    }

                },

                series: [{
                    type: 'candlestick',
                    name: 'AAPL',
                    data: ohlc
                    //                           dataGrouping: {
                    //                               units: groupingUnits
                    //                           }
                },
                {
                    type: 'column',
                    name: 'Volume',
                    data: volume,

                    yAxis: 1
                                            dataGrouping: {
                                                units: groupingUnits
                                            }
                },
                {
                    name: 'MA5',
                    data: avg5,
                    type: 'spline',
                    threshold: null,
                    tooltip: {
                        valueDecimals: 2
                    }
                },
                {
                    name: 'MA10',
                    data: avg10,
                    type: 'spline',
                    threshold: null,
                    tooltip: {
                        valueDecimals: 2
                    }
                },
                {
                    name: 'MA20',
                    data: avg20,
                    type: 'spline',
                    threshold: null,
                    tooltip: {
                        valueDecimals: 2
                    }
                }]
            });
        });
    });
    </script>
    <script type="text/javascript">
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div id="test">
            </div>
            <div id="container" style="height: 100%; width: 100%">
            </div>
        </div>
    </form>
</body>

4.后台数据获取

新建一个axsh文件

代码如下

using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

using System.Web.Script.Serialization;
using System.Text;
namespace HighCharts_test.JsonData
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class StockData : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/javascript";
            string callback = context.Request.QueryString["callback"];

            StringBuilder json = new StringBuilder();
            json.Append(callback);
           
            DataSet ds = GetStockData("600379");
            json.Append(DataSetToJson(ds));
            
            //json = serializer.Serialize(ds);
            context.Response.Write(json);
            
        }
        public string GetUNIX(string dateTimeString)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            DateTime dtNow = DateTime.Parse(dateTimeString);
            TimeSpan toNow = dtNow.Subtract(dtStart);
            string timeStamp = toNow.Ticks.ToString();
            timeStamp = timeStamp.Substring(0, timeStamp.Length - 4);
            return timeStamp;
        }
        /// <summary>
        /// 将DataSet转化成JSON数据
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public StringBuilder DataSetToJson(DataSet ds)
        {
            string json = string.Empty;
            try
            {
                if (ds.Tables.Count == 0)
                    throw new Exception("DataSet中Tables为0");
                json = "([";
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    json += "[";
                    for (int n = 0; n < ds.Tables[0].Columns.Count; n++)
                    {
                        if (n==0)
                        {
                            json +=GetUNIX( ds.Tables[0].Rows[i][n].ToString()) + ",";
                        }
                        else
                        {
                            json += ds.Tables[0].Rows[i][n].ToString() + ",";
                        }
                    }
                    json = json.Substring(0, json.Length - 1);
                    
                    json += "],";
                   
                }
                json = json.Substring(0, json.Length - 1);
                json += "]);";
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            StringBuilder sb = new StringBuilder();
            sb.Append(json);
            return sb;
        } 
        
        public DataSet GetStockData(string stockId)
        {
            //string sql = "select Cdate,KPJ,ZGJ,ZDJ,SPJ,JYL from CompanyStockDate where StockId=" + stockId + " and Cdate>=DATEADD(YY,-1,GETDATE()) order by Cdate asc";
            string sql = "select Cdate,KPJ,ZGJ,ZDJ,SPJ,JYL from CompanyStockDate where StockId=" + stockId + " and Cdate>=DATEADD(m,-3,GETDATE()) order by Cdate asc";
            DataSet ds = SqlHelper.Query(sql);
            return ds;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
效果如下



  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值