天天看點

通過新浪股票接口 實作 Echarts K線圖

股票行情K線圖的效果 

通過新浪股票接口 實作 Echarts K線圖

找到一個好的接口很重要~~(之前自己搜羅的一個接口查回來的資料 JSON  key不帶引号 惡心的一匹 然後 資料也不是很好用,直接舍棄)

股票行情圖接口-日K曆史資料

請求

(1)url:{domainname}/stock/stockInformation/getBussinessLabelPoint   

POST

     Content-Type: application/json

        head:  key: headParam     value : {"device_no":"ios","devcie_name":"ios","token":"123","phone":"15202146557"}

(2)請求參數:

字段名 類型 說明
code String 股票編号

(3)請求body:

  {

"code":"600519"

  }

2.傳回

(1)傳回參數

字段名 類型 說明
status String 傳回接口狀态
msg String 傳回接口資訊
errorMsg String 傳回接口錯誤資訊
success boolean 傳回接口是否成功
result List<Object[]> [日期,昨收,開盤,當日最高,當日最低,目前價,成交量,成交額,買賣點]

(2)傳回body:

{

    "status": "200",

    "msg": "操作成功",

    "errorMsg": "",

    "result": [

        [

            "20180622",

            "759.32",

            "754.0",

            "767.0",

            "750.0",

            "767.0",

            "28854.0",

            "0",

            "0"

        ],

        [

            "20160104",

            "",

            "207.277",

            "207.277",

            "199.661",

            "200.0",

            "17349.0",

            "0",

            "0"

        ]

    ],

    "success": true

}

備注:{domainname}:https://www.desmart.com.cn:8443

請求之前可以先用Postman等類似的工具測試一下接口是否可以傳回正确的資料。

通過新浪股票接口 實作 Echarts K線圖

将Body和Headers中的參數設定好,資料成功傳回。

本來想在前端通路,但是因為ajax 存在跨越問題,不知道資料如何在前端拿過來,就在後端進行請求獲得資料。

我這裡用的是httpclent也可以用别的方式隻要請求傳回正确的資料就好。

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.TextFormat.ParseException;

@Controller
@RequestMapping("stockMarket")
public class stockMarketController {
	
	@RequestMapping(value="getdata")
	@ResponseBody
	public JSONArray resultData() throws ParseException, IOException {
		String body = doPostMethod();
		JSONObject jsonObject = JSONObject.parseObject(body);
		JSONArray jsonArray = jsonObject.getJSONArray("result");
		System.out.println(jsonArray);
		
		JSONArray jsonArray2 = new JSONArray();
		//從資料中截取
		for(int i=0;i<200;i++) {
			//周遊jsonArray數組,把每個對象轉成josn對象
			JSONArray jar = jsonArray.getJSONArray(i);
			jsonArray2.add(jar);
		}
		System.out.println("jsonArray2"+jsonArray2);
		
		//對資料進行逆向排序
		JSONArray newJsonArray = new JSONArray();
		for(int i = jsonArray2.size()-1;i>=0;i--) {
			JSONArray jar2 = jsonArray2.getJSONArray(i);
			newJsonArray.add(jar2);
		}
		
		return newJsonArray;
	}
	/**
	 * httpClient post 請求 
	 * @return
	 */
	public String doPostMethod() {
		String url = "https://www.desmart.com.cn:8443/stock/stockInformation/getBussinessLabelPoint";
		String param = "{\"code\":\"sh600000\"}";
                //建立client和post對象
		HttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		//json形式 headers參數
		post.addHeader("Content-Type", "application/json");
		post.addHeader("headParam","{\"device_no\":\"ios\",\"devcie_name\":\"ios\",\"token\":\"123\",\"phone\":\"15202146557\"}");
		//json字元串以實體的實行放到post中
		//body參數
		post.setEntity(new StringEntity(param,Charset.forName("utf-8")));
		HttpResponse response = null;
		try {
            //獲得response對象
			response = client.execute(post);
		} catch (Exception e) {
			e.printStackTrace();
		} 

		if(HttpStatus.SC_OK!=response.getStatusLine().getStatusCode()){
			System.out.println("請求傳回不正确");
		}

		String result="";
		try {
           //獲得字元串形式的結果
			result = EntityUtils.toString(response.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		} 
		System.out.println(result);
		return result;
	}
    
    
}
           

請求傳回的資料需要進行處理,使之與EchartsK線圖所需要的參數向對應。到這裡背景的工作也就完成了,剩下的就交給Echarts。

首先引入Echarts 這個官網有這裡就不再贅述。

通過新浪股票接口 實作 Echarts K線圖

Echarts K線圖demo中的參數

通過新浪股票接口 實作 Echarts K線圖

通過觀察發現這個數組中的資料似乎并不是都用到了,關鍵代碼如下。

var dates = rawData.map(function (item) {
    return item[0];
});

var data = rawData.map(function (item) {
    return [+item[1], +item[2], +item[5], +item[6]];
});
           

顯而易見 item[0]就是 資料中的date

通過效果圖的參數可以定位到open   close   lowest   highest 等關鍵參數而MA5 MA10 MA20 是通過基于這幾個參數計算而來的

通過新浪股票接口 實作 Echarts K線圖

明白了這一點 OK 把 擷取到的 資料與之對應即可,前端代碼:這部分是生成圖表的

function StockMarket(){
			$.ajax({
					url:"stockMarket/getdata",
					async: false,//設定為同步傳輸
					success:function(result){
					    // 基于準備好的dom,初始化echarts執行個體
       				 var myChart = echarts.init(document.getElementById('echats'));
					//app.title = '2015 年上證指數';
						//參數 順序 	日期				open	close						lowest   highest										

					function calculateMA(dayCount, data) {
					    var result = [];
					    for (var i = 0, len = data.length; i < len; i++) {
					        if (i < dayCount) {
					            result.push('-');
					            continue;
					        }
					        var sum = 0;
					        for (var j = 0; j < dayCount; j++) {
					            sum += data[i - j][1];
					        }
					        result.push(sum / dayCount);
					    }
					    return result;
					}

					var dates = result.map(function (item) {
 					    return item[0];
 					});

 					var data = result.map(function (item) {
 						//			open	close    lowest   highest
 					    return [+item[3], +item[2], +item[4], +item[5]];
 						//3245
 					});
					var option = {
							//整體背景色
					    backgroundColor: '#FFFFFF',
					    legend: {
					        data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30'],
					        inactiveColor: '#777',
					        textStyle: {
					            color: '#110000' //頭部顔色
					        }
					    },
					    tooltip: {
					        trigger: 'axis',
					        axisPointer: {
					            animation: false,
					            type: 'cross',
					            lineStyle: {
					                color: '#376df4',
					                width: 2,
					                opacity: 1
					            }
					        }
					    },
					    xAxis: {
					        type: 'category',
					        data: dates,
					        axisLine: { lineStyle: { color: '#8392A5' } }
					    },
					    yAxis: {
					        scale: true,
					        axisLine: { lineStyle: { color: '#8392A5' } },
					        splitLine: { show: false }
					    },
					    grid: {
					        bottom: 80
					    },
					    dataZoom: [{
					        textStyle: {
					            color: '#8392A5'
					        },
					        handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
					        handleSize: '80%',
					        dataBackground: {
					            areaStyle: {
					                color: '#8392A5'
					            },
					            lineStyle: {
					                opacity: 0.8,
					                color: '#8392A5'
					            }
					        },
					        handleStyle: {
					            color: '#fff',
					            shadowBlur: 3,
					            shadowColor: 'rgba(0, 0, 0, 0.6)',
					            shadowOffsetX: 2,
					            shadowOffsetY: 2
					        }
					    }, {
					        type: 'inside'
					    }],
					    animation: false,
					    series: [
					        {
					            type: 'candlestick',
					            name: '日K',
					            data: data,
					            itemStyle: {
					                normal: {
					                    color: '#FD1050',
					                    color0: '#0CF49B',
					                    borderColor: '#FD1050',
					                    borderColor0: '#110000'
					                }
					            }
					        },
					        {
					            name: 'MA5',
					            type: 'line',
					            data: calculateMA(5, data),
					            smooth: true,
					            showSymbol: false,
					            lineStyle: {
					                normal: {
					                    width: 1
					                }
					            }
					        },
					        {
					            name: 'MA10',
					            type: 'line',
					            data: calculateMA(10, data),
					            smooth: true,
					            showSymbol: false,
					            lineStyle: {
					                normal: {
					                    width: 1
					                }
					            }
					        },
					        {
					            name: 'MA20',
					            type: 'line',
					            data: calculateMA(20, data),
					            smooth: true,
					            showSymbol: false,
					            lineStyle: {
					                normal: {
					                    width: 1
					                }
					            }
					        },
					        {
					            name: 'MA30',
					            type: 'line',
					            data: calculateMA(30, data),
					            smooth: true,
					            showSymbol: false,
					            lineStyle: {
					                normal: {
					                    width: 1
					                }
					            }
					        }
					    ]
					};
					myChart.setOption(option);
					
					}//success結束		
				})
}
           

 var myChart = echarts.init(document.getElementById('echats'));

這段代碼的作用就是把圖表渲染到指定位置寫一個div 對應好id 即可。

<div id="echats"class="content"><!-- 行情圖展示位置 --></div>
           

OK,這樣就大功告成了,Echarts真的好用。