基本信息
源码名称:C#获取实时数字货币数据
源码大小:4.21M
文件格式:.zip
开发语言:C#
更新时间:2021-04-12
   源码介绍

C# 一键GET主流数字货币实时数据

陈立恒博客-专注金融编程:https://www.chenliheng.com

原文链接:https://www.chenliheng.com/findata/getdcdata.html

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;

namespace GetFinData
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        List<string> infoList = new List<string>();//定义infoList,保存解析后的数字货币信息

        /// <summary>
        /// 用HttpWebRequest和HttpWebResponse类发送和接收HTTP数据。
        /// </summary>
        /// <param name="url"></param>
        /// <param name="Timeout"></param>
        /// <returns></returns>
        public static string GetHttpResponse(string url, int Timeout)
        {
            //发送
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";//GET方式通过在网络地址附加参数来完成数据的提交
            request.ContentType = "text/html;charset=UTF-8";
            request.UserAgent = null;
            request.Timeout = Timeout;//设置请求的超时值。

            //接收
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }


        private void button1_Click(object sender, EventArgs e)
        {
            this.dataGridView1.Rows.Clear();//清空dataGridView
            try
            {
                string json = GetHttpResponse("http://api.coincap.io/v2/assets", 6000);//调用COINCAP API 2.0获取所有数字货币信息
                dataShow(json);             
            }
            catch (Exception ex)
            {
                MessageBox.Show(""   ex);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            createJson();
            writeJson(infoList);
            MessageBox.Show("文件已保存到根目录!","提示");
        }

        /// <summary>
        /// 提取Json嵌套数组数据并添加到dataGridView
        /// </summary>
        /// <param name="json"></param>
        private void dataShow(string json)
        {
            string[] temArr = { "", "", "", "", "", "", "", "", "", "", "" };//数组集合
            JObject jo = (JObject)JsonConvert.DeserializeObject(json);//反序列化
            JArray jar = JArray.Parse(jo["data"].ToString());//data是原始Json文件中的数组名
            for (var i = 0; i < jar.Count; i  )
            {
                JObject j = JObject.Parse(jar[i].ToString());
                temArr[0] = j["id"].ToString();//unique identifier for asset
                temArr[1] = j["rank"].ToString();//rank is in ascending order - this number is directly associated with the marketcap whereas the highest marketcap receives rank 1
                temArr[2] = j["symbol"].ToString();//most common symbol used to identify this asset on an exchange
                temArr[3] = j["name"].ToString();//proper name for asset
                temArr[4] = j["supply"].ToString();//available supply for trading
                temArr[5] = j["maxSupply"].ToString();//total quantity of asset issued
                temArr[6] = j["marketCapUsd"].ToString();//supply x price
                temArr[7] = j["volumeUsd24Hr"].ToString();//quantity of trading volume represented in USD over the last 24 hours
                temArr[8] = j["priceUsd"].ToString();//	volume-weighted price based on real-time market data, translated to USD
                temArr[9] = j["changePercent24Hr"].ToString();//the direction and value change in the last 24 hours
                temArr[10] = j["vwap24Hr"].ToString();//Volume Weighted Average Price in the last 24 hours
                infoList.AddRange(temArr);//添加解析后的数据到List中
                this.dataGridView1.Rows.Add(temArr[0], temArr[1], temArr[2], temArr[3], temArr[4], temArr[5], temArr[6], temArr[7], temArr[8], temArr[9], temArr[10]);//dataGridView绑定列值
            }
        }

        /// <summary>
        /// 创建Json文件
        /// </summary>
        private void createJson()
        {
            //获取当前程序所在路径,并创建CoincapData.json文件
            string fp = System.Windows.Forms.Application.StartupPath   "\\CoincapData.json";       
            if (!File.Exists(fp))//判断是否已有相同文件
            {
                FileStream fs1 = new FileStream(fp, FileMode.Create, FileAccess.ReadWrite);
                fs1.Close();
            }
        }

        /// <summary>
        /// 写入Json文件
        /// </summary>
        /// <param name="ob"></param>
        private void writeJson(object ob)
        {
            //获取当前程序所在路径,并写入CoincapData.json文件
            string fp = System.Windows.Forms.Application.StartupPath   "\\CoincapData.json";
            File.WriteAllText(fp, JsonConvert.SerializeObject(ob));//序列化
        }

        private void button3_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://www.chenliheng.com");//陈立恒博客-专注金融编程
        }

        private void button4_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://www.chenliheng.com/findata/getdcdata.html");//原文链接
        }
    }
}