qt qchart绘制简单股票

原始数据来自公开的链接

解析代码:

#include "StockDataReader.h"
#include <QtSql>
#include <QApplication>
#include <QString>
//#include "../StockAnalyse/StockAnalyse_global.h"
//#include "../StockAnalyse/stockanalyse.h"


// 静态成员变量需要在类体的外面进行初始化
//StocksDataReader* StocksDataReader::m_pInstance = NULL;
StocksDataReader* StocksDataReader::m_pInstance=NULL;
QMutex StocksDataReader::m_Mutex;


static QString strhttp_kline = "https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol=";

//绘制实时的分时图需要下列两个网址相结合,腾讯的网址获取今日的历史分时图,新浪的网址实时的该股票行情,进行对今日分时图刷新
//http://data.gtimg.cn/flashdata/hushen/minute/sz000001.js?maxage=110&0.28163905744440854
static QString strhttp_realtime = "http://hq.sinajs.cn/list=";
static QString strhttp_timeline = "http://data.gtimg.cn/flashdata/hushen/minute/";
static QString strhttp_4daytimeline = "http://data.gtimg.cn/flashdata/hushen/4day/"; //+sz/或sh/

//https://web.ifzq.gtimg.cn/appstock/app/minute/query?code=sh600519         //新的链接
static QString strhttp_timeline_new = "https://web.ifzq.gtimg.cn/appstock/app/minute/query?code=";
static QString strhttp_4daytimeline_new = "https://web.ifzq.gtimg.cn/appstock/app/day/query?code=";
//获取最新行情
static QString strhttp_realtime_all = "http://qt.gtimg.cn/q=";//sh600000,sz000001  sh500038 //可以选这个数据多,不用计算可以直接用



//获取实时资金流向
//http://qt.gtimg.cn/q=ff_sh600519

//参考链接https://www.jianshu.com/p/e14b01990ff4
static QString strhttp_realtimemoney = "http://qt.gtimg.cn/q=";

//获取简要信息
//http://qt.gtimg.cn/q=s_sh600519,s_sh600000,s_sz000001

//获取港股最新行情
//http://qt.gtimg.cn/q=r_hk09988

//获取美股最新行情
//http://qt.gtimg.cn/?q=s_usBABA

//一些链接
// https://www.cnblogs.com/jackljf/p/3589216.html


//获取所有股票代码 (sign会不定期调整)
//http://api.k780.com/?app=finance.stock_list&category=hs&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
static QString strhttp_allSharescode = "http://api.k780.com/?app=finance.stock_list&category=hs&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";

//参考文章
//https://blog.csdn.net/dangfm/article/details/25079471

//获取股票的交易明细(p为分页,每页70条数据)
//https://stock.gtimg.cn/data/index.php?appn=detail&action=data&c=sz002451&p=0

//返回的格式: v_detail_data_sz002451=[0,"0/09:25:01/6.21/0.01/20/12420/B|1/09:30:01/6.25/0.04/81/50621/B]

static QString strhttp_tradeDetail = "https://stock.gtimg.cn/data/index.php?appn=detail&action=data&c=";
StocksDataReader::StocksDataReader()
{
    manager = new QNetworkAccessManager(this);
    bool bSupp = QSslSocket::supportsSsl();
    QString buildVersion = QSslSocket::sslLibraryBuildVersionString();
    QString version = QSslSocket::sslLibraryVersionString();
    qDebug() << bSupp << buildVersion << version << endl;

    qDebug() << manager->supportedSchemes();
    m_SharesCodelist = new QVariantList();
    m_templist = new QVariantList();
    m_timelinelist = new QVector<QStringList>;

    m_pMap5DayTimeLine = new QMap<QString,QVector<QStringList>*>();

    //m_AllRealtimelist = new QVector<QStringList>;
    m_SharesOlderList = new QMap<int,QVector<SharesOlderData>*>();
    m_AllRealtimeMoneylist = new QVector<QStringList>;
    m_timer = new QTimer(this);

    connect(m_timer, &QTimer::timeout, this, [=](){

        if(m_SharesAllCode.size()> 0){
            PreGetAllRealtimeData(m_SharesAllCode);
            PreGetAllRealtimeMoney(m_SharesAllCode);
            //qDebug()<<"实时刷新正在运行...";
        }


    });
    m_timer->start(1000);


    m_currentPage = 0;
    m_bGetDetailFinished = false;

    m_currentIndex = 0;
    m_bGetAllKLineStart = false;
    m_bGetAllKLineFinished = false;

}

void StocksDataReader::StartWorking()
{
    qDebug()<<"StocksDataReader"<<QThread::currentThread();
    //得到所有的股票代码(有两种方式1.本地数据库 2.http方式)
    //StartGetAllSharesCodeFromHttp(m_SharesCodelist);
    //用于搜索框的数据源
    //StartGetKLineDataFromHttp("sz000001",TYPE_DAY_KLINE,-1,m_templist);
    GetAllSharesCodeFromDB();
    getChooseSharelistFromDB();
    //必须要m_SharesAllCode中已经插入所有股票代码
    //PreGetAllRealtimeData(m_SharesAllCode);

    //
   // StartGetTimelineDataFromHttp("sz000001" ,m_timelinelist);

    //
   // StartGetTradeDetailFromHttp("sz002425",0);

    //腾讯的最新获取分时线方法
    //StartGetRealtimeDataFromHttp_new("sz000001" ,m_timelinelist);

    //ReadAllKLineFromLocalFile();

}

void StocksDataReader::Running(QString strcode)
{
    //先要清除相关容器

    StartGetKLineDataFromHttp(strcode,TYPE_DAY_KLINE,-1,m_templist);
    //StartGetTimelineDataFromHttp(strcode ,m_timelinelist);
    StartGetTimelineDataFromHttp_new(strcode ,m_timelinelist);
    StartGetTimelineData_5DayFromHttp_new(strcode,m_pMap5DayTimeLine);

    //交易明细
    PreGetTradeDetail(strcode);


}

void StocksDataReader::SetFlashStatus(bool flag)
{
    if(flag){
        //qDebug()<<"开市了";
        if(!m_timer->isActive())
        {
            qDebug()<<m_timer->isActive()<<"开启定时任务获取实时数据";
            m_timer->start(1000);
        }

    }else{
       // qDebug()<<"还没开市!";
        if(m_timer->isActive())
        {
            qDebug()<<"关闭定时获取实时数据任务";
            m_timer->stop();
        }
    }
   // m_timer->start(1000);
}

void StocksDataReader::UpdateAllCodeFromHttpToDB()
{
    //m_SharesCodelist函数内没用到
    //qDebug()<<__FUNCTION__;
    StartGetAllSharesCodeFromHttp(m_SharesCodelist);

}

StocksDataReader::~StocksDataReader()
{
    manager->deleteLater();
}

void StocksDataReader::StartGetKLineDataFromHttp(QString SharesCode,int type,int num,QVariantList* list)
{
    QNetworkRequest request;
     // 发送https请求前准备工作;
    QSslConfiguration config;
    QSslConfiguration conf = request.sslConfiguration();
    conf.setPeerVerifyMode(QSslSocket::VerifyNone);
    conf.setProtocol(QSsl::TlsV1SslV3);
    request.setSslConfiguration(conf);

    QString strType,strCode,strNum;

    switch(type){

        case TYPE_5MIN_KLINE:
            strType = "5";
            break;
        case TYPE_10MIN_KLINE:
            strType = "10";
            break;
        case TYPE_10DAY_KLINE:
            strType  = "2400";
            break;
        case TYPE_5DAY_KLINE:
            strType = "1200";
            break;
        case TYPE_15MIN_KLINE:
            strType = "15";
            break;
        case TYPE_30MIN_KLINE:
            strType = "30";
            break;
        case TYPE_60MIN_KLINE:
            strType = "60";
            break;
        case TYPE_DAY_KLINE:
            strType = "240";
            break;
        default:
            strType = "240";
            break;
    }

    strNum = QString::number(num);

    //默认5,10,20,30均线都请求
    request.setUrl(QUrl(strhttp_kline+SharesCode+"&scale="+strType+"&ma=5,10,20,30"+"&datalen="+strNum));       //

    //start
    QNetworkReply *pReply = manager->get(request);
    connect(pReply , SIGNAL(finished()) , this , SLOT(onFinished_GetKLine()));
    connect(pReply , SIGNAL(error(QNetworkReply::NetworkError)) , this , SLOT(onError_GetKLine(QNetworkReply::NetworkError)));
}

void StocksDataReader::StartGetAllKLineDataFromHttp()
{
    m_currentCodeforAllKLine = m_SharesAllCode.at(m_currentIndex);
    m_bGetAllKLineStart = true;
    StartGetKLineDataFromHttp(m_currentCodeforAllKLine,TYPE_DAY_KLINE,-1,m_templist);//通过改第三个参数来决定获得多少天的数据

}
void StocksDataReader::StartGetRealtimeDataFromHttp(QString SharesCode, QVector<QStringList> *list)
{

}

//新的腾讯分时api
void StocksDataReader::StartGetTimelineDataFromHttp_new(QString SharesCode, QVector<QStringList> *list)
{
    QNetworkRequest request;

     // 发送https请求前准备工作;
    QSslConfiguration config;
    QSslConfiguration conf = request.sslConfiguration();
    conf.setPeerVerifyMode(QSslSocket::VerifyNone);
    conf.setProtocol(QSsl::TlsV1SslV3);
    request.setSslConfiguration(conf);
    //使qt自动处理重定向及相关问题
    request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
    request.setUrl(QUrl(strhttp_timeline_new+SharesCode));

    //start
    QNetworkReply *pReply = manager->get(request);
    connect(pReply,SIGNAL(finished()),this,SLOT(onFinished_GetTimeLineNew()));
    connect(pReply , SIGNAL(error(QNetworkReply::NetworkError)) , this , SLOT(onError_GetTimeLineNew(QNetworkReply::NetworkError)));

}

void StocksDataReader::StartGetTimelineData_5DayFromHttp_new(QString SharesCode, QMap<QString,QVector<QStringList>*>*list)
{
    QNetworkRequest request;

     // 发送https请求前准备工作;
    QSslConfiguration config;
    QSslConfiguration conf = request.sslConfiguration();
    conf.setPeerVerifyMode(QSslSocket::VerifyNone);
    conf.setProtocol(QSsl::TlsV1SslV3);
    request.setSslConfiguration(conf);
    //使qt自动处理重定向及相关问题
    request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
    request.setUrl(QUrl(strhttp_4daytimeline_new+SharesCode));

    //start
    QNetworkReply *pReply = manager->get(request);
    connect(pReply,SIGNAL(finished()),this,SLOT(onFinished_GetTimeLine_5DayNew()));
    connect(pReply , SIGNAL(error(QNetworkReply::NetworkError)) , this , SLOT(onError_GetTimeLine_5DayNew(QNetworkReply::NetworkError)));
}
void StocksDataReader::StartGetTimelineDataFromHttp(QString SharesCode, QVector<QStringList>* list)
{
    QNetworkRequest request;

     // 发送https请求前准备工作;
    QSslConfiguration config;
    QSslConfiguration conf = request.sslConfiguration();
    conf.setPeerVerifyMode(QSslSocket::VerifyNone);
    conf.setProtocol(QSsl::TlsV1SslV3);
    request.setSslConfiguration(conf);

    //使qt自动处理重定向及相关问题
    request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
    request.setUrl(QUrl(strhttp_timeline+SharesCode+".js"));       //?maxage=110&0.28163905744440854

    //start
    QNetworkReply *pReply = manager->get(request);
    connect(pReply,SIGNAL(finished()),this,SLOT(onFinished_GetTimeLine()));
    connect(pReply , SIGNAL(error(QNetworkReply::NetworkError)) , this , SLOT(onError_GetTimeLine(QNetworkReply::NetworkError)));

}

void StocksDataReader::PreGetAllRealtimeData(QStringList SharesCodes)
{
    //因为腾讯的实时数据接口一次最多请求900个数据,所以需要进行处理
    int num = SharesCodes.size();//基金代码不想要了,就从303开始
    int times = (num)/900+1;//-303
    int res;

    for(int i = 0;i<times;i++)
    {
        if(i == times - 1)
            res = (num)%900;
        else
            res = 900;
        StartGetAllRealtimeDataFromHttp(SharesCodes.mid(900*i,res),m_AllRealtimelist);
        //进行等待
    }
}
//采用腾讯的查询接口获取数据
void StocksDataReader::StartGetAllRealtimeDataFromHttp(QStringList SharesCodes,QVector<QStringList>* list)
{
    QNetworkRequest request;
    request.setUrl(QUrl(strhttp_realtime_all+SharesCodes.join(",")));

    //m_AllRealtimelist = list;
    QNetworkReply *pReply = manager->get(request);
    connect(pReply,SIGNAL(finished()),this,SLOT(onFinished_GetAllRealTime()));
    connect(pReply , SIGNAL(error(QNetworkReply::NetworkError)) , this , SLOT(onError_GetAllRealTime(QNetworkReply::NetworkError)));
}
//获取股票的交易明细
void StocksDataReader::StartGetTradeDetailFromHttp(QString ShareCode,int page)
{
    QNetworkRequest request;
    request.setUrl(QUrl(strhttp_tradeDetail+ShareCode+"&p=" + QString::number(page)));

    QNetworkReply *pReply = manager->get(request);
    connect(pReply,SIGNAL(finished()),this,SLOT(onFinished_GetTradeDetail()));
    connect(pReply , SIGNAL(error(QNetworkReply::NetworkError)) , this , SLOT(onError_GetTradeDetail(QNetworkReply::NetworkError)));
}
void StocksDataReader::PreGetTradeDetail(QString ShareCode)
{
    m_currentPage = 0;
    m_bGetDetailFinished = false;
    m_currentCodeforDetail = ShareCode;
    //清除上一个股票的成交明细
    m_SharesOlderList->clear();

    StartGetTradeDetailFromHttp(m_currentCodeforDetail ,m_currentPage);
}

void StocksDataReader::StartGetAllTradeDetailFromHttp()
{
    m_bGetAllTradeDetailFinished = false;
    //获取所有股票的成交明细,主要用于保存成历史文件
    m_currentCodeforTradeDetail = m_SharesAllCode.at(m_currentIndexForTradeDetail);
    PreGetTradeDetail(m_currentCodeforTradeDetail);

}

void StocksDataReader::PreGetAllRealtimeMoney(QStringList SharesCodes)
{
    int num = SharesCodes.size();//基金代码不想要了,就从303开始
    int times = (num)/680;//-303
    int res;

    for(int i = 0;i<times;i++)
    {
        if(i == times - 1)
            res = (num)%680;
        else
            res = 680;
        StartGetAllRealtimeMoneyFromHttp(SharesCodes.mid(680*i,res));
        //进行等待
    }
}
//获取实时资金流向  (可以请求多个)
void StocksDataReader::StartGetAllRealtimeMoneyFromHttp(QStringList SharesCodes)
{
     QNetworkRequest request;
     QStringList tmp;
     //每次请求最多只能请求680个,故要进行处理
    for(int j = 0;j<SharesCodes.size();j++)
    {
        tmp<<"ff_"+SharesCodes.at(j);

    }
    //qDebug()<<tmp;
     request.setUrl(QUrl(strhttp_realtimemoney+tmp.join(",")));
     QNetworkReply *pReply = manager->get(request);
     connect(pReply,SIGNAL(finished()),this,SLOT(onFinished_GetRealtimeMoney()));
     connect(pReply , SIGNAL(error(QNetworkReply::NetworkError)) , this , SLOT(onError_GetRealtimeMoney(QNetworkReply::NetworkError)));
}

//从网络更新所有的股票代码
void StocksDataReader::StartGetAllSharesCodeFromHttp(QVariantList *list)
{
    QNetworkRequest request;
    request.setUrl(QUrl(strhttp_allSharescode));

    if(list == NULL)
        return;
    //m_SharesCodelist = list;
    QNetworkReply *pReply = manager->get(request);

    connect(pReply,SIGNAL(finished()),this,SLOT(onFinished_GetAllSharesCode()));
    connect(pReply , SIGNAL(error(QNetworkReply::NetworkError)) , this , SLOT(onError_GetAllSharesCode(QNetworkReply::NetworkError)));
}
//从本地数据库中获得所有股票代码
void StocksDataReader::GetAllSharesCodeFromDB()
{
    QSqlDatabase database =QSqlDatabase::addDatabase("QSQLITE");
//       if(QSqlDatabase::contains("localhost@3306"))
//           database = QSqlDatabase::database("localhost@3306");
//       else
//          database = QSqlDatabase::addDatabase("QSQLITE", "localhost@3306");
    database.setDatabaseName(QApplication::applicationDirPath()+"/database.db");
            //    database.setUserName("root");
            //    database.setPassword("123456");
    if (!database.open())
    {
        qDebug() << "Error: Failed to connect database." << database.lastError();
    }
    else
    {
         qDebug() << "Succeed to connect database." ;
         QSqlQuery sql_query;
         //QString create_sql = "create table allSharecode_table (id varchar(30) primary key, name varchar(30))";
         QString select_allSharesCode_sql = "select * from  allSharecode_table";
         sql_query.prepare(select_allSharesCode_sql);
         if(!sql_query.exec())
         {
             qDebug()<<sql_query.lastError();
         }
         else
         {
             while(sql_query.next()){
                 QStringList *list = new QStringList();
                 list->append(sql_query.value(0).toString());
                 list->append(sql_query.value(1).toString());

                 //过滤掉数据库中的基金和其他不是股票的code,因为从网络获得的所有股票数据不太好,需要换个链接
                 if(sql_query.value(0).toString().left(3) != "sh5" \
                         && sql_query.value(0).toString().left(3) != "sz1"\
                         && sql_query.value(0).toString().left(3) != "sz6"\
                         && sql_query.value(0).toString().left(3) != "sh9")
                 {
                     m_SharesInfo.insert(sql_query.value(0).toString(),*list);
                     //存入读取的股票代码
                     m_SharesAllCode<<sql_query.value(0).toString();

                 }

             }
         }
    }
    database.close();

    //发出得到所有股票信息的消息
    emit getAllSharesInfoFinished(&m_SharesInfo);

}

void StocksDataReader::getChooseSharelistFromDB()
{
    QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE");
//    if(QSqlDatabase::contains("localhost@3306"))
//        database = QSqlDatabase::database("localhost@3306");
//    else
//       database = QSqlDatabase::addDatabase("QSQLITE", "localhost@3306");
            //
    database.setDatabaseName(QApplication::applicationDirPath()+"/database.db");
            //    database.setUserName("root");
            //    database.setPassword("123456");
    if (!database.open())
    {
        qDebug() << "Error: Failed to connect database." << database.lastError();
    }
    else
    {
         //qDebug() << "Succeed to connect database." ;
         QSqlQuery sql_query;
         //QString create_sql = "create table allSharecode_table (id varchar(30) primary key, name varchar(30))";
         //"create table ChooseSharelist_table (code varchar(30) primary key, date varchar(30),tip varchar(30))";
         //if(IsTableExit(sql_query,"ChooseSharelist_table")){
         QString select_ChooseSharelist_sql = "select * from  ChooseSharelist_table";
         sql_query.prepare(select_ChooseSharelist_sql);
         if(!sql_query.exec())
         {
             qDebug()<<sql_query.lastError();
         }
         else
         {
             while(sql_query.next()){
                 ChooseShareslistData *data = new ChooseShareslistData();

                 data->code = (sql_query.value(0).toString());
                 data->AddDate = (sql_query.value(1).toString());
                 data->Tip = sql_query.value(2).toString();
                 data->Name = sql_query.value(3).toString();
                 m_ChooseShareslist.push_back(*data);
                 //qDebug()<<sql_query.value(0).toString()<<sql_query.value(1).toString();
             }
         }

    }
    database.close();

    //发出得到所有股票信息的消息
    if(!m_ChooseShareslist.empty())
        emit getChooseSharelistFinished(&m_ChooseShareslist);
}
//读取本地的股票分时数据
void StocksDataReader::GetRealTimeDataByCode(QString SharesCode)
{

}

QStringList StocksDataReader::GetOneStockRealtime(QString strCode)
{
    if(m_MapAllSharesRealtime.contains(strCode))
    {
        return m_MapAllSharesRealtime[strCode];
    }
    else
        return QStringList();
}

QStringList StocksDataReader::GetOneStockRealtimeMoney(QString strCode)
{
    if(m_MapAllRealtimeMoney.contains(strCode))
        return m_MapAllRealtimeMoney[strCode];
    else
        return QStringList();
}

void StocksDataReader::clearKlinedata()
{
    m_templist->clear();
}

void StocksDataReader::clearTimelinedata()
{
    m_timelinelist->clear();

}


//将股票数据保存到本地的文件
int StocksDataReader::SaveAsLocalFile(QString SharesCode)
{
    return 0;
}
int StocksDataReader::ReadFromLocalFile(QString SharesCode)
{
    return 0;
}

int StocksDataReader::SaveAllKLineAsLocalFile()
{

    QJsonObject obj;
    QJsonObject sub;
    QJsonArray  arr,arr2;
    QJsonArray jsonArray;
    QString str;
    QFile file("temo.json");
    file.open(QIODevice::WriteOnly);
    for(int i = 0;i<m_MapAllSharesKLine.size();i++){
        str = m_MapAllSharesKLine.keys().at(i);
        jsonArray = QJsonArray::fromVariantList(m_MapAllSharesKLine.value(str));
        sub.insert("data",QJsonArray(jsonArray));
        sub.insert("code",QJsonValue(str));
        arr2.append(sub);

        //内存中的数据写到文件
        QJsonDocument doc(arr2);
        //将json对象转换成字符串
        QByteArray data=doc.toJson(QJsonDocument::Compact);

        file.write(data);
        arr2.pop_back();
    }

    file.close();
    qDebug()<<__FUNCTION__<<"OK";
    return 0;
}

/*
    未写完,用sqlite数据库更方便
*/
int StocksDataReader::ReadAllKLineFromLocalFile()
{
    QFile file("temo.json");
    file.open(QIODevice::ReadWrite );
    uchar* fPtr = file.map(0, file.size());//映射文件,注意这里的file.size()如果大于系统的虚拟内存,就要对文件分块映射
                                       //其实对于大文件一般都是进行分块映射的。
    if(fPtr)
    {
         //do something   to fPtr

        qDebug()<<*fPtr;
        file.unmap(fPtr);

    }

    file.close();
    return 0;


}

int StocksDataReader::SaveAllKlineToLocalDB()
{
    return 0;
}

bool StocksDataReader::IsFinishGettingData()
{
    return false;
}

bool StocksDataReader::IsTableExit(QSqlQuery &query, QString table)
{
    QString sql = QString("select count(*) from sqlite_master where type = 'table' name='%1'").arg(table);
    return query.exec(sql);
}

QList<QString> StocksDataReader::Parase(QJsonValue value)
{
    QList<QString> list;
    if(value.isObject())
    {
        QJsonObject obj = value.toObject();
        QJsonValue val = obj.value(obj.keys().at(0));
        if(val.isObject())
        {
            QJsonValue val1 =val.toObject().value("data");
            if(val1.isObject()){
                QJsonValue val2 = val1.toObject().value("data");
                if(val2.isArray()){
                    qDebug()<<val2.toVariant().toList();
                }
            }
        }
    }
    return list;
}

StocksDataReader *StocksDataReader::GetInstance()
{
    if(m_pInstance==NULL)
    {
        QMutexLocker mutexLocker(&m_Mutex);
        if (m_pInstance==NULL)
            m_pInstance =  new StocksDataReader();
    }
    return m_pInstance;
}



void StocksDataReader::onFinished_GetKLine()
{
    m_bDataGet = true;
    //将返回的k线数据进行初步的处理
    QNetworkReply *pReplay = qobject_cast<QNetworkReply*>(sender());
    if(QNetworkReply::ContentNotFoundError == pReplay->error()){
        //没有获得数据
        m_templist->clear();
        m_MapAllSharesKLine.clear();
    }
    else{
        QByteArray replyContent = pReplay->readAll();

        if(replyContent == "null"){
            if(m_bGetAllKLineStart){
                 //qDebug()<<m_currentIndex;  sz1 ,sh5,sz6不需要请求
                m_currentIndex += 1;
                if(m_currentIndex < m_SharesAllCode.size()){

                    m_currentCodeforAllKLine = m_SharesAllCode.at(m_currentIndex);

                    StartGetKLineDataFromHttp(m_currentCodeforAllKLine,TYPE_DAY_KLINE,-1,m_templist);

                }
                else{
                    m_bGetAllKLineStart = false;
                    qDebug()<<"结束2";
                    m_bGetAllKLineFinished = true;

                }
            }
        }
        //qDebug()<<pReplay->readAll();
        QJsonParseError jsonparseerr;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(replyContent,&jsonparseerr);

        if(jsonDoc.isArray())
        {
             //qDebug()<<"aaaa";

            if(m_bGetAllKLineStart == false){
                 m_templist->clear();
                (*m_templist) = jsonDoc.toVariant().toList();
                //数据接收完成,发出信号
                emit getKlineFinished(m_templist);
            }
            //用于分析
            if(m_bGetAllKLineStart){
                m_MapAllSharesKLine.insert(m_currentCodeforAllKLine,jsonDoc.toVariant().toList());
                //请求下一条
                m_currentIndex += 1;
                if(m_currentIndex < m_SharesAllCode.size()){
                    m_currentCodeforAllKLine = m_SharesAllCode.at(m_currentIndex);
                    //qDebug()<<m_currentIndex;
                    emit progressValue(m_SharesAllCode.size(),m_currentIndex);//进度条更新消息
                    StartGetKLineDataFromHttp(m_currentCodeforAllKLine,TYPE_DAY_KLINE,-1,m_templist);
                }
                else{
                    m_bGetAllKLineStart = false;
                    qDebug()<<"结束";

                    m_bGetAllKLineFinished = true;
                    emit getAllKlineFinished(&m_MapAllSharesKLine);

                    //不调用
                    //SaveAllKLineAsLocalFile();
                }
            }
        }
    }
    pReplay->deleteLater();
}
void StocksDataReader::onFinished_GetTimeLine()
{
    QNetworkReply *pReplay = qobject_cast<QNetworkReply*>(sender());

    if(QNetworkReply::ContentNotFoundError == pReplay->error()){
        //没有获得数据
            m_timelinelist->clear();
    }
    else{
         //构建QTextStream读一行
        //qDebug()<<__FUNCTION__<<pReplay->error()<<pReplay->readAll();
        QTextStream datam(pReplay->readAll());
        datam.readLine();
        QString date = datam.readLine();
        QStringList strList;

        m_timelinelist->clear();
        do{

            QString line = datam.readLine();
            line = line.replace("\\n\\"," ");
            strList = line.split(" ", QString::SkipEmptyParts);
            if(strList[0] != "\";")
                m_timelinelist->append(strList);

        }while(strList[0] != "\";");

    }
    //发出接收分时数据完成信号
    emit getTimelineFinished(m_timelinelist);
    //qDebug()<<m_timelinelist->at(1);
    pReplay->deleteLater();
}

void StocksDataReader::onFinished_GetTimeLineNew()
{
    QNetworkReply *pReplay = qobject_cast<QNetworkReply*>(sender());
    QStringList strList;

    if(QNetworkReply::ContentNotFoundError == pReplay->error()){
        //没有获得数据
        m_timelinelist->clear();
    }
    else
    {
        m_timelinelist->clear();
        QByteArray replyContent = pReplay->readAll();
        QJsonParseError jsonparseerr;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(replyContent,&jsonparseerr);
        //qDebug()<<jsonDoc;
        QJsonObject jsonObject = jsonDoc.object();
        //qDebug()<<jsonObject.keys().at(2);
        //qDebug()<<jsonObject;
        if(jsonObject.contains(QStringLiteral("data")))
        {
            //数据类型应该是QMap<QString,QVector<QStringList> >
            QJsonValue value = jsonObject["data"];
            if(value.isObject()&& !value.isNull()){
                if(value.isObject())
                {
                    QJsonObject obj = value.toObject();
                    QJsonValue val = obj.value(obj.keys().at(0));
                    if(val.isObject())
                    {
                        QJsonValue val1 =val.toObject().value("data");
                        if(val1.isObject()){
                            QJsonValue val2 = val1.toObject().value("data");
                            if(val2.isArray()){
                                //qDebug()<<val2.toVariant().toList().at(0).toStringList();
                                for(int i = 0;i<val2.toVariant().toList().size();i++){

                                    m_timelinelist->append(val2.toVariant().toList().at(i).toString().split(' '));
                                    //Debug()<<m_timelinelist->at(i);
                                }
                                emit getTimelineNewFinished(m_timelinelist);

                            }
                        }
                    }
                }
            }
        }
    }
    pReplay->deleteLater();

}

void StocksDataReader::onFinished_GetTimeLine_5DayNew()
{
    QNetworkReply *pReplay = qobject_cast<QNetworkReply*>(sender());
    QStringList strList;
    if(QNetworkReply::ContentNotFoundError == pReplay->error()){
        //没有获得数据
        m_pMap5DayTimeLine->clear();
    }
    else{
        m_pMap5DayTimeLine->clear();
        QByteArray replyContent = pReplay->readAll();
        QJsonParseError jsonparseerr;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(replyContent,&jsonparseerr);
        //qDebug()<<jsonDoc;
        QJsonObject jsonObject = jsonDoc.object();
        if(jsonObject.contains(QStringLiteral("data"))){

            QJsonValue value = jsonObject["data"];

           // qDebug()<<value;
            if(value.isObject()&& !value.isNull())
            {
                QJsonObject obj = value.toObject();
                //qDebug()<<obj.keys(); //股票代码
                QJsonValue val = obj.value(obj.keys().at(0));
                if(val.isObject()){
                    //
                    QJsonValue val1 =val.toObject().value("data");
                    if(val1.isArray()){
                        //QJsonValue val2 = val1.toObject().value("data");

                        //qDebug()<<val1.toArray().at(2);

                        for(int i=0;i<val1.toArray().size();i++){
                            QString str = val1.toArray().at(i).toObject()["date"].toString();
                            QJsonValue val2 = val1.toArray().at(i).toObject()["data"];
                            int num = val2.toVariant().toList().size();
                            QVector<QStringList>* strlist = new QVector<QStringList>();
                            for(int j = 0;j<num;j++){
                                strlist->append(val2.toVariant().toList().at(j).toStringList());
                            }
                            m_pMap5DayTimeLine->insert(str,strlist);

                        }
                        //发出接收完成信号
                        emit getTimeline_5DayNewFinished(m_pMap5DayTimeLine);
                    }

                }


            }

        }

    }
}
void StocksDataReader::onFinished3()//实时行情槽函数
{

}
void StocksDataReader::onFinished_GetAllRealTime()//腾讯的实时股票显示数据()槽函数
{
    //解析多个股票的实时数据
    QNetworkReply *pReplay = qobject_cast<QNetworkReply*>(sender());


    QTextCodec *gbk = QTextCodec::codecForName("gbk");
    QString g2u = gbk->toUnicode(pReplay->readAll());
    QString g2uTmp = g2u.replace(QString("\n"),QString(""));

    //m_AllRealtimelist->clear();
    QStringList strList = g2u.split(";",QString::SkipEmptyParts);

    for (QStringList::iterator it = strList.begin();it != strList.end(); ++it)
    {
        int index= it->indexOf("\"");
         int index2= it->lastIndexOf("\"");
         QString vCode = it->left(index-1);
         QString st1 = it->mid(index+1,index2-(index+1));

         QStringList strTo = st1.split("~");//,QString::SkipEmptyParts
         //strTo<<vCode;

         m_MapAllSharesRealtime.insert(strTo.at(Type_Code),strTo);
    }

    //qDebug()<<m_MapAllSharesRealtime.size();
    emit getAllRealtimeFinished(&m_MapAllSharesRealtime);
    pReplay->deleteLater();
}
void StocksDataReader::onFinished_GetAllSharesCode() //从网络获取所有股票代码的槽函数
{
    QNetworkReply *pReplay = qobject_cast<QNetworkReply*>(sender());

    QByteArray replyContent = pReplay->readAll();
    //json的中文处理
    //qDebug()<<QString::fromLocal8Bit(replyContent);
    QJsonParseError jsonparseerr;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(replyContent,&jsonparseerr);
    QJsonObject jsonObject = jsonDoc.object();

    if(jsonObject["success"] == "1")
    {

        if(jsonObject.contains(QStringLiteral("result")))
        {
             QJsonValue objectValue = jsonObject.value("result");
             if(objectValue.isObject())
             {
                 QJsonObject jsonObject2 = objectValue.toObject();
                 QJsonValue arrayValue = jsonObject2.value("lists");
                 if(arrayValue.isArray())
                 {
                     (*m_SharesCodelist) = arrayValue.toVariant().toList();

                     //qDebug()<<jsonObject2.value("lists");
                     QVariantList tmplist,tmplist2;
                    // m_SharesAllCode.clear();
                     for (int i= 0; i<m_SharesCodelist->size() ; i++ )
                     {
                         QVariantMap map = m_SharesCodelist->at(i).toMap();
                         if(!m_SharesAllCode.contains(map["symbol"].toString()) \
                                 && map["symbol"].toString().left(3) != "sh5"\
                                 && map["symbol"].toString().left(3) != "sz1"\
                                 && map["symbol"].toString().left(3) != "sz6"\
                                 && map["symbol"].toString().left(3) != "sh9"){


                             qDebug()<<map["symbol"].toString();
                             //将新增的股票代码添加到本地数据库sqlite的allSharecode_table表中,逐条插入

                             //内存中也需要更新(逐条插入)
                              m_SharesAllCode.append(map["symbol"].toString());

                              QStringList *list = new QStringList();
                              list->append(map["symbol"].toString());
                              list->append(map["sname"].toString());
                              m_SharesInfo.insert(map["symbol"].toString(),*list);

                              emit getAllSharesCodeFinished(*list);

                         }
                     }
                 }
             }
        }
    }
    else{
       qDebug()<<"获取所有股票代码失败.";
    }
    pReplay->deleteLater();
}
void StocksDataReader::onFinished_GetTradeDetail()//从网络获取交易明细的槽函数
{
    QNetworkReply *pReplay = qobject_cast<QNetworkReply*>(sender());
    QByteArray replyContent = pReplay->readAll();
    //如果返回没有数据,则可以认为已经接收完了,不用继续请求下一页数据了
    if(replyContent == "")
    {
        qDebug()<<"获取分时交易数据成功。";
        m_bGetDetailFinished = true;
        emit getTradeDetailFinished(m_SharesOlderList);
        return;
    }
    QString str = QString(replyContent);
    QString page =str.mid(str.indexOf('[')+1,str.indexOf(',')-(str.indexOf('[')+1));
    //qDebug()<<str.indexOf('\"')<<str.lastIndexOf('\"');
    QString str1 = str.mid(str.indexOf('\"')+1,str.lastIndexOf('\"')-(str.indexOf('\"')+1));

    QStringList str2= str1.split('|');

    QVector<SharesOlderData>* s = new QVector<SharesOlderData>();
    for(int i = 0;i<str2.size();i++)
    {

        QStringList str3 = str2.at(i).split('/');
        SharesOlderData* olderData = new SharesOlderData();
        olderData->time = str3.at(1);
        olderData->price = str3.at(2).toDouble();
        olderData->zhangdie = str3.at(3).toDouble();
        olderData->volume = str3.at(4).toULong();
        olderData->money = str3.at(5).toULong();
        olderData->flag = str3.at(6);
        s->append(*olderData);

    }
    m_SharesOlderList->insert(page.toInt(),s);
    if(m_bGetDetailFinished == false)
    {
        m_currentPage += 1;
        StartGetTradeDetailFromHttp(m_currentCodeforDetail,m_currentPage);
    }
    //qDebug()<<m_SharesOlderList->size()<<m_currentPage;

}
void StocksDataReader::onFinished_GetRealtimeMoney()//从网络获取资金流向的槽函数
{
    QNetworkReply *pReplay = qobject_cast<QNetworkReply*>(sender());
    //qDebug()<<pReplay->readAll();
    QTextCodec *gbk = QTextCodec::codecForName("gbk");
    QString g2u = gbk->toUnicode(pReplay->readAll());
    g2u = g2u.simplified(); //去掉一些换行符啥的
    QStringList strtmp = g2u.split(";");
    //qDebug()<<strtmp.size();
    for(int i =0;i<strtmp.size()-1;i++){
        QString str1 = strtmp.at(i).mid(strtmp.at(i).indexOf('\"')+1,strtmp.at(i).lastIndexOf('\"')-(strtmp.at(i).indexOf('\"')+1));
        QStringList str2 = str1.split('~');
        m_MapAllRealtimeMoney.insert(str2.at(TYPE_CODE),str2);
    }
    //
   //qDebug()<<m_MapAllRealtimeMoney["sz300077"];
    //emit getAllRealtimeMoneyFinished(m_AllRealtimeMoneylist);
}
void StocksDataReader::onError_GetAllSharesCode(QNetworkReply::NetworkError err)
{
    qDebug()<<"获取股票代码不可用";
}
void StocksDataReader::onError_GetKLine(QNetworkReply::NetworkError err)
{
    qDebug()<<"获取K线数据不可用";
}
void StocksDataReader::onError_GetAllRealTime(QNetworkReply::NetworkError err)
{
    qDebug()<<"获取所有实时数据不可用";
}
void StocksDataReader::onError_GetTimeLine(QNetworkReply::NetworkError err)
{
    qDebug()<<"获取分时数据不可用";
}

void StocksDataReader::onError_GetTimeLineNew(QNetworkReply::NetworkError err)
{
    qDebug()<<"获取分时数据不可用"<<__FUNCTION__;
}

void StocksDataReader::onError_GetTimeLine_5DayNew(QNetworkReply::NetworkError err)
{
    qDebug()<<"获取5日分时数据不可用"<<__FUNCTION__;
}

void StocksDataReader::onError_GetTradeDetail(QNetworkReply::NetworkError err)
{
    qDebug()<<"获取交易明细不可用";
}

void StocksDataReader::onError_GetRealtimeMoney(QNetworkReply::NetworkError err)
{
    qDebug()<<"获取实时资金不可用";
}

void StocksDataReader::onStartAnalysis()
{
    //获取250日的所有股票的K线
//    StartGetAllKLineDataFromHttp();
    qDebug()<<__FUNCTION__;
   // StockAnalyse stockAnalyse;
    //qDebug()<<stockAnalyse.AnalyseAll(&m_MapAllSharesRealtime,&m_MapAllRealtimeMoney,&m_MapAllSharesKLine)->value("000001");

}

void StocksDataReader::onSaveEveryday()
{
    qDebug()<<__FUNCTION__;

}

代码:

 shares和stockAnalyse-QT文档类资源-CSDN文库