從新浪獲得股票和股指最新行情(.NET版),最新行情.net
使用CTP開發股指期貨期權的程序化交易系統中,經常會用到股指的當前點數和最收盤,為了使程序能夠自動獲得,需要通過網絡查詢。
目前除了使用Python進行爬蟲獲取外還可以通過新浪提供的JS行情服務器獲得,本文采用的是後者。
1、查詢股指一般返回的含有以下字段:
指數名稱,當前點數,當前價格,漲跌率,成交量(手),成交額(萬元);
2、查詢股票一般返回的含有以下字段:
股票名字,今日開盤價,昨日收盤價,當前價格,今日最高價,今日最低價,買一價,賣一價,成交的股票數,成交金額,買一量,買一價,...,買五量,買五價,賣一量,賣一價,...,賣五量,買五價,日期,時間
由於股指查詢返回的沒有昨收盤,所以需要通過返回的當前點數和漲跌率計算獲得。
Show me your code:
public class SinaStockIndexHelper
{
public static double GetThreePreCloseIndex()
{
double precloseindex = 0;
try
{
//指數查詢規則:s_sh000001,s_sz399001,s_sz399106,s_sh000300:上證指數,深證成指,深證綜指,滬深300
//股票查詢規則:sh601857,sz002230:中石油,科大訊飛(以sh開頭代表滬市A股,以sz開頭代表深市股票,後面是對應的股票代碼)
string url = "http://hq.sinajs.cn/list=s_sh000300";
HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse webreponse = (HttpWebResponse)webrequest.GetResponse();
Stream stream = webreponse.GetResponseStream();
byte[] rsByte = new Byte[webreponse.ContentLength]; //save data in the stream
stream.Read(rsByte, 0, (int)webreponse.ContentLength);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(rsByte, 0, rsByte.Length).ToString());
string tmp = System.Text.Encoding.UTF8.GetString(rsByte, 0, rsByte.Length).ToString();
string[] index = tmp.Split('"');
string[] datas = index[1].Split(',');
double todayindex = double.Parse(datas[1]);
double increaserate = double.Parse(datas[3]) / 100;
precloseindex = todayindex / (1 + increaserate);
string pci = precloseindex.ToString("F2");
precloseindex = double.Parse(pci);
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
}
return precloseindex;
}
}