This article is a mirror article of machine translation, please click here to jump to the original article.

View: 23205|Reply: 6

[ASP.NET] Highcharts combines Asp.net to realize dynamic data stock graph display examples

[Copy link]
Posted on 6/28/2015 12:06:24 AM | | | |

The specific application market for this example is that I need to read the price of a commodity from the database regularly, and then display it on the web page as a graph, similar to the price trend chart of trading instruments in stocks.

I use asp.net, combined with the Highcharts plugin implementation in jQuery, the plugin can support many types of graphics, but they are static, and the examples provided need to be transformed, interested friends can go to the Highcharts official website to see (http://www.highcharts.com/), which provides a lot of demos, to be honest, to realize my needs, I should use Highstock, However, after looking at the dynamic-update example of Highcharts, I can also realize that my requirements interface is more concise, so this article uses the dynamic-update model in Highcharts, and the graphics type is spline. The final effect map is as follows (the price of Pinqijin is updated every 10 seconds, and a point is added to the line graph every 10 seconds):

Achieve step gathering:

Create a new website with VS and create a asp.net page DynamicUpdate.aspx, the page code is as follows:


  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicUpdate.aspx.cs"
  2.     Inherits="WebImg.DynamicUpdate" %>

  3. <!DOCTYPE HTML>
  4. <html>
  5. <head>
  6.     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  7.     <title>动态显示价格图例</title>
  8.     <scrip去掉t type="text/javascrip去掉t" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></scrip去掉t>
  9.     <scrip去掉t type="text/javascrip去掉t">
  10.    $(function () {
  11.        $(document).ready(function () {
  12.            Highcharts.setOptions({
  13.                global: {
  14.                    useUTC: false
  15.                }
  16.            });
  17.            var chart;
  18.            chart = new Highcharts.Chart({
  19.                chart: {
  20.                    renderTo: 'container',
  21.                    type: 'spline',
  22.                    marginRight: 10,
  23.                    events: {
  24.                    load: function () {
  25.                    // set up the updating of the chart each second
  26.                    var series = this.series[0];
  27.                    setInterval(function () {
  28.                                   var randomCode = parseInt(Math.random() * 10000);
  29.                                   var oldrandomCode = parseInt(Math.random() * 10000);
  30.                                   $.ajax({
  31.                                     url: "ajaxhandler/dataupdate.ashx?" + randomCode + "=" + oldrandomCode + "&flag=1",
  32.                                     type: "get",
  33.                                     dataType: "json",
  34.                                     success: function (data, textStatus, XMLHttpRequest) {
  35.                                         var ctime = new Date();
  36.                                         ctime.setTime(parseInt(data.rows[0].times));
  37.                                         var x = ctime.getTime(), // current time
  38.                                         y = data.rows[0].price * 200;
  39.                                         series.addPoint([x, y], true, true);
  40.                                     },
  41.                                     error: function () { }
  42.                                    });
  43.                    }, 10000);
  44.                    }
  45.                }
  46.            },
  47.            title: {
  48.                text: '品旗撮合交易市场品种行情'
  49.            },
  50.            xAxis: {
  51.                         title: {
  52.                                 text: '时间'
  53.                             },
  54.                type: 'datetime',
  55.                tickPixelInterval: 150,
  56.                         labels:{formatter:function(){
  57.                             var vDate = new Date(this.value);
  58.                             return vDate.getHours()+":"+vDate.getMinutes()+":"+vDate.getSeconds();
  59.                         }}
  60.            },
  61.            yAxis: {
  62.                title: {
  63.                    text: '价格'
  64.                },
  65.                plotLines: [{
  66.                    value: 0,
  67.                    width: 1,
  68.                    color: '#808080'
  69.                }]
  70.            },
  71.            tooltip: {
  72.                formatter: function () {
  73.                    return '<b>' + this.series.name + '</b><br/>' +
  74.                         Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
  75.                         Highcharts.numberFormat(this.y, 2);
  76.                }
  77.            },
  78.            legend: {
  79.                enabled: false
  80.            },
  81.            exporting: {
  82.                enabled: false
  83.            },
  84.                     credits:{
  85.                         text:'品旗金属交易市场',
  86.                         url:'http://www.inv6.com'
  87.                     },
  88.            series: [{
  89.                name: '品旗金(GOLD)',
  90.                data: (function () {
  91.                    var data = [],
  92.                             i;
  93.                             var jsonData = <%= jsonstr %>;
  94.                    for (i = -19; i <= 0; i++) {
  95.                                 var ctime = new Date();
  96.                                 ctime.setTime(parseInt(jsonData.rows[i+19].time1));
  97.                        data.push({
  98.                             x: ctime.getTime(),
  99.                                      y: jsonData.rows[i + 19].price * 200
  100.                        });
  101.                    }
  102.                    return data;
  103.                })()
  104.            }]
  105.        });
  106.    });
  107. });
  108.     </scrip去掉t>
  109. </head>
  110. <body>
  111.     <scrip去掉t src="http://code.highcharts.com/highcharts.js"></scrip去掉t>
  112.     <scrip去掉t src="http://code.highcharts.com/modules/exporting.js"></scrip去掉t>
  113.     <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto">
  114.     </div>
  115. </body>
  116. </html>
Copy code

Highcharts property renderTo indicates display containers,

events represents the event that the container needs to register, where load means that it occurs after the loading is completed, here a js timer is set in the load, which occurs once every 10 seconds, and the code in it is to request the latest GOLD from the dataupdate.ashx file of the ajaxhandler folder in the same root directory as the DynamicUpdate.aspx page through ajax in jQuery The price data of the variety, here is why I add randomCode + "=" + oldrandomCode in the ajax URL because adding a random number can avoid caching, and flag=1 is because my dataupdate.ashx file wants to accept multiple requests from different ajax, so use flag to distinguish it

xAxis represents the collection of attributes defined for the x-axis of the container, type represents the displayed text type, optional, here I fill in the time type, here note that the default for the instance is GMT time, you can also use UTC time, but we generally use Beijing time, (GMT or UTC) + 8 hours = Beijing time, so when we use ajax to get the time is Beijing time, we should subtract 8 hours from the hour (here I also want to share an experience, How to convert server time to js time that can be used by the .getTime() method, that is, subtract the server time from 1970-1-1, convert the remaining days to milliseconds, and then assign a value to the newly initialized time through the setTime method in js, I found that the result obtained by getTime() is incorrect to initialize a js time directly in js in the form of new Date (year, month, day, hour, minute, second, millisecond) with getTime(), As for why 1970-1-1 is subtracted, it is because the definition of the getTime() method is to get the number of milliseconds from the current time from 1970-1-1), when the x-axis is not displayed as a time or you need to define it yourself, it can also be defined by the categories attribute, tickPixelInterval represents the density of the x-axis, and labels is used to format the display format of the x-axis

yAxis represents a collection of attributes defined for the y-axis of the container, which is roughly the same as the attributes of the x-axis, but in Highcharts it is not possible to define the fixed value of the y-axis through categories, the y-axis of Highcharts is automatically generated based on the given coordinate point data, which depends on the data sub-attribute of the series attribute, for example, when you assign a value to data The maximum value is 300, and the minimum value is 100. Then the display of the y-axis will be between 100 and 300, or you can also set the max or min attribute of yAxis

series represents the collection of all curves displayed in the container, here I only show one curve, name represents the name of the curve, data represents the collection of a series of coordinate points of the curve, x is in front, y is behind, it is a js array, in this case, because the x-axis shows time, so the x property of the array object must be set to time, but in Highcharts it is not directly assigned time to the x-axis, Instead, the number of milliseconds between 1970-1-1 and a certain time is assigned to the x-axis to represent this time, so the getTime() method must be used, the form of the y-axis coordinate point must be y = small number * integer form, and I didn't understand why Highcharts had to do this, because the price data of the variety in this example is generally about the same, so I had to divide by 200 when obtaining the data, and then multiply by 200 when assigning a value to the y-axis.


<%= jsonstr %> in the page code is the initial data I need to get from the server to initialize the graph, the cs generation of the page


  1. public string jsonstr = "";
  2.         protected void Page_Load(object sender, EventArgs e)
  3.         {
  4.             getData();
  5.         }
  6.         private void getData()
  7.         {
  8.             DataTable dtPrice = SQLDBHelper.ExecuteTable("select top 20 TMPCode,TMPTime,TMPPrice from TabMerPrice with(nolock) order by TMPTime desc");
  9.             string json = "{"rows":[";
  10.             for (int i = (dtPrice.Rows.Count-1); i >= 0; i--)
  11.             {
  12.                 json += "{"time1":"" + (Convert.ToDateTime(dtPrice.Rows[i]["TMPTime"]).AddHours(-8) - new DateTime(1970, 1, 1)).TotalMilliseconds + "","price":"" + (Convert.ToDecimal(dtPrice.Rows[i]["TMPPrice"])/200) + ""},";
  13.             }
  14.             json = json.TrimEnd(',');
  15.             json += "]}";
  16.             jsonstr = json;
  17.         }
Copy code

Among them, the TabMerPrice table is the variety price information table, TMPTime time, TMPPrice price, TMPTime time interval is ten seconds, I use a database job to generate the record of the table, which happens once every ten seconds

AddHours(-8) is to convert the time to Beijing time, and the generated data format is json format

The dataupdate.ashx code looks like this:


  1. public void ProcessRequest(HttpContext context)
  2.         {
  3.             string flag = context.Request.QueryString["flag"].ToString();
  4.             switch (flag)
  5.             {
  6.                 case "1"://获取品种当前价格
  7.                     GetMerPrice(context);
  8.                     break;
  9.             }
  10.         }
  11.         private void GetMerPrice(HttpContext context)
  12.         {
  13.             context.Response.Clear();
  14.             context.Response.Buffer = true;
  15.             context.Response.ContentType = "application/json";
  16.             context.Response.ContentEncoding.GetBytes("utf-8");
  17.             DataTable dtPrice = SQLDBHelper.ExecuteTable("select top 1 TMPCode,TMPTime,TMPPrice from TabMerPrice with(nolock) order by TMPTime desc");
  18.             string json = "{"rows":[";
  19.             json += "{"times":"" + (Convert.ToDateTime(dtPrice.Rows[0]["TMPTime"]).AddHours(-8) - new DateTime(1970, 1, 1)).TotalMilliseconds + "","price":"" + (Convert.ToDecimal(dtPrice.Rows[0]["TMPPrice"]) / 200) + ""}";
  20.             json = json.TrimEnd(',');
  21.             json += "]}";
  22.             context.Response.Write(json);
  23.             context.Response.Flush();
  24.             context.Response.End();
  25.         }
Copy code

This is the rough implementation of step aggregation, which can realize the real-time display of server-side data with a graph similar to the stock format


HighCharts演示.zip (48.69 KB, Number of downloads: 1)


Score

Number of participants1MB+1 contribute+1 Collapse reason
Male god congratulations + 1 + 1 Can the landlord give me a contact information, it helps a lot

See all ratings





Previous:How to get into developer mode for Android 4.4.x
Next:Based on Sina@ function simple example
Posted on 6/28/2015 10:34:21 AM |
This post was last edited by microxdd on 2015-6-28 10:35

Stitching strings is the most wasteful of performance and can be used with StringBuilder. However, it is recommended to use JSON serialization, which can directly convert objects into JSON strings. It can also be deserialized
Recommend Baidu icon library http://echarts.baidu.com/doc/example.html
 Landlord| Posted on 6/28/2015 10:54:45 AM |
microxdd posted on 2015-6-28 10:34
Stitching strings is the most wasteful of performance and can be used with StringBuilder. However, it is recommended to use JSON serialization, which can directly convert objects into ...

The advantage of json is that it is a divine horse? I've only heard of this thing
Posted on 6/28/2015 4:02:07 PM |
Published on 2015-6-28 10:54
The advantage of json is that it is a divine horse? I've only heard of this thing

JSON is a data format that is language agnostic
Posted on 6/28/2015 4:03:36 PM |
Delver_Si Posted on 2015-6-28 16:02
JSON is a data format that is language agnostic

Directly transfer the data required by JS from the background in JSON format, how to deal with JS
 Landlord| Posted on 6/28/2015 5:33:24 PM |
Delver_Si Posted on 2015-6-28 16:03
Directly transfer the data required by JS from the background in JSON format, how to deal with JS

Learning
Posted on 6/29/2015 6:56:59 PM |
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com