text:
<repo_name>Luojb7/WQ_project<file_sep>/project4/code/TraderSpi/bin/OrderInfo.ini
;order information config ini
;OrderType: 1-LimitPrice 2-MarketPrice 3-FOK 4-FAK
;Instrument:
;Direction: 0-Buy 1-Sell
;CombOffsetFlag: 0-Open 1-Close 2-ForceClose 3-CloseToday 4-CloseYesterday 5-ForceOff 6-LocalForceClose
;CombHedgeFlag: 1-Speculation 2-Arbitrage 3-Hedge
;LimitPrice:
;VolumeTotalOriginal:
;MinVolume:
;ForceCloseReason: 0-NotForceClose 1-LackDeposit 2-ClientOverPositionLimit 3-MemberOverPositionLimit 4-NotMultiple 5-Violation 6-Other 7-PersonDeliv
;IsAutoSuspend:
;UserForceClose:

[OrderType]
ot=1

[Instrument]
ins=al1803

[Direction]
dir=0

[CombOffsetFlag]
cof=0

[CombHedgeFlag]
chf=1

[LimitPrice]
pri=14005

[VolumeTotalOriginal]
vto=5

[MinVolume]
mv=1

[ForceCloseReason]
fcr=0

[IsAutoSuspend]
ias=0

[UserForceClose]
ufc=0<file_sep>/project2/code/fastResearchData.py
# coding: utf-8
import pandas as pd
import os
from sklearn import preprocessing
import pickle as pk

class FastResearchData:
    def __init__(self, dir_path):
        self.stock_dict = {}
        self.dir_path = dir_path

    def getCode(self, file_path):
        """截取文件路径中的股票编号"""
        code_start_position = file_path.rfind('/')
        code_end_position = file_path.rfind('.')
        code = file_path[code_start_position+1:code_end_position]
        return code

    def loadFromDataFrame(self, stock_code, df):
        """把dataframe对象存入字典"""
        if stock_code not in self.stock_dict.keys():
            self.stock_dict[stock_code] = df
        else:
            pd.concat([self.stock_dict[stock_code], df], axis=0)

    def loadStockData(self, stock_code, file_type='csv', sheet_name=''):
        """根据股票编号生成文件路径，并读取文件数据，存入字典. 更新数据用"""
        if file_type == 'csv':
            df = pd.read_csv(os.path.join(self.dir_path, stock_code+'.csv'))
        elif file_type == 'pickle':
            df = pd.DataFrame(pk.load(open(os.path.join(self.dir_path, stock_code+'.pkl'), 'rb')))
        elif file_type == 'hdf':
            df = pd.read_hdf(os.path.join(self.dir_path, stock_code+'.hdf'), 'df')
        elif file_type == 'excel':
            df = pd.DataFrame(pd.read_excel(os.path.join(self.dir_path, stock_code+'.xlsx'), sheet_name))
        else:
            print "this type of file can not be read"
            return
        if stock_code not in self.stock_dict.keys():
            self.stock_dict[stock_code] = df
        else:
            pd.concat([self.stock_dict[stock_code], df], axis=0)

    def loadFromFile(self, file_path, file_type='csv', sheet_name=''):
        """根据输入的文件类型，读取文件数据，存入字典"""
        stock_code = self.getCode(file_path)
        if file_type == 'csv':
            df = pd.read_csv(file_path)
        elif file_type == 'pickle':
            df = pd.DataFrame(pk.load(open(file_path,'rb')))
        elif file_type == 'hdf':
            df = pd.read_hdf(file_path, 'df')
        elif file_type == 'excel':
            df = pd.DataFrame(pd.read_excel(file_path, sheet_name))
        else:
            print "this type of file can not be read"
            return
        self.loadFromDataFrame(stock_code, df)

    # def loadFromCSV(self, file_path):
    #     """从csv文件中读取数据"""
    #     code = self.getCode(file_path)
    #     df = pd.read_csv(file_path)
    #     self.loadFromDataFrame(code, df)

    # def loadFromPickle(self, stock_code, file_name):
    #     """从Pickle中读取数据，并存入字典"""
    #     pickle_file = open(file_name, 'rb')
    #     df = pd.DataFrame(pk.load(pickle_file))
    #     self.loadFromDataFrame(stock_code, df)

    # def loadFromHDF5(self, stock_code, file_path):
    #     """从hdf5文件中读取数据，并存入字典"""
    #     hdf = pd.DataFrame(pd.read_hdf(file_path, 'df'))
    #     self.loadFromDataFrame(stock_code, hdf)

    # def loadFromExcel(self, stock_code, file_path, sheet_name):
    #     """从excel文件中读取数据，并存入字典"""
    #     excel = pd.DataFrame(pd.read_excel(file_path, sheet_name))
    #     self.loadFromDataFrame(stock_code, excel)

    def getDataFrame(self, stock_code):
        """返回某一股票数据"""
        if stock_code not in self.stock_dict.keys():
            print "the code is not in the data set"
            return None
        return self.stock_dict[stock_code]

    def setDataFrame(self, stock_code, df):
        """更新某一股票数据"""
        if stock_code not in self.stock_dict.keys():
            print "the code is not in the data set"
            return None
        self.stock_dict[stock_code] = df

    def getStockDict(self):
        """返回整个字典"""
        return self.stock_dict

if __name__ == "__main__":
    frd = FastResearchData("data/1day/")
    frd.loadFromFile("data/1day/000001.csv", 'csv')
    stock_dict = frd.getStockDict()
    print stock_dict.keys()
<file_sep>/project3/code/project3_v2.cpp
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<algorithm>

using namespace std;

struct sub_val
{
	string substring;
	int value;
	double avg_value;
	int priority;
	vector<int> next;
	int pos;

	sub_val(){
		priority = 1;
		pos = -1;
	}
};

bool cmp1(sub_val sv1, sub_val sv2){
	if(sv1.avg_value == sv2.avg_value){
		return sv1.substring.size() > sv2.substring.size();
	}
	else{
		return sv1.avg_value>sv2.avg_value;
	}
}

bool cmp2(sub_val sv1, sub_val sv2){
	return sv1.priority < sv2.priority;
}

void cal_next(string str, vector<int> &next, int len){
	next.push_back(-1);
	int k=-1;
	for(int q=1; q<=len-1; q++){
		while(k>-1 && str[k+1]!=str[q]){
			k=next[k];
		}
		if(str[k+1]==str[q]){
			k=k+1;
		}
		next.push_back(k);
	}
}

int KMP(string str, sub_val substr){
	int slen = str.size();
	int plen = substr.substring.size();
	int k=-1;
	for(int i=0;i<slen;i++){
		while(k>-1 && substr.substring[k+1]!=str[i])
			k = substr.next[k];
		if(substr.substring[k+1] == str[i])
			k = k+1;
		if(k == plen-1){
			return i-plen+1;
		}
	}
	return -1;
}

int main()
{
	ifstream in("in1.txt");
	int n,k;
	string s;
	in>>n>>k>>s;
	// cout<<n<<" "<<k<<" "<<s<<endl;
	vector<sub_val> mySV;
	sub_val temp;
	for(int i=0;i<k;i++){
		in>>temp.substring>>temp.value;
		temp.avg_value = temp.value * 1.0 / temp.substring.size(); //calculate average value
		cal_next(temp.substring, temp.next, temp.substring.size()); // calculate next matrix
		mySV.push_back(temp);
	}

	sort(mySV.begin(), mySV.end(), cmp1);
	// for(int i=0;i<k;i++){
	// 	cout<<mySV[i].substring<<" "<<mySV[i].value<<" "<<mySV[i].avg_value<<endl;
	// }

	for(int i=0;i<mySV.size();i++){
		for(int j=i-1;j>=0;j--){
			if(KMP(mySV[j].substring, mySV[i]) != -1){
				mySV[i].priority ++;
				break;
			}
		}
	}

	sort(mySV.begin(), mySV.end(), cmp2);
//	 for(int i=0;i<k;i++){
//	 	cout<<mySV[i].substring<<" "<<mySV[i].value<<" "<<mySV[i].avg_value<<" "<<mySV[i].priority<<endl;
//	 }

	vector<sub_val> result;
	int sum=0;
	for(int i=0;i<mySV.size();i++){
		int temp = KMP(s, mySV[i]);
		if(temp != -1){
			mySV[i].pos = temp;
			sum += mySV[i].value;
			s.erase(temp, mySV[i].substring.size());
			result.push_back(mySV[i]);
			i = -1;
		}
	}
	for(int i=0;i<result.size();i++){
		cout<<result[i].pos<<" "<<result[i].substring<<endl;
	}
	cout<<sum<<endl;

	return 0;
}
<file_sep>/project4/code/TraderSpi/CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
PROJECT(Demo)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
SET(SOURCE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/src)
SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)

INCLUDE_DIRECTORIES(inc)

ADD_SUBDIRECTORY(src)
<file_sep>/project4/code/TraderSpi/bin/test.sh
#!/bin/bash
./TraderServer 192.168.0.6 12345 55
<file_sep>/project4/code/TraderSpi/src/testTraderSpi.cpp
#include "ThostFtdcTraderApi.h"
#include "TraderSpi.h"
#include <unistd.h>
#include <iostream>
#include <cstring>
#include <string>
#include "Ini.h"

using namespace std;

CThostFtdcTraderApi* pUserApi;

char  FRONT_ADDR[] = "tcp://192.168.127.12:10000";
TThostFtdcBrokerIDType	BROKER_ID;
TThostFtdcInvestorIDType INVESTOR_ID;
TThostFtdcPasswordType  PASSWORD;
TThostFtdcInstrumentIDType INSTRUMENT_ID;

int LoginFlag = 0;
int iRequestID = 0;
char *OrderFilePath = new char[256];

void loadInfoFromFile(char *filePath)
{
	CIni ini;
	ini.OpenFile(filePath,"r");
	char *broId = ini.GetStr("Broker","ID");
	strcpy(BROKER_ID, broId);
	char *invId = ini.GetStr("Investor","ID");
	strcpy(INVESTOR_ID, invId);
	char *pwd = ini.GetStr("Investor","Password");
	strcpy(PASSWORD, pwd);
	char *insId = ini.GetStr("Instrument", "Ins");
	strcpy(INSTRUMENT_ID, insId);
}

int main(int argc, char *argv[])
{

	char ch;
	while((ch = getopt(argc, argv, "b:i:p:s:f:t:h")) != -1){
        switch(ch){
            case 'b':
            	strcpy(BROKER_ID, optarg);
                break;
            case 'i':
                strcpy(INVESTOR_ID, optarg);
				break;
            case 'p':
                strcpy(PASSWORD, optarg);
				break;
			case 's':
				strcpy(INSTRUMENT_ID, optarg);
				break;
			case 'f':
				char *configFilePath;
				configFilePath = optarg;
				loadInfoFromFile(configFilePath);
				break;
            case 'h':
                cout << "-h help" << endl;
                cout << "-b broker id" << endl;
                cout << "-i investor id" << endl;
                cout << "-p password" << endl;
                cout << "-s instrument id" << endl;
                cout << "-f config.ini file" << endl;
                break;
            default:
                cout << "input -h to check usage of the code" << endl;
                break;
        }
    }

	pUserApi = CThostFtdcTraderApi::CreateFtdcTraderApi();
	CTraderSpi* pUserSpi = new CTraderSpi();
	pUserApi->RegisterSpi((CThostFtdcTraderSpi*)pUserSpi);
	pUserApi->SubscribePublicTopic(THOST_TERT_QUICK);
	pUserApi->SubscribePrivateTopic(THOST_TERT_QUICK);
	pUserApi->RegisterFront(FRONT_ADDR);
	pUserApi->Init();

	char *order = new char[256];
	while(!LoginFlag){ }
	cout << "input your order: ";
	while(1){
		cin.getline(order, 256);
		if(strcmp(order, "login") == 0){
			while(!LoginFlag){ }
			pUserSpi->ReqUserLogin();
		}
		else if(strcmp(order, "queryInstrument") == 0){
			cout << "input the instrument id: ";
			cin.getline(INSTRUMENT_ID, 256);
			pUserSpi->ReqQryInstrument();
		}
		else if(strcmp(order, "queryAccount") == 0){
			pUserSpi->ReqQryTradingAccount();
		}
		else if(strcmp(order, "queryPosition") == 0){
			pUserSpi->ReqQryInvestorPosition();
		}
		else if(strcmp(order, "insertOrder") == 0){
			cout << "input order infomation file path: ";
			cin.getline(OrderFilePath, 256);
			cout << OrderFilePath << endl;
			pUserSpi->ReqOrderInsert();
		}
		else if(strcmp(order, "cancalOrder") == 0){
			cout << "input instrument ID: ";
			string instrumentTemp;
			getline(cin,instrumentTemp);
			cout << "input orderSysID: ";
			string orderTemp;
			getline(cin,orderTemp);
			while(orderTemp.size() < 12) { orderTemp = ' ' + orderTemp; }
			pUserSpi->ReqQryOrder((char*)orderTemp.c_str());
		}
		else if(strcmp(order, "logout") == 0){
			LoginFlag = 0;
		}
		else{
			cout << "order error" << endl;
		}
	}
	delete[] order;

	pUserApi->Join();
//	pUserApi->Release();
	return 0;
}<file_sep>/project4/code/MdSpi/build/src/CMakeFiles/testMdSpi.dir/cmake_clean.cmake
file(REMOVE_RECURSE
  "CMakeFiles/testMdSpi.dir/testMdSpi.cpp.o"
  "../../bin/testMdSpi.pdb"
  "../../bin/testMdSpi"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/testMdSpi.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/project4/code/MdSpi/src/testMdSpi.cpp
#include <iostream>
#include "ThostFtdcMdApi.h"
#include "MdSpi.h"
#include "Ini.h"
#include <vector>
#include <string>
#include <cstring>
#include <unistd.h>

using namespace std;

CThostFtdcMdApi* pUserApi;

char FRONT_ADDR[] = "tcp://172.16.58.3:10010";
TThostFtdcBrokerIDType	BROKER_ID ;
TThostFtdcInvestorIDType INVESTOR_ID ;
TThostFtdcPasswordType  PASSWORD ;
char *ppInstrumentID[100];
int iInstrumentID = 0;

bool LoginFlag = 0;
int iRequestID = 0;
int dataNum = 0;

vector<string> split(const string &str,const string &pattern);

void InstrumentCopy(vector<string> myvector);

void loadInfoFromFile(char *filePath);

void loadInstrumentFromFile(char *filePath);

int main(int argc, char* argv[])
{
	char ch;
	string insTmp;
	string pattern = ",";
	vector<string> myInstrumentList;

	while((ch = getopt(argc, argv, "b:i:p:f:h")) != -1){
        switch(ch){
            case 'b':
            	strcpy(BROKER_ID, optarg);
                break;
            case 'i':
                strcpy(INVESTOR_ID, optarg);
				break;
            case 'p':
                strcpy(PASSWORD, optarg);
				break;
			case 'f':
				char *configFilePath;
				configFilePath = optarg;
				loadInfoFromFile(configFilePath);
				break;
            case 'h':
                cout << "-h help" << endl;
                cout << "-b broker id" << endl;
                cout << "-i investor id" << endl;
                cout << "-p <PASSWORD>" << endl;
                cout << "-f config.ini file" << endl;
                break;
            default:
                cout << "input -h to check usage of the code" << endl;
                break;
        }
    }

	pUserApi = CThostFtdcMdApi::CreateFtdcMdApi();
	CMdSpi* pUserSpi = new CMdSpi();
	pUserApi->RegisterSpi(pUserSpi);
	pUserApi->RegisterFront(FRONT_ADDR);
	pUserApi->Init();

	char *order = new char[256];
	while(!LoginFlag){ }
	cout << "input your order: ";
	while(1){
		cin.getline(order,256);
		if(strcmp(order, "login") == 0){
			while(!LoginFlag){ }
			pUserSpi->ReqUserLogin();
		}
		else if(strcmp(order, "SMD") == 0){
			cout << "input the number of instrument list: ";
			cin >> iInstrumentID;
			cout << "input the instrument list divided with ',': ";
			cin >> insTmp;
			myInstrumentList.clear();
			myInstrumentList = split(insTmp, pattern);
			InstrumentCopy(myInstrumentList);
			pUserSpi->SubscribeMarketData();
		}
		else if(strcmp(order, "USMD") == 0){
			cout << "input the number of instrument list: ";
			cin >> iInstrumentID;
			cout << "input the instrument list divided with ',': ";
			cin >> insTmp;
			cin.sync();
			myInstrumentList.clear();
			myInstrumentList = split(insTmp, pattern);
			InstrumentCopy(myInstrumentList);
			pUserSpi->UnSubscribeMarketData();
		}
		else if(strcmp(order, "SMDFF") == 0){
			cout << "input file path: ";
			char *InstrumentFile = new char[256];
			cin.getline(InstrumentFile, 256);
			loadInstrumentFromFile(InstrumentFile);
			pUserSpi->SubscribeMarketData();
		}
		else if(strcmp(order, "SQ") == 0){

		}
		else if(strcmp(order, "USQ") == 0){

		}
		else if(strcmp(order, "logout") == 0){
			LoginFlag = 0;
		}
		else{
			cout << "order error" << endl;
		}
	}
	delete[] order;

	pUserApi->Join();
	return 0;
}

vector<string> split(const string &str,const string &pattern)
{
    //const char* convert to char*
    char * strc = new char[strlen(str.c_str())+1];
    strcpy(strc, str.c_str());
    vector<string> resultVec;
    char* tmpStr = strtok(strc, pattern.c_str());
    while (tmpStr != NULL)
    {
        resultVec.push_back(string(tmpStr));
        tmpStr = strtok(NULL, pattern.c_str());
    }

    delete[] strc;

    return resultVec;
}

void InstrumentCopy(vector<string> myvector)
{
	for (int i=0; i<iInstrumentID; i++){
		ppInstrumentID[i] = (char*)myvector[i].data();
	}
}

void loadInfoFromFile(char *filePath)
{
	CIni ini;
	ini.OpenFile(filePath,"r");
	char *broId = ini.GetStr("Broker","ID");
	strcpy(BROKER_ID, broId);
	char *invId = ini.GetStr("Investor","ID");
	strcpy(INVESTOR_ID, invId);
	char *pwd = ini.GetStr("Investor","Password");
	strcpy(PASSWORD, pwd);
}

void loadInstrumentFromFile(char *filePath)
{
	CIni ini;
	ini.OpenFile(filePath, "r");
	iInstrumentID = ini.GetInt("InstrumentNum", "Num");
	char InstrumentCode[4] = {'I','n','s','1'};
	string temp[iInstrumentID];
	for(int i=0;i<iInstrumentID;i++)
	{
		InstrumentCode[3] = (char)(i+49);
		temp[i] = ini.GetStr("Instrument", InstrumentCode);
		ppInstrumentID[i] = (char*)temp[i].data();
	}
}<file_sep>/project4/code/MdSpi/build/src/CMakeFiles/Ini.dir/cmake_clean.cmake
file(REMOVE_RECURSE
  "CMakeFiles/Ini.dir/Ini.cpp.o"
  "../../lib/libIni.pdb"
  "../../lib/libIni.a"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/Ini.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/project3/code/project3.cpp
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<algorithm>
#include<unistd.h>

using namespace std;

struct SubVal
{
	string substring;
	int value;
	vector<int> next;
	int pos;

	SubVal(){
		pos = -1;
	}
};

struct Output
{
	string target;
	int value_sum;
	vector<SubVal> path;

	Output(){
		value_sum = 0;
	}
};

bool cmp(SubVal sv1, SubVal sv2){
	return sv1.value > sv2.value;
}

void calNext(string str, vector<int> &next, int len){
	next.push_back(-1);
	int k=-1;
	for(int q=1; q<=len-1; q++){
		while(k>-1 && str[k+1]!=str[q]){
			k=next[k];
		}
		if(str[k+1]==str[q]){
			k=k+1;
		}
		next.push_back(k);
	}
}

int KMP(string str, SubVal substr){
	int slen = str.size();
	int plen = substr.substring.size();
	int k=-1;
	for(int i=0;i<slen;i++){
		while(k>-1 && substr.substring[k+1]!=str[i])
			k = substr.next[k];
		if(substr.substring[k+1] == str[i])
			k = k+1;
		if(k == plen-1){
			return i-plen+1;
		}
	}
	return -1;
}

Output addPath(Output &op1, Output &op2){
	Output op_tmp = op1;
	for(int i=0;i<op2.path.size();i++){
		op_tmp.path.push_back(op2.path[i]);
	}
	return op_tmp;
}

Output dfs(string str, vector<SubVal> &mySV, vector<Output> &max_tmp){
	for(int i=0;i<max_tmp.size();i++){
		if(str == max_tmp[i].target){
			return max_tmp[i];
		}
	}

	Output re_tmp;
	re_tmp.target = str;

	if(str == ""){
		return re_tmp;
	}
	else{
		Output op_tmp = re_tmp;

		for(int i=0;i<mySV.size();i++){
			Output tmp = op_tmp;
			string str_tmp = str;
			int pos_tmp = KMP(str, mySV[i]);
			if(pos_tmp != -1){
				mySV[i].pos = pos_tmp;
				tmp.path.push_back(mySV[i]);
				tmp.value_sum += mySV[i].value;
				// cout<<str_tmp<<"+++"<<mySV[i].substring<<endl;

				str_tmp.erase(pos_tmp, mySV[i].substring.size());

				Output temp = dfs(str_tmp, mySV, max_tmp);
				if(temp.value_sum + tmp.value_sum > re_tmp.value_sum){
					re_tmp = addPath(tmp, temp);
					re_tmp.value_sum = temp.value_sum + tmp.value_sum;
				}
			}
		}
		max_tmp.push_back(re_tmp);//cout<<re_tmp.target<<"----"<<re_tmp.value_sum<<endl;
		return re_tmp;
	}
}

Output dfsInit(string str, vector<SubVal> &mySV){
	Output result;
	vector<Output> max_tmp;
	result.target = str;

	Output result_tmp = result;

	for(int i=0;i<mySV.size();i++){
		Output op_tmp = result_tmp;
		string str_tmp = str;
		int pos_tmp = KMP(str, mySV[i]);
		if( pos_tmp != -1){
			mySV[i].pos = pos_tmp;
			op_tmp.path.push_back(mySV[i]);
			op_tmp.value_sum += mySV[i].value;
			// cout<<str_tmp<<"+++"<<mySV[i].substring<<endl;

			str_tmp.erase(pos_tmp, mySV[i].substring.size());

			Output temp = dfs(str_tmp, mySV, max_tmp);

			if(temp.value_sum + op_tmp.value_sum > result.value_sum){
				result = addPath(op_tmp, temp);
				result.value_sum = temp.value_sum + op_tmp.value_sum;
			}
		}
	}
	return result;
}

int main( int argc, char* argv[] )
{
	string in_file = argv[1];
	string out_file = argv[2];

    ifstream in(in_file.c_str());
	int str_len, subset_len;
	string str;
	in>>str_len>>subset_len>>str;
	vector<SubVal> mySV;
	SubVal temp;
	for(int i=0;i<subset_len;i++){
		in>>temp.substring>>temp.value;
		calNext(temp.substring, temp.next, temp.substring.size());
		mySV.push_back(temp);
	}

//	sort(mySV.begin(), mySV.end(), cmp);
	Output op_result = dfsInit(str, mySV);

	ofstream out(out_file.c_str());
	for(int i=0;i<op_result.path.size();i++){
		out<<op_result.path[i].pos<<" "<<op_result.path[i].substring<<endl;
	}
	out<<op_result.value_sum<<endl;

	return 0;
}

<file_sep>/project4/code/TraderSpi/bin/config.ini
[Broker]
ID=9999

[Investor]
ID=112585
Password=<PASSWORD>

[Instrument]
Ins=al1803

[FrontAddr]
Addr=tcp://172.16.31.10:10000
<file_sep>/project4/code/MdSpi/inc/MdSpi.h
#include "ThostFtdcMdApi.h"

class CMdSpi : public CThostFtdcMdSpi
{
public:

	// used before connected
	virtual void OnFrontConnected();

	//
	virtual void OnFrontDisconnected(int nReason);

	//
	virtual void OnHeartBeatWarning(int nTimeLapse);

	// response for login
	virtual void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ;

	// response for error
	virtual void OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ;

	//
	virtual void OnRspSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ;

	virtual void OnRspUnSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ;

	virtual void OnRspSubForQuoteRsp(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ;

	virtual void OnRspUnSubForQuoteRsp(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ;

	// more information
	virtual void OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData) ;

	//
	virtual void OnRtnForQuoteRsp(CThostFtdcForQuoteRspField *pForQuoteRsp) ;

public:
	void ReqUserLogin();

	void SubscribeMarketData();

	void UnSubscribeMarketData();

	void SubscribeForQuoteRsp();

	bool IsErrorRspInfo(CThostFtdcRspInfoField *pRspInfo);

};<file_sep>/project4/code/MdSpi/build/src/CMakeFiles/MdSpi.dir/cmake_clean_target.cmake
file(REMOVE_RECURSE
  "../../lib/libMdSpi.a"
)
<file_sep>/project4/code/MdSpi/build/src/CMakeFiles/MdSpi.dir/cmake_clean.cmake
file(REMOVE_RECURSE
  "CMakeFiles/MdSpi.dir/MdSpi.cpp.o"
  "../../lib/libMdSpi.pdb"
  "../../lib/libMdSpi.a"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/MdSpi.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/project4/code/TraderSpi/build/src/CMakeFiles/CTraderSpi.dir/cmake_clean_target.cmake
file(REMOVE_RECURSE
  "../../lib/libCTraderSpi.a"
)
<file_sep>/project4/code/TraderSpi/src/CtestTraderSpi.cpp
#include "ThostFtdcTraderApi.h"
#include "CTraderSpi.h"
#include <unistd.h>
#include <iostream>
#include <cstring>
#include <string>
#include "Ini.h"

using namespace std;

int main(int argc, char *argv[])
{
	CTraderSpi *pUserSpi = new CTraderSpi();

	char ch;
	while((ch = getopt(argc, argv, "f:h")) != -1){
        switch(ch){
			case 'f':
				char *configFilePath;
				configFilePath = optarg;
				pUserSpi->SetConfigInfo(configFilePath);
				pUserSpi->Init();
				break;
            case 'h':
                cout << "-h help" << endl;
                cout << "-b broker id" << endl;
                cout << "-i investor id" << endl;
                cout << "-p password" << endl;
                cout << "-s instrument id" << endl;
                cout << "-f config.ini file" << endl;
                break;
            default:
                cout << "input -h to check usage of the code" << endl;
                break;
        }
    }

	char *order = new char[256];
	while(1){
		cin.getline(order, 256);
		if(strcmp(order, "login") == 0){
			pUserSpi->ReqUserLogin();
		}
		else if(strcmp(order, "queryInstrument") == 0){
			cout << "input the instrument id: ";
			char *instrumentID = new char[256];
			cin.getline(instrumentID, 256);
			pUserSpi->ReqQryInstrument();
			delete[] instrumentID;
		}
		else if(strcmp(order, "queryAccount") == 0){
			pUserSpi->ReqQryTradingAccount();
		}
		else if(strcmp(order, "queryPosition") == 0){
			pUserSpi->ReqQryInvestorPosition();
		}
		else if(strcmp(order, "insertOrder") == 0){
			cout << "input order infomation file path: ";
			char *orderFilePath = new char[256];
			cin.getline(orderFilePath, 256);
			cout << orderFilePath << endl;
			pUserSpi->ReqOrderInsert(orderFilePath);
			delete[] orderFilePath;
		}
		else if(strcmp(order, "cancalOrder") == 0){
			cout << "input orderSysID: ";
			string orderTemp;
			getline(cin,orderTemp);
			while(orderTemp.size() < 12) { orderTemp = ' ' + orderTemp; }
			pUserSpi->ReqQryOrder((char*)orderTemp.c_str());
		}
		else if(strcmp(order, "logout") == 0){

		}
		else{
			cout << "order error" << endl;
		}
	}
	delete[] order;

	return 0;
}<file_sep>/project4/code/MdSpi/bin/config.ini
[Broker]
ID=9999

[Investor]
ID=112585
Password=<PASSWORD><file_sep>/project2/code/indicatorGallexy.py
# coding: utf-8
import numpy as np
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt

class IndicatorGallexy:
    def __init__(self, data):
        self.data = data
        self.col_head = data.columns.values.tolist()

    def isValidDate(self, str):
        try:
            dt.datetime.strptime(str, "%Y-%m-%d")
            return True
        except:
            return False

    def isValidTime(self, str):
        try:
            dt.datetime.strptime(str, "%Y-%m-%d %H:%M:%S")
            return True
        except:
            return False

    def dateAccess(self, date_col_head='date'):
        """判断日期格式是否能够处理，并采取对应处理措施"""
        if date_col_head not in self.col_head:
            print date_col_head+" is no exit"
            return None
        else:
            self.data = self.data.sort_values(by=date_col_head, ascending=True)
            self.data = self.data.reset_index(drop=True)
            year_col_head = 'year'  #dataframe列名
            month_col_head = 'month'
            day_col_head = 'day'
            hour_col_head = 'hour'
            minute_col_head = 'minute'
            second_col_head = 'second'

            date = []
            if self.isValidDate(self.data[date_col_head][0]):
                for i in range(len(self.data[date_col_head])):
                    date.append(dt.datetime.strptime(self.data[date_col_head][i], "%Y-%m-%d"))
                date_list = []
                for d in date:
                    temp = []
                    temp.append(d.year)
                    temp.append(d.month)
                    temp.append(d.day)
                    date_list.append(temp)
                del self.data[date_col_head]
                date_frame = pd.DataFrame(date_list, columns=[year_col_head, month_col_head, day_col_head])
                self.data = pd.concat([date_frame, self.data], axis=1)
                self.col_head = self.data.columns.values.tolist()

            elif self.isValidTime(self.data[date_col_head][0]):
                for i in range(len(self.data[date_col_head])):
                    date.append(dt.datetime.strptime(self.data[date_col_head][i], "%Y-%m-%d %H:%M:%S"))
                date_list = []
                for d in date:
                    temp = []
                    temp.append(d.year)
                    temp.append(d.month)
                    temp.append(d.day)
                    temp.append(d.hour)
                    temp.append(d.minute)
                    temp.append(d.second)
                    date_list.append(temp)
                del self.data[date_col_head]
                date_frame = pd.DataFrame(date_list, columns=[year_col_head, month_col_head, day_col_head, hour_col_head, minute_col_head, second_col_head])
                self.data = pd.concat([date_frame, self.data], axis=1)
                self.col_head = self.data.columns.values.tolist()

            else:
                print "the data format can't be processed"
                return None

    def getAtt(self, s_att):
        """返回某一属性列值"""
        s_att = self.data[s_att]
        return s_att

    def getEMA(self, col='close', ema_model='ema12', ema_molecule=11, ema_denominator=13, init_ema=0):
        """
            EMA(12) = EMA(12) * 11/13 + close * 2/13
            EMA(26) = EMA(26) * 25/27 + close * 2/27
        """
        ema_model = ema_model+'_'+col
        fac1 = ema_molecule / ema_denominator
        fac2 = 1 - fac1

        ema = []
        ema.append(init_ema * fac1 + self.data[col][0] * fac2)
        for i in range(1, len(self.data[col])):
            ema.append(ema[i-1] * fac1 + self.data[col][i] * fac2)

        ema = pd.DataFrame(ema, columns=[ema_model])
        return ema

    def getDIFF(self, first_ema, second_ema, col='close'):
        """  DIFF = EMA(12) - EMA(26) """
        first_ema_col_head = first_ema.columns.values.tolist()
        second_ema_col_head = second_ema.columns.values.tolist()
        diff_col_head = 'diff_'+col

        diff = []
        for i in range(len(first_ema)):
            temp = first_ema[first_ema_col_head[0]][i] - second_ema[second_ema_col_head[0]][i]
            diff.append(temp)
        diff = pd.DataFrame(diff, columns=[diff_col_head])
        return diff

    def getDEA(self, diff, dea_molecule=8, dea_denominator=10, init_dea=0, col='close'):
        """ DEA = DEA * 8/10 + DIF * 2/10 """
        diff_col_head = diff.columns.values.tolist()
        dea_head = 'dea_'+col
        fac1 = dea_molecule / dea_denominator
        fac2 = 1 - fac1

        dea = []
        dea.append(init_dea * fac1 + diff[diff_col_head[0]][0] * fac2)

        for i in range(1,len(diff)):
            dea.append(dea[i-1] * fac1 + diff[diff_col_head[0]][i] * fac2)

        dea = pd.DataFrame(dea, columns=[dea_head])
        return dea

    def getMACD(self, diff, dea, col='close'):
        """ macd = 2 * (DIFF - DEA) """
        diff_col_head = diff.columns.values.tolist()
        dea_col_head = dea.columns.values.tolist()
        macd_col_head = 'macd_'+col

        macd = []
        for i in range(len(diff)):
            macd.append(2 * (diff[diff_col_head[0]][i] - dea[dea_col_head[0]][i]))

        macd = pd.DataFrame(macd, columns=[macd_col_head])
        return macd

    def getBOLL(self):
        """compute boll"""
        pass

    def getRSI(self, selected_att='price_change', power=100):
        """RSI(N) = A / (A+B) * 100"""
        posi = 0
        nega = 0
        colhead = 'rsi_'+selected_att

        rsi = []
        length = len(self.data[selected_att]) - 5
        for i in range(length):
            for j in range(5):
                if self.data[selected_att][i+j] > 0:
                    posi += self.data[selected_att][i+j]
                else:
                    nega += self.data[selected_att][i+j]
            rsi.append(posi * (posi - nega ) * power)
        for i in range(5):
            rsi.append(rsi[length])

        rsi = pd.DataFrame(rsi, columns=[colhead])
        return rsi

    def mergeData(self, add_att_df):
        self.data = pd.concat([self.data, add_att_df], axis=1)

    def getColHead(self):
        self.col_head = self.data.columns.values.tolist()
        return self.col_head

    def getData(self):
        return self.data

    def plotData(self, col_list):
        """根据输入的属性列表，画出对比图像"""
        temp_list = []
        for cl in col_list:
            if cl not in self.col_head:
                print cl+' not in the data set'
            else:
                temp_list.append(self.data[cl])

        temp_df = pd.concat(temp_list, axis=1)
        temp_df.plot()
        plt.show()

if __name__ == "__main__":
    data = pd.read_csv("data/1day/000001.csv")

    xmIG = IndicatorGallexy(data)

    xmIG.dateAccess('date')

    ema12 = xmIG.getEMA()
    ema26 = xmIG.getEMA('close', 'ema26', 25, 27, 0)
    xmIG.mergeData(ema12)
    xmIG.mergeData(ema26)

    diff = xmIG.getDIFF(ema12, ema26)
    xmIG.mergeData(diff)

    dea = xmIG.getDEA(diff, 8, 10, 0)
    xmIG.mergeData(dea)

    macd = xmIG.getMACD(diff, dea)
    xmIG.mergeData(macd)

    col_list = ['open', 'close']
    xmIG.plotData(col_list)<file_sep>/project2/code/main.py
# coding: utf-8
import argparse
import copy as cp
import pandas as pd
import indicatorGallexy as ig
import dataAccess as da
import model as md
import fastResearchData as frd

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument("-sc", "--stock_code", type=str, default='000001', help="the stock codes you want to load")
    parser.add_argument("-l", "--label", type=str, default="price_change", help="the label you want to predict")
    parser.add_argument("-d", "--date", type=str, default="date", help="the col name of date_data")
    parser.add_argument("-da","--del_att",type=str,default='year,month,day',help="the attributes you want to delete")
    parser.add_argument("-m", "--method", type=str, default='NN', help="select model in NN\DT\SVM\KNN\RNN")
    parser.add_argument("-r", "--ratio", type=int, default=9, help="the ratio used to divide train and test")
    parser.add_argument("-t", "--test", type=int, default=0, help="if you want to compare the results between all models, input 1")
    args = parser.parse_args()

    stock_code = args.stock_code
    print stock_code
    label = args.label
    del_att = args.del_att.split(',')
    date = args.date
    ratio = args.ratio
    test = args.test
    method = args.method

    dir_path = 'data/1day/'
    xmFRD = frd.FastResearchData(dir_path)
    xmFRD.loadStockData(stock_code)
    xmIG = ig.IndicatorGallexy(xmFRD.getDataFrame(stock_code))
    xmIG.dateAccess(date)
    xmIG.getData().to_csv("process_data/"+stock_code+'.csv', index=False)

    ema12 = xmIG.getEMA()
    ema26 = xmIG.getEMA('close', 'ema26', 25, 27, 0)
    xmIG.mergeData(ema12)
    xmIG.mergeData(ema26)
    diff = xmIG.getDIFF(ema12, ema26)
    xmIG.mergeData(diff)
    dea = xmIG.getDEA(diff, 8, 10, 0)
    xmIG.mergeData(dea)
    macd = xmIG.getMACD(diff, dea)
    xmIG.mergeData(macd)

    xmIG_data = xmIG.getData()
    # xmIG_data_col_head = xmIG.getColHead()

    xmDA = da.DataAccess(xmIG_data)
    # xmDA.oneHotEncode(['year', 'month', 'day'])
    select_att = xmDA.getColHead()
    xmDA.selectLabel(label)
    select_att.remove(label)
    for temp in del_att:
        select_att.remove(temp)
    print select_att
    xmDA.selectAtt(select_att)
    train_x, train_y, test_x, test_y = xmDA.divideData(ratio)

    xmModel = md.Model()

    if test == 1:
        model_list = ['NN', 'DT', 'SVM', 'KNN', 'RNN']
        xmModel.algorithmCompare(train_x, train_y, test_x, test_y, model_list)
    else:
        xmModel.modelBuild(train_x, train_y, method)
        pre_result = xmModel.modelPredict(test_x)
        xmModel.plotResult(test_y, pre_result, method)
        xmModel.algorithmEvaluate(test_y, pre_result)<file_sep>/project4/code/MdSpi/src/MdSpi.cpp
#include "MdSpi.h"
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

extern CThostFtdcMdApi* pUserApi;

extern char FRONT_ADDR[];
extern TThostFtdcBrokerIDType	BROKER_ID;
extern TThostFtdcInvestorIDType INVESTOR_ID;
extern TThostFtdcPasswordType	<PASSWORD>;
extern char* ppInstrumentID[];
extern int iInstrumentID;

extern bool LoginFlag;
extern int iRequestID;
extern int dataNum;

bool CMdSpi::IsErrorRspInfo(CThostFtdcRspInfoField *pRspInfo)
{
	bool bResult = ((pRspInfo) && (pRspInfo->ErrorID != 0));
	if (bResult)
		cout << "--->>> ErrorID=" << pRspInfo->ErrorID << ", ErrorMsg=" << pRspInfo->ErrorMsg << endl;
	return bResult;
}

void CMdSpi::OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	IsErrorRspInfo(pRspInfo);
}

void CMdSpi::OnFrontConnected()
{
	cout << "--->>> connect succeed" << endl;
	LoginFlag = 1;
	//ReqUserLogin();
}

void CMdSpi::ReqUserLogin()
{
	CThostFtdcReqUserLoginField req;
	memset(&req, 0, sizeof(req));
	strcpy(req.BrokerID, BROKER_ID);
	strcpy(req.UserID, INVESTOR_ID);
	strcpy(req.Password, <PASSWORD>);
	int iResult = pUserApi->ReqUserLogin(&req, ++iRequestID);
}

void CMdSpi::OnFrontDisconnected(int nReason)
{
	cout << "--->>> connect error for " << nReason << endl;
}

void CMdSpi::OnHeartBeatWarning(int nTimeLapse)
{
	cout << "--->>> nTimeLapse: " << nTimeLapse << endl;
}

void CMdSpi::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	if(bIsLast && !IsErrorRspInfo(pRspInfo))
	{
		cout << "--->>> login succeed!" << endl;
		cout << "Login date: " << pRspUserLogin->TradingDay << endl;
		cout << "FrontID: " << pRspUserLogin->FrontID << endl;
		cout << "SessionID: " << pRspUserLogin->SessionID << endl;
		//SubscribeMarketData();
		//SubscribeForQuoteRsp();
	}
	else
	{
		cout << "--->>> ErrorID: " << pRspInfo->ErrorID << endl;
		cout << "--->>> ErrorMsg: " << pRspInfo->ErrorMsg << endl;
	}
}

void CMdSpi::SubscribeMarketData()
{
	int iResult = pUserApi->SubscribeMarketData(ppInstrumentID, iInstrumentID);
	//cout << "--->>> Subscribe market data: " << ((iResult == 0) ? "succeed" : "default") << endl;
}

void CMdSpi::SubscribeForQuoteRsp()
{
	int iResult = pUserApi->SubscribeForQuoteRsp(ppInstrumentID, iInstrumentID);
	//cout << "--->>> Subscribe for quote response: " << ((iResult == 0) ? "succeed" : "default") << endl;
}

void CMdSpi::OnRspSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	if(!IsErrorRspInfo(pRspInfo))
	{
		cout << "--->>> Subscribe market data succeed" << endl;
		cout << "InstrumentID: " << pSpecificInstrument->InstrumentID << endl;
		char filePath[100] = {'\0'};
		sprintf(filePath, "%s_market_data.csv", pSpecificInstrument->InstrumentID);
		ofstream outFile;
		outFile.open(filePath, ios::out);
		outFile << "InstrumentID" << ","
				<< "UpdateTime" << "," //gengxinshijian
				<< "LastPrice" << "," //zuixinjia
				<< "PreSettlementPrice" << "," //shangci jiesuanjia
				<< "PreClosePrice" << ","  //zuo shoupan
				<< "PreOpenInterest" << "," //zuo chicangliang
				<< "OpenPrice" << "," //jin kaipan
				<< "HighestPrice" << "," //zuigaojia
				<< "LowestPrice" << "," //zuidijia
				<< "Volume" << "," //shuliang
				<< "Turnover" << "," //chengjiao jin'er
				<< "OpenInterest" << "," //chicangliang
				<< "ClosePrice" << "," //jin shoupan
				<< "SettlementPrice" << endl; //benci jiesuanjia
	}
	else
	{
		cout << "--->>> ErrorID: " << pRspInfo->ErrorID << endl;
		cout << "--->>> ErrorMsg: " << pRspInfo->ErrorMsg << endl;
	}
}

void CMdSpi::OnRspUnSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	if(!IsErrorRspInfo(pRspInfo))
	{
		cout << "--->>> Unsubscribe market data succeed" << endl;
		cout << "InstrumentID: " << pSpecificInstrument->InstrumentID << endl;
	}
	else
	{
		cout << "--->>> ErrorID: " << pRspInfo->ErrorID << endl;
		cout << "--->>> ErrorMsg: " << pRspInfo->ErrorMsg << endl;
	}
}

void CMdSpi::OnRspSubForQuoteRsp(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	if(!IsErrorRspInfo(pRspInfo))
	{
		cout << "--->>> Subscribe for quote response succeed" << endl;
		cout << "InstrumentID: " << pSpecificInstrument->InstrumentID << endl;
	}
	else
	{
		cout << "--->>> ErrorID: " << pRspInfo->ErrorID << endl;
		cout << "--->>> ErrorMsg: " << pRspInfo->ErrorMsg << endl;
	}
}

void CMdSpi::OnRspUnSubForQuoteRsp(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	if(!IsErrorRspInfo(pRspInfo))
	{
		cout << "--->>> Unsubscribe for quote response succeed" << endl;
		cout << "InstrumentID: " << pSpecificInstrument->InstrumentID << endl;
	}
	else
	{
		cout << "--->>> ErrorID: " << pRspInfo->ErrorID << endl;
		cout << "--->>> ErrorMsg: " << pRspInfo->ErrorMsg << endl;
	}
}

void CMdSpi::OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData)
{
	char filePath[100] = {'\0'};
	sprintf(filePath, "%s_market_data.csv", pDepthMarketData->InstrumentID);
	ofstream outFile;
	outFile.open(filePath, ios::app);
	outFile << pDepthMarketData->InstrumentID << ","
			<< pDepthMarketData->UpdateTime << ","
			<< pDepthMarketData->LastPrice << ","
			<< pDepthMarketData->PreSettlementPrice << ","
			<< pDepthMarketData->PreClosePrice << ","
			<< pDepthMarketData->PreOpenInterest << ","
			<< pDepthMarketData->OpenPrice << ","
			<< pDepthMarketData->HighestPrice << ","
			<< pDepthMarketData->LowestPrice << ","
			<< pDepthMarketData->Volume << ","
			<< pDepthMarketData->Turnover << ","
			<< pDepthMarketData->OpenInterest << ","
			<< pDepthMarketData->ClosePrice << ","
			<< pDepthMarketData->SettlementPrice << endl;
}

void CMdSpi::OnRtnForQuoteRsp(CThostFtdcForQuoteRspField *pForQuoteRsp)
{
	cout << "--->>> Quote response: " << endl;
	cout << "Date: " << pForQuoteRsp->TradingDay << endl;
	cout << "InstrumentID: " << pForQuoteRsp->InstrumentID << endl;
}

void CMdSpi::UnSubscribeMarketData()
{
	int iResult = pUserApi->UnSubscribeMarketData(ppInstrumentID, iInstrumentID);
}<file_sep>/project2/框架项目.md
# Sklearn 项目总结
## 1. 代码命名风格
* 模块名： 小写字母，单词之间用\_分割
* 包名: 小写字母，单词之间用\_分割
* 类名：单词首字母大写
* 普通变量：小写字母，单词之间用\_分割
* 实例变量：以\_开头，小写字母，单词之间用_分割
* 私有实例变量：以\_\_开头（2个下划线），小写字母，单词之间用_分割
* 专有变量：开头，结尾，一般为python的自有变量，不要以这种方式命名
* 普通函数：小写字母，单词之间用_分割
* 私有函数： 以__开头（2个下划线），小写字母，单词之间用分割
* 常量名：大写字母，单词之间用_分割

**错误例子**
```
def Data_Access(self):
	self.Name = 'error_example'
	self.A = 1 + 2
```

## 2. 框架结构规范
* **FastRearchData**
	可从多个不同的文件类型中读取数据，进行数据清洗、筛选等处理，组织生成更快更容易处理的数据格式
* **IndicatorGallexy**
	存放各种指标的计算方法，传入数据并计算相应指标结果并返回
* **ModelEngine**
	存放模型的构建函数、预测函数、模型评价指标计算函数等
* **一些小点**
	* 可将多个类分写到多个文件里，并使用import进行调用
	* 函数内不能存在对数字或字符串等对象的直接使用的情况，可变变量尽量通过参数传递进函数，其余可变变量应放置在函数体前面，以便修改
	* 将具有相同或相似功能的函数进行合写，以便对函数功能进行修改

## 3. 股票的一些指标
* **EMA(Exponential Moving Average) 指数平均数指标**
	* EMA是一种趋向类指标，指数平均数指标是以指数式递减加权的移动平均。
	* 计算公式：EMA_today = α x Pricetoday + ( 1 - α ) * EMA_yesterday
		其中，α为平滑指数。在计算MACD指标时，EMA计算中的N一般选取12和26天，因此α相应为2/13和2/27
		在EMA指标中，每天价格的权重系数以指数等比形式缩小。时间越靠近当今时刻，它的权重越大，说明EMA函数对近期的价格加强了权重比，更能及时反映近期价格波动情况。所以EMA比MA更具参考价值，而EMA也不容易出现死叉和金叉
* **DIFF 差离值**
	* 股价的短期均价与长期均价的差
	* 首先分别计算出收市价SHORT日指数平滑移动平均线与LONG日指数平滑移动平均线，分别记为EMA(SHORT）与EMA(LONG）
	* 求这两条指数平滑移动平均线的差，即：DIFF=EMA（SHORT）－EMA（LONG）
* **DEA**
	* DEA是DIF的一定时间的平均值
* **MACD 指数平滑移动平均线**
	* 由快的指数移动平均线（EMA12）减去慢的指数移动平均线（EMA26）得到快线DIF，再用2×（快线DIF-DIF的9日加权移动均线DEA）得到MACD柱
	* MACD的意义和双移动平均线基本相同，即由快、慢均线的离散、聚合表征当前的多空状态和股价可能的发展变化趋势，但阅读起来更方便
	* 当MACD从负数转向正数，是买的信号。当MACD从正数转向负数，是卖的信号
	* 当MACD以大角度变化，表示快的移动平均线和慢的移动平均线的差距非常迅速的拉开，代表了一个市场大趋势的转变
* **BOLL 布林线指标**
	* 布林线利用统计原理，求出股价的标准差及其信赖区间，从而确定股价的波动范围及未来走势，利用波带显示股价的安全高低价位
	* 计算：
		中轨线=N日的移动平均线
		上轨线=中轨线+两倍的标准差
		下轨线=中轨线－两倍的标准差

## 4. 个人框架设计
* 股票类：把股票单独作为一个类，类中存放有从.csv文件中读取出的数据，并提供计算上述其余几种指标的接口函数，以及将计算出的指标合并如总数据集中的接口函数
* 数据处理类：数据处理类中提供：选择预测对象、选择训练集属性列以及划分数据集的接口函数
* 模型选择类：模型选择类中提供：构建Nerual Network\Decision Tree\SVM\KNN\RNN模型的接口函数，结果预测函数，以及不同模型的比较函数

## 5. 个人总结
通过本次项目，熟悉了numpy以及pandas中的一些容器，如dataframe、list、array的用法，以及实现了sklearn中的一些机器学习模型。但是在项目实现过程中没有注意函数以及变量的命名规范，导致框架的可读性太差，另外，在框架的构建上，没有充分做到代码可重用性的要求。这些都是在以后的代码编写任务中需要多多注意的方面。<file_sep>/project2/readme.md
## 代码说明
### IndicatorGallexy
* isValidDate(self, str) & isValidTime(slef, str)
	判断传入字符串是否是可被处理的日期或时间格式

* dateAccess(self, date_col_head)
	* 根据前面的格式判断结果进行日期处理
	* date_col_head为传入字符串，代表dataframe中日期一列的列名
	* 5min数据和1day数据可以共同使用本函数进行处理

* getEMA(self, col='close', ema_model='ema12', ema_molecule=11, ema_denominator=13, init_ema=0)
	* 计算EMA指标
	* col: 被选择计算的列名
	* ema_model: 计算的ema指标类型
	* ema_molecule: 计算公式中的分子
	* ema_denominator: 计算公式中的分母
	* init_ema: 计算初始值

* getDIFF(self, first_ema, second_ema, col='close')
	* 计算DIFF指标
	* first_ema: 第一个ema指标
	* second_ema: 第二个ema指标
	* col: 被选择计算的列名

* getDEA(self, diff, dea_molecule=8, dea_denominator=10, init_dea=0, col='close')
	* 计算DEA指标

* getMACD(self, diff, dea, col='close')
	* 计算MACD指标

* getRSI(self, selected_att='price_change', power=100)
	* 计算RSI指标

* plotData(self, col_list):
	* 根据输入的属性列表，画出对比图像

### DataAccess
* selectLabel(self, label)
	* label: 字符串类型，代表选择的要预测的Y

* selectAtt(self, selected_att)
	* selected_att: 字符串list，代表要选择的用于训练的属性集

* divideData(self, num)
	* num：表示以num+1个样本为一组划分训练集和验证集，并执行y移位操作

* storeToPickle(self, data, file_path):
	* 把数据或者模型转存成pickle文件

### Model
* modelBuild(self, train_x, train_y, selected_model='NN')
	* 根据selected_model来选择构建的机器学习模型

* modelPredict(self, test_x)
	* 预测函数

* plotResult(self, test_y, pre_result, ti)
	* 使用画图方法比较预测结果与真实值的差别
	* ti: 字符串类型，用户plot()函数的title属性

* algorithmCompare(self, train_x, train_y, test_x, test_y, model_list=[])
	* 模型比较函数，根据输入的model_list，分别画出预测结果图和计算出相应模型评价指标
	* model_list: 字符串list

* algorithmEvaluate(self, test_y, pre_result)
	* 模型评价指标计算函数，包括MSE, MAE, EVS

### FastResearchData
* getCode(self, file_path):
	* 获取路径中的股票编号

* loadFromDataFrame(self, stock_code, df):
	* 把dataframe对象存入字典

* loadStockData(self, stock_code, file_type='csv', sheet_name=''):
	* 根据输入的文件类型、股票编号，生成对应的文件路径，并通过该文件路径读取数据
	* 用于数据更新

* loadFromFile(self, file_path, file_type='csv', sheet_name=''):
	* 根据数据的文件类型以及文件路径读取数据，存入字典

<file_sep>/project4/code/TraderSpi/src/TraderServer.cpp
#include <iostream>

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <vector>
#include <pthread.h>

#include "Ini.h"
#include "ThostFtdcTraderApi.h"
#include "CTraderSpi.h"

using namespace std;

#define BUFFER_SIZE 1024

int socketBuild(char *ip, int port, int backlog);
void socketGetClient(int &fd, CTraderSpi *mySpi);
void orderMatch(char *order, int &connfd, CTraderSpi *mySpi);
void recvFile(char *filePath, int &connfd);

int main(int argc, char *argv[])
{
	char *localIP = "192.168.0.6";
	int localBacklog = 10;
	int localPort = 0;
	char *configFilePath = new char[256];

	bool isError = 0;

	char ch;
	while((ch = getopt(argc, argv, "p:c:h")) != -1){
        switch(ch){
            case 'p':
            	localPort = atoi(optarg);
            	break;
            case 'c':
            	strcpy(configFilePath, optarg);
            	break;
            case 'h':
                cout << "-h: help list" << endl;
                cout << "-p: tcp port" << endl;
                cout << "-c: config file path" << endl;
                isError = 1;
                break;
            default:
                cout << "input -h to check usage of the code" << endl;
                isError = 1;
                break;
        }
    }

    if(!isError){
    	cout << localPort << " " << configFilePath<< endl;

	    CTraderSpi *pUserSpi = new CTraderSpi;
	    pUserSpi->SetConfigInfo(configFilePath);
	    pUserSpi->Init();
	    pUserSpi->ReqUserLogin();

	    int fd = socketBuild(localIP, localPort, localBacklog);
	    while(1){
	    	socketGetClient(fd, pUserSpi);
	    }
	    close(fd);
    }

    delete[] configFilePath;
    return 0;
}

int  socketBuild(char *ip, int port, int backlog)
{
    int fd;
    int check_ret;

    fd = socket(PF_INET,SOCK_STREAM , 0);
    assert(fd >= 0);

    struct sockaddr_in address;
    bzero(&address,sizeof(address));

    address.sin_port = htons(port);
    address.sin_family = AF_INET;

    inet_pton(AF_INET, ip, &address.sin_addr);

    int recvbuf = 4096;
    int len = sizeof( recvbuf );
    setsockopt( fd, SOL_SOCKET, SO_RCVBUF, &recvbuf, sizeof( recvbuf ) );
    getsockopt( fd, SOL_SOCKET, SO_RCVBUF, &recvbuf, ( socklen_t* )&len );
    printf( "the receive buffer size after settting is %d\n", recvbuf );

    check_ret = bind(fd,(struct sockaddr*)&address,sizeof(address));
    assert(check_ret >= 0);

    check_ret = listen(fd, backlog);
    assert(check_ret >= 0);

    return fd;
}

void socketGetClient(int &fd, CTraderSpi *mySpi)
{
	struct sockaddr_in addressClient;
    socklen_t clientLen = sizeof(addressClient);

    int connfd = accept(fd, (struct sockaddr*)&addressClient, &clientLen);
    if(connfd < 0){
        cout << "accept error" << endl;
    }
    else{
        char showData[INET_ADDRSTRLEN];
        cout <<inet_ntop(AF_INET,&addressClient.sin_addr,showData,INET_ADDRSTRLEN)<<":" <<ntohs(addressClient.sin_port)<<endl;

        const int BUF_LEN = 1024;
        char sockBuf[BUF_LEN];
        size_t ret;

        memset(sockBuf, '\0' ,BUF_LEN);
        ret = recv(connfd, sockBuf, BUF_LEN-1, 0);
        if(ret > 0){
            printf("ret=%ld,msg=%s\n",ret,sockBuf);
            orderMatch(sockBuf, connfd, mySpi);
            bzero(sockBuf, BUF_LEN);
        }
    }
}

void orderMatch(char *order, int &connfd, CTraderSpi *mySpi)
{
    const int BUF_LEN = 1024;
    char sockBuf[BUF_LEN];
    bzero(sockBuf, BUF_LEN);

    if(strcmp(order, "queryAccount") == 0){
        mySpi->ReqQryTradingAccount();
    }
    else if(strcmp(order, "queryPosition") == 0){
        mySpi->ReqQryInvestorPosition();
    }
    else if(strcmp(order, "insertOrder") == 0){
    	int ret = recv(connfd, sockBuf, BUF_LEN-1, 0);
        char *filePath = new char[256];
        strcpy(filePath, sockBuf);
        recvFile(filePath, connfd);

        mySpi->ReqOrderInsert(filePath);
    }
    else if(strcmp(order, "cancalOrder") == 0){
    	int ret = recv(connfd, sockBuf, BUF_LEN-1, 0);
    	char *orderSysID = new char[256];
    	strcpy(orderSysID, sockBuf);

    }
    else if(strcmp(order, "logout") == 0){

    }
    else if(strlen(order)>0){
        cout << "order error" << endl;
    }
    bzero(sockBuf, BUF_LEN);
}

void recvFile(char *filePath, int &connfd)
{
    FILE *fp = fopen(filePath, "w");
    int FILESIZE = 1024;
    char orderFile[FILESIZE];
    if(fp == NULL){
        printf("File:\t%s Can Not Open To Write!\n", filePath);
        exit(1);
    }
    else{
        bzero(orderFile, FILESIZE);

        int length = recv(connfd, orderFile, FILESIZE, 0);
        if (length < 0){
            printf("Recieve Data Failed!\n");
        }
        int write_length = fwrite(orderFile, sizeof(char), length, fp);
        if (write_length < length){
            printf("File:\t%s Write Failed!\n", filePath);
        }
        printf("Recieve File:\t%s Finished!\n", filePath);

        fclose(fp);
    }
}
<file_sep>/project4/code/TraderSpi/build/src/CMakeFiles/Ini.dir/cmake_clean_target.cmake
file(REMOVE_RECURSE
  "../../lib/libIni.a"
)
<file_sep>/project4/code/TraderSpi/build/src/CMakeFiles/CtestTraderSpi.dir/cmake_clean.cmake
file(REMOVE_RECURSE
  "CMakeFiles/CtestTraderSpi.dir/CtestTraderSpi.cpp.o"
  "../../bin/CtestTraderSpi.pdb"
  "../../bin/CtestTraderSpi"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/CtestTraderSpi.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/project3/report.md
## Project3 总结
### C++编译过程
总的来说，C++编译过程包括预编译、汇编、编译、链接四个过程
* **预编译** 预编译主要展开包含的头文件，宏定义等操作。即如果包含了某一个.h文件，那么整个.h文件会在预编译的过程中被包含进来。
* **汇编** 汇编过程就是把已经预编译的文件编译成汇编代码的过程，整个过程会包含语法、词法的分析，和一些优化操作。
* **编译** 编译过程是将汇编代码变成机器码，即二进制(.o)文件。
* **链接** 链接过程是将单个编译后的文件链接成一个可执行程序。

在实际应用中，如果不是需要，一般会将上述整个过程合并，直接从.cpp文件产生最终的可执行文件；亦或者是编写makefile文件，在makefile文件中，一般将省略上述的“预编译”以及“汇编”过程。

### Makefile
Makefile文件是用于告诉make命令需要怎么样的去编译和链接程序。该文件主要体现了一种文件之间的依赖关系，每个.o文件会依赖于该文件对应的.cpp和.h文件，可执行文件依赖于所有的.o文件，当某个.cpp或者.h文件发生改变，其对应的所有.o文件需要再重新编译一遍，可执行文件耶需要再重新链接一遍。
关于Makefile的语法，可以参考 [http://wiki.ubuntu.org.cn/%E8%B7%9F%E6%88%91%E4%B8%80%E8%B5%B7%E5%86%99Makefile:MakeFile%E4%BB%8B%E7%BB%8D](http://wiki.ubuntu.org.cn/%E8%B7%9F%E6%88%91%E4%B8%80%E8%B5%B7%E5%86%99Makefile:MakeFile%E4%BB%8B%E7%BB%8D "跟我一起写makefile")

### 动态链接库&静态链接库
* 在Linux下，动态链接库为.so文件；在Windows下，动态链接库为.dll文件。 静态链接库为.o文件。
* 动态链接库与静态链接库的一个比较重要的区别，就是在可执行文件运行时，若采用动态链接方式，则需要对程序中的某些函数进行重定向，而静态链接不用。
* 由于采用动态链接方法时，程序的部分实现并不会被包含进可执行文件当中，因此可执行文件相比采用静态链接方法时要小，程序的灵活性与可更新性耶更强。

### 调试相关
* 调试工具
	* time 计时
	* perf 查看性能 eg. perf recode ./main ; perf report
	* gdb  		   eg. b break; bt 查看堆栈; info 查看当前状态
* 编译选项
	* O1/O2/O3 优化等级：随着

### 个人总结
本次项目主要是考察算法设计。若单纯使用深搜算法，本次项目很明显是时间损耗会非常大，因此，需要在深搜的基础上对算法进行优化。主要的优化思路就是将深搜过程中得到的结果进行保存，在每次进行递归的时候需要先遍历已保存的内容，由此提高遍历速度。
<file_sep>/project4/code/TraderSpi/build/src/CMakeFiles/CTraderSpi.dir/cmake_clean.cmake
file(REMOVE_RECURSE
  "CMakeFiles/CTraderSpi.dir/CTraderSpi.cpp.o"
  "../../lib/libCTraderSpi.pdb"
  "../../lib/libCTraderSpi.a"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/CTraderSpi.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/project2/code/proj2.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime as dt
from sklearn import preprocessing
from sklearn.neural_network import MLPRegressor
from sklearn import tree
from sklearn import svm
from sklearn.neighbors import KNeighborsRegressor
from sklearn.neighbors import RadiusNeighborsRegressor
from sklearn.metrics import mean_squared_error
from sklearn.metrics import explained_variance_score
from sklearn.metrics import mean_absolute_error

class Shares:
    def __init__(self, data):
        self.data = data
        self.col_head = data.columns.values.tolist()

    def date_access(self):
        """
            datetime with "y-m-d"
        """
        if 'date' not in self.col_head:
            print "date is no exit"
            return None
        else:
            date = []
            for no in range(len(self.data['date'])):
                date.append(dt.datetime.strptime(self.data['date'][no], "%Y-%m-%d"))
            date_list = []
            for d in date:
                temp = []
                temp.append(d.year)
                temp.append(d.month)
                temp.append(d.day)
                date_list.append(temp)
            del self.data['date']
            # 重新生成一个dataframe
            date_frame = pd.DataFrame(date_list, columns=['year', 'month', 'day'])
            # dataframe合并
            self.data = pd.concat([date_frame, self.data], axis=1)

    def time_access(self):
        """
            datetime with "y-m-d h:m:s"
        """
        if 'date' not in self.colhead:
            print "date is no exit"
            return None
        else:
            date = []
            for no in range(len(self.data['date'])):
                date.append(dt.datetime.strptime(self.data['date'][no], "%Y-%m-%d %H:%M:%S"))
            date_list = []
            for d in date:
                temp = []
                temp.append(d.year)
                temp.append(d.month)
                temp.append(d.day)
                temp.append(d.hour)
                temp.append(d.minute)
                temp.append(d.second)
                date_list.append(temp)
            del self.data['date']
            date_frame = pd.DataFrame(date_list, columns=['year', 'month', 'day', 'hour', 'minute', 'second'])
            self.data = pd.concat([date_frame, self.data], axis=1)

    def get_att(self, s_att):
        """
            return a attribute according input
        """
        temp = self.data[s_att]
        return temp

    def get_ema(self, col='close', ema_model='12', ema_molecule=11, ema_denominator=13, init_ema=0):
        """
            compute EMA(12) & EMA(26)
            EMA(12) = EMA(12) * 11/13 + close * 2/13
            EMA(26) = EMA(26) * 25/27 + close * 2/27
        """
        ema_model = 'ema_'+ema_model
        ema = []
        length = len(self.data[col]) - 1
        ema.append(init_ema * ema_molecule/ema_denominator + self.data[col][length] * (ema_denominator-ema_molecule)/ema_denominator)
        for i in range(1, len(self.data[col])):
            ema.append(ema[i-1] * ema_molecule/ema_denominator + self.data[col][length-i] * (ema_denominator-ema_molecule)/ema_denominator)
        ema.reverse()

        ema = pd.DataFrame(ema, columns=[ema_model])
        return ema

    def get_diff(self, first_ema, second_ema):
        """
            compute DIFF bitween EMA(12) & EMA(16)
            DIFF = EMA(12) - EMA(26)
        """
        first_ema_col_head = first_ema.columns.values.tolist()
        second_ema_col_head = second_ema.columns.values.tolist()
        diff_col_head = 'diff_'+first_ema_col_head[0]+"_"+second_ema_col_head[0]

        diff = []
        for i in range(len()):
            diff.append(first_ema[i] - second_ema[i])
        diff = pd.DataFrame(diff, columns=[diff_col_head])
        return diff

    def get_dea(self, diff, dea_molecule=8, dea_denominator=10):
        """
            compute MACD(DEA)
            DEA(MACD) = DEA * 8/10 + DIF * 2/10
        """
        diff_col_head = diff.columns.values.tolist()
        dea_head = 'dea_'+diff_col_head[0]

        dea = []
        init_dea = 0
        length = len(diff[col_head[0]]) - 1
        dea.append(init_dea * dea_molecule/dea_denominator + diff[col_head[0]][length] * (dea_denominator-dea_molecule)/dea_denominator)

        for i in range(1,len(diff)):
            dea.append(dea[i-1] * dea_molecule/dea_denominator + diff[col_head[0]][length - i] * (dea_denominator-dea_molecule)/dea_denominator)
        dea.reverse()

        dea = pd.DataFrame(dea, columns=[dea_head])
        return dea

    def get_macd(self, diff, dea):
        """
            compute BAR
            macd = 2 * (DIFF - DEA)
        """
        diff_col_head = diff.columns.values.tolist()
        dea_col_head = dea.columns.values.tolist()
        macd_col_head = 'macd_'+diff_col_head[0]+"_"+dea_col_head[0]

        macd = []
        for i in range(len(diff)):
            macd.append(2 * (diff[diff_col_head[0]][i] - dea[dea_col_head[0]][i]))

        macd = pd.DataFrame(macd, columns=[macd_col_head])
        return macd

    def Get_Boll(self):
        """
            compute boll

        """
        pass

    def Get_RSI(self):
        """
            RSI(N) = A / (A+B) * 100
        """
        Posi_Price_Change = 0
        Nega_Price_Change = 0
        self.GSI = []
        length = len(self.data['price_change']) - 5
        for i in range(length):
            for j in range(5):
                if self.data['price_change'][i+j] > 0:
                    Posi_Price_Change += self.data['price_change'][i+j]
                else:
                    Nega_Price_Change += self.data['price_change'][i+j]
            self.GSI.append(Posi_Price_Change * (Posi_Price_Change + Nega_Price_Change * (-1)) * 100)
        for i in range(5):
            self.GSI.append(self.GSI[length])
        return self.GSI

    def Get_ColHead(self):
        return self.colHead

    def sort(self):
        """
            sort the data by the year/month/day
        """
        self.data = self.data.sort_values(by=['year', 'month', 'day'], ascending=True)

    def Get_Data(self):
        """
            return the data set with some computed_value
        """
        self.Date_Access()
        EMA = self.Get_EMA()
        DIFF = self.Get_DIFF()
        MACD = self.Get_MACD()
        BAR = self.Get_BAR()
        self.data = pd.concat([self.data, EMA, DIFF, MACD, BAR], axis=1)
        self.sort()
        return self.data

    def Target_Plot(self, target, start, end):
        total_df = []
        if 'ma5' in target:
            total_df.append(self.data['ma5'][start:end])
        if 'ma10' in target:
            total_df.append(self.data['ma10'][start:end])
        if 'ma20' in target:
            total_df.append(self.data['ma20'][start:end])
        if 'v_ma5' in target:
            total_df.append(self.data['v_ma5'][start:end])
        if 'v_ma10' in target:
            total_df.append(self.data['v_ma10'][start:end])
        if 'v_ma20' in target:
            total_df.append(self.data['v_ma20'][start:end])
        if 'EMA_12' in target:
            total_df.append(self.EMA['EMA_12'][start:end])
        if 'EMA_26' in target:
            total_df.append(self.EMA['EMA_26'][start:end])
        if 'DIFF' in target:
            total_df.append(self.DIFF['DIFF'][start:end])
        if 'MACD' in target:
            total_df.append(self.MACD['MACD'][start:end])
        if 'BAR' in target:
            total_df.append(self.BAR['BAR'][start:end])

        total_df = pd.concat(total_df, axis=1)
        if 'BAR' in target:
            total_df.plot(kind='bar')
        else:
            total_df.plot()
        plt.show()

class DataAccess:
    def __init__(self, data):
        self.data = data
        self.colHead = data.columns.values.tolist()

    def encode(self):
        """
            onehot encoding
        """
        enc = preprocessing.OneHotEncoder()
        enc.fit(self.data['year'])

    def Get_corr(self):
        """
            compute correlation
        """
        print self.data.corr()

    def Select_Label(self, label):
        """
            select label
            divide into data and label
        """
        if label not in self.colHead:
            label = label + "is no exit"
            print(label)
        else:
            label_list = self.data[label]
            del self.data[label]
            self.label_y = np.array(label_list)
            self.label_y = self.label_y.tolist()
            self.label_y.reverse()

    def Select_Data(self, Selected_Att):
        """
            According input to select columns
        """
        final = []
        for sa in Selected_Att:
            final.append(self.data[sa])
        self.data_x = pd.concat(final, axis=1)
        self.data_x = np.array(self.data_x)
        self.data_x = self.data_x.tolist()
        self.data_x.reverse()
        self.data_x = preprocessing.scale(self.data_x)

    def Divide(self, num):
        """
            divide data_set into train_set and test_set
        """
        train_x = []
        test_x = []
        train_y = []
        test_y = []

        temp = 0
        for i in range(len(self.data_x)):
            if temp < num:
                train_x.append(self.data_x[i])
                train_y.append(self.label_y[i])
                temp += 1
            else:
                test_x.append(self.data_x[i])
                test_y.append(self.label_y[i])
                temp = 0

        return train_x,train_y,test_x,test_y

    def Get_Data(self):
        return self.data

    def Get_Data_x(self):
        return self.data_x

    def Get_Label_y(self):
        return self.label_y

class Model:
    def __init__(self):
        pass

    def NN_Build(self, train_x, train_y):
        """
            structure nerual network
        """
        self.NN = MLPRegressor(hidden_layer_sizes=(50), activation='relu', solver='adam',
                               alpha=0.0001, batch_size='auto', learning_rate='adaptive', learning_rate_init=0.001)
        self.NN.fit(train_x, train_y)

    def NN_Predict(self, test):
        """
            nerual network
            predict the result with the input data
        """
        pre_result = self.NN.predict(test)
        return pre_result

    def DT_Build(self, train_x, train_y):
        """
            decision tree model
        """
        self.DT = tree.DecisionTreeRegressor()
        self.DT.fit(train_x, train_y)

    def DT_Predict(self, test):
        """
            predict the result with the input data
        """
        pre_result = self.DT.predict(test)
        return pre_result

    def SVM_Build(self, train_x, train_y):
        """SVM_Build"""
        self.clf = svm.SVR()
        self.clf.fit(train_x, train_y)

    def SVM_Predict(self, test):
        """SVM_Predict"""
        pre_result = self.clf.predict(test)
        return pre_result

    def KNN_Build(self, train_x, train_y):
        """KNN_Build"""
        self.kneigh = KNeighborsRegressor(n_neighbors=2)
        self.kneigh.fit(train_x, train_y)

    def KNN_Predict(self, test):
        """KNN_Predict"""
        pre_result = self.kneigh.predict(test)
        return pre_result

    def RNN_Build(self, train_x, train_y):
        """RNN_Build"""
        self.rneigh = RadiusNeighborsRegressor(radius=1.0)
        self.rneigh.fit(train_x, train_y)

    def RNN_Predict(self, test):
        """RNN_Predict"""
        pre_result = self.kneigh.predict(test)
        return pre_result

    def pre_plot(self, train_y, pre_result, start, end, ti):
        """
            compare the predict_result with the true label
        """
        train_y = pd.DataFrame(train_y[start:end], columns=['train_y'])
        pre_result = pd.DataFrame(pre_result[start:end], columns=['pre_result'])
        result = pd.concat([train_y, pre_result], axis=1)
#         print result
        result.plot(title=ti)
        plt.show()

    def Get_MSE(self, test_y, pre_result):
        """
            compute MSE between label & pre_result
            MSE = sum(pow(test_y-pre_result,2)) / len(test_y)
        """
        diff = []
        for i in range(len(test_y)):
            diff.append(pow(test_y[i] - pre_result[i],2))
        result = np.sum(diff) / len(test_y)
        print 'MSE: ',result

    def Algorithm_compare(self, train_x, train_y, test_x, test_y):
        """plot the results precited by the models"""
        self.NN_Build(train_x, train_y)
        self.DT_Build(train_x, train_y)
        self.SVM_Build(train_x, train_y)
        self.KNN_Build(train_x, train_y)
        self.RNN_Build(train_x, train_y)
        self.NN_result = self.NN_Predict(test_x)
        self.DT_result = self.DT_Predict(test_x)
        self.SVM_result = self.SVM_Predict(test_x)
        self.KNN_result = self.KNN_Predict(test_x)
        self.RNN_result = self.RNN_Predict(test_x)

        self.pre_plot(test_y, self.NN_result, 0, len(self.NN_result), 'NN_result')
        self.Evaluate(test_y, self.NN_result)
        self.pre_plot(test_y, self.DT_result, 0, len(self.DT_result), 'DT_result')
        self.Evaluate(test_y, self.DT_result)
        self.pre_plot(test_y, self.SVM_result, 0, len(self.SVM_result), 'SVM_result')
        self.Evaluate(test_y, self.SVM_result)
        self.pre_plot(test_y, self.KNN_result, 0, len(self.KNN_result), 'KNN_result')
        self.Evaluate(test_y, self.KNN_result)
        self.pre_plot(test_y, self.RNN_result, 0, len(self.RNN_result), 'RNN_result')
        self.Evaluate(test_y, self.RNN_result)

    def Evaluate(self, test_y, pre_result):
        MSE = mean_squared_error(test_y, pre_result)
        MAE = mean_absolute_error(test_y, pre_result)
        EVS = explained_variance_score(test_y, pre_result)
        print 'MSE: ',MSE
        print 'MAE: ',MAE
        print 'EVS: ',EVS

if __name__ == "__main__":
    #读文件
    data = pd.read_csv("data/1day/000001.csv")

    #股票对象
    shares = Shares(data)
    data = shares.Get_Data()

    length = len(data['ma5'])
    shares.Target_Plot(['ma5','ma10','ma20'], length-20, length)
    shares.Target_Plot(['v_ma5','v_ma10','v_ma20'], length-20, length)
    shares.Target_Plot(['EMA_12','EMA_26'],length-20,length)
    shares.Target_Plot(['DIFF','MACD','BAR'],length-20,length)

    #数据处理对象
    DA = DataAccess(data)
#     DA.Get_corr()
    DA.Select_Label('price_change')
    cols = ['year', 'month', 'day', 'open', 'high', 'close', 'low', 'volume', 'p_change',
            'ma5', 'ma10', 'ma20', 'v_ma5', 'v_ma10', 'v_ma20', 'EMA_12', 'EMA_26', 'turnover','DIFF','MACD','BAR']
    DA.Select_Data(cols)
    train_x,train_y,test_x,test_y=DA.Divide(4)

    #模型对象
    model = Model()
    model.Algorithm_compare(train_x, train_y, test_x, test_y)
<file_sep>/project4/code/MdSpi/bin/Instrument.ini
[InstrumentNum]
Num=3

[Instrument]
Ins1=al1807
Ins2=al1808
Ins3=al1809<file_sep>/project4/code/TraderSpi/inc/CTraderSpi.h
#ifndef TRADERSPI_H_
#define TRADERSPI_H_

#include "ThostFtdcTraderApi.h"
#include <stdio.h>
#include <fstream>
#include <cstring>

class CTraderSpi : public CThostFtdcTraderSpi
{
public:
	virtual void OnFrontConnected();
	virtual void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin,	CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);
	virtual void OnRspSettlementInfoConfirm(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);
	virtual void OnRspQryInstrument(CThostFtdcInstrumentField *pInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);
	virtual void OnRspQryTradingAccount(CThostFtdcTradingAccountField *pTradingAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);
	virtual void OnRspQryInvestorPosition(CThostFtdcInvestorPositionField *pInvestorPosition, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);
	virtual void OnRspOrderInsert(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);
	virtual void OnRspOrderAction(CThostFtdcInputOrderActionField *pInputOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);
	virtual void OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);
	virtual void OnFrontDisconnected(int nReason);
	virtual void OnHeartBeatWarning(int nTimeLapse);
	virtual void OnRtnOrder(CThostFtdcOrderField *pOrder);
	virtual void OnRtnTrade(CThostFtdcTradeField *pTrade);
	virtual void OnRspQryOrder(CThostFtdcOrderField *pOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);

public:
	void ReqUserLogin();
	void ReqSettlementInfoConfirm();
	void ReqQryInstrument();
	void ReqQryTradingAccount();
	void ReqQryInvestorPosition();
	void ReqOrderInsert(char *OrderFilePath);
	void ReqOrderAction(CThostFtdcOrderField *pOrder);
	bool IsErrorRspInfo(CThostFtdcRspInfoField *pRspInfo);
	bool IsMyOrder(CThostFtdcOrderField *pOrder);
	bool IsTradingOrder(CThostFtdcOrderField *pOrder);
	void ReqQryOrder(char *instrumentId, char *orderSysId);
	void SetOrderType(char *OrderFilePath);
	void SetConfigInfo(char *configFilePath);
	//void Init();
	void Init(){
		if(pUserApi == nullptr)
		{
			pUserApi = CThostFtdcTraderApi::CreateFtdcTraderApi();
			pUserApi->RegisterSpi(this);
		}
		if(!isConnected)
		{
			pUserApi->SubscribePublicTopic(THOST_TERT_QUICK);
			pUserApi->SubscribePrivateTopic(THOST_TERT_QUICK);
			pUserApi->RegisterFront(FRONT_ADDR);
			pUserApi->Init();
		}
	}
	CTraderSpi();

	char* GetBrokerID(){return BROKER_ID;}
	char* GetInvstorID(){return INVESTOR_ID;}
	bool GetIsLogin(){return isLogin;}
	bool CompairInfo(CTraderSpi &spiTemp);

private:
	CThostFtdcTraderApi* pUserApi = nullptr;
	char FRONT_ADDR[256];
	TThostFtdcBrokerIDType	BROKER_ID = "";
	TThostFtdcInvestorIDType INVESTOR_ID = "";
	TThostFtdcPasswordType  PASSWORD = "";
	TThostFtdcInstrumentIDType INSTRUMENT_ID = "";
	bool isConnected = 0;
	bool isLogin = 0;
	int iRequestID = 0;

	TThostFtdcFrontIDType	FRONT_ID;
	TThostFtdcSessionIDType	SESSION_ID;	 // session id
	TThostFtdcOrderRefType	ORDER_REF;	 // order reference

	CThostFtdcInputOrderField InsertOrder;

};

#endif<file_sep>/project4/code/TraderSpi/inc/TraderSpi.h
#include "ThostFtdcTraderApi.h"
#include <stdio.h>
#include <fstream>

class CTraderSpi : public CThostFtdcTraderSpi
{
public:
	// used before connected
	virtual void OnFrontConnected();

	// response for login
	virtual void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin,	CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);

	// response for settlement information confirm
	virtual void OnRspSettlementInfoConfirm(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);

	// query instrument
	virtual void OnRspQryInstrument(CThostFtdcInstrumentField *pInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);

	// query trading account
	virtual void OnRspQryTradingAccount(CThostFtdcTradingAccountField *pTradingAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);

	// query investor position
	virtual void OnRspQryInvestorPosition(CThostFtdcInvestorPositionField *pInvestorPosition, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);

	//
	virtual void OnRspOrderInsert(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);

	//
	virtual void OnRspOrderAction(CThostFtdcInputOrderActionField *pInputOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);

	//
	virtual void OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);

	//
	virtual void OnFrontDisconnected(int nReason);

	//
	virtual void OnHeartBeatWarning(int nTimeLapse);

	//
	virtual void OnRtnOrder(CThostFtdcOrderField *pOrder);

	//
	virtual void OnRtnTrade(CThostFtdcTradeField *pTrade);

	virtual void OnRspQryOrder(CThostFtdcOrderField *pOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast);

public:

	void ReqUserLogin();

	void ReqSettlementInfoConfirm();

	void ReqQryInstrument();

	void ReqQryTradingAccount();

	void ReqQryInvestorPosition();

	void ReqOrderInsert();

	void ReqOrderAction(CThostFtdcOrderField *pOrder);

	bool IsErrorRspInfo(CThostFtdcRspInfoField *pRspInfo);

	bool IsMyOrder(CThostFtdcOrderField *pOrder);

	bool IsTradingOrder(CThostFtdcOrderField *pOrder);

	void ReqQryOrder(char *instrumentId, char *orderSysId);

	void SetOrderType();

};<file_sep>/project4/code/TraderSpi/src/CMakeLists.txt
SET(CLASS_FILE CTraderSpi Ini)
SET(MAIN_FILE TraderServer)
SET(CTP_SO thosttraderapi)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

FOREACH(f ${CLASS_FILE})
	#ADD_LIBRARY(${f} SHARED ${f}.cpp)
	ADD_LIBRARY(${f} STATIC ${f}.cpp)
	#SET_TARGET_PROPERTIES(${f} PROPERTIES VERSION 1.2 SOVERSION 1)
	#SET_TARGET_PROPERTIES(${f}_static PROPERTIES OUTPUT_NAME "${f}")
	#SET_TARGET_PROPERTIES(${f} PROPERTIES CLEAN_DIRECT_OUTPUT 1)
	#SET_TARGET_PROPERTIES(${f}_static PROPERTIES CLEAN_DIRECT_OUTPUT 1)
ENDFOREACH(f)

LINK_DIRECTORIES(${LIBRARY_OUTPUT_PATH})
ADD_EXECUTABLE(${MAIN_FILE} ${MAIN_FILE}.cpp)
TARGET_LINK_LIBRARIES(${MAIN_FILE} ${CTP_SO} ${CLASS_FILE})
<file_sep>/project2/code/dataAccess.py
# coding: utf-8
import numpy as np
import pandas as pd
from sklearn import preprocessing
import pickle as pk
import indicatorGallexy as ig

class DataAccess:
    def __init__(self, data):
        self.data = data
        self.colHead = data.columns.values.tolist()

    def oneHotEncode(self,colname_list):
        """独热编码"""
        enc = preprocessing.OneHotEncoder()
        data_temp=[]
        for cl in colname_list:
            data_temp.append(self.data[cl])
            del self.data[cl]
        data_temp = pd.concat(data_temp,axis=1)
        enc.fit(data_temp)
        data_temp = enc.transform(data_temp).toarray()
        data_temp = pd.DataFrame(data_temp)
        self.data = pd.concat([data_temp, self.data], axis=1)
        self.colHead = self.data.columns.values.tolist()

    def getCorr(self):
        print self.data.corr()

    def selectLabel(self, label):
        """选择预测对象, 把该列值单独取出"""
        if label not in self.colHead:
            label = label + "is no exit"
            print(label)
        else:
            label_list = self.data[label]
            del self.data[label]
            self.label_y = np.array(label_list)
            self.label_y = self.label_y.tolist()
            # self.label_y.reverse()

    def selectAtt(self, selected_att):
        """选择训练的属性集"""
        final = []
        for sa in selected_att:
            final.append(self.data[sa])
        self.data_x = pd.concat(final, axis=1)
        self.data_x = np.array(self.data_x)
        self.data_x = self.data_x.tolist()
        # self.data_x.reverse()
        self.data_x = preprocessing.scale(self.data_x)

    def divideData(self, num):
        """划分训练集和验证集, 以num+1为一组进行划分，并进行移位操作"""
        train_x = []
        test_x = []
        train_y = []
        test_y = []

        temp = 0
        for i in range(len(self.data_x)-1):
            if temp < num:
                train_x.append(self.data_x[i])
                train_y.append(self.label_y[i+1])
                temp += 1
            else:
                test_x.append(self.data_x[i])
                test_y.append(self.label_y[i+1])
                temp = 0

        return train_x,train_y,test_x,test_y

    def storeToPickle(self, data, file_path):
        """序列化操作"""
        pickle_file = open(file_path, 'wb')
        pk.dump(data, pickle_file)

    def getData(self):
        return self.data

    def getColHead(self):
        return self.colHead

    def getDataX(self):
        return self.data_x

    def getLabelY(self):
        return self.label_y

if __name__ == "__main__":
    data = pd.read_csv("data/1day/000001.csv")
    xmIG = ig.IndicatorGallexy(data)

    xmIG.dateAccess('date')
    data = xmIG.getData()

    xmDA = DataAccess(data)
    # xmDA.oneHotEncode(['year', 'month', 'day'])
    xmDA.selectLabel('year')
<file_sep>/project4/code/MdSpi/CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
PROJECT(Demo)

SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
SET(SOURCE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/src)
SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)

INCLUDE_DIRECTORIES(inc)

ADD_SUBDIRECTORY(src)<file_sep>/project4/code/MdSpi/bin/test.sh
#!/bin/bash
./testMdSpi -b 9999 -i 112585 -p qq824073152
login
SMD
3
al1803,al1804,al1805
SMDFF
./Instrument.ini<file_sep>/project2/code/model.py
# coding: utf-8
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn.neural_network import MLPRegressor
from sklearn import tree
from sklearn import svm
from sklearn.neighbors import KNeighborsRegressor
from sklearn.neighbors import RadiusNeighborsRegressor
from sklearn.metrics import mean_squared_error
from sklearn.metrics import explained_variance_score
from sklearn.metrics import mean_absolute_error

class Model:
    def __init__(self):
        self.my_model = None

    def modelBuild(self, train_x, train_y, selected_model='NN'):
        """训练模型"""
        if selected_model == 'NN':
            self.my_model = MLPRegressor(hidden_layer_sizes=(50), activation='relu', solver='adam', alpha=0.0001, batch_size='auto', learning_rate='adaptive', learning_rate_init=0.001)
        elif selected_model == 'DT':
            self.my_model = tree.DecisionTreeRegressor()
        elif selected_model == 'SVM':
            self.my_model = svm.SVR()
        elif selected_model == 'KNN':
            self.my_model == KNeighborsRegressor(n_neighbors=2)
        elif selected_model == 'RNN':
            self.my_model == RadiusNeighborsRegressor(radius=1.0)
        else:
            print "this model can not be built"
            return

        self.my_model.fit(train_x, train_y)

    def modelPredict(self, test_x):
        """模型预测，返回预测结果"""
        pre_result = self.my_model.predict(test_x)
        return pre_result

    def plotResult(self, test_y, pre_result, ti):
        """结果展示"""
        test_y = pd.DataFrame(test_y, columns=['train_y'])
        pre_result = pd.DataFrame(pre_result, columns=['pre_result'])

        result = pd.concat([test_y, pre_result], axis=1)
#         print result
        result.plot(title=ti)
        plt.show()

    def algorithmCompare(self, train_x, train_y, test_x, test_y, model_list=[]):
        """模型比较"""
        evaluate = []
        evaluate_colname = ['MSE','MAE','EVS']
        for ml in model_list:
            self.modelBuild(train_x, train_y, ml)
            pre_result = self.modelPredict(test_x)
            print ml+": "
            self.plotResult(test_y, pre_result, ml)
            mse_temp, mae_temp, evs_temp = self.algorithmEvaluate(test_y, pre_result)
            evaluate.append([mse_temp,mae_temp,evs_temp])
        evaluate = pd.DataFrame(evaluate, columns=evaluate_colname)
        evaluate.plot(kind='bar')
        plt.show()

    def algorithmEvaluate(self, test_y, pre_result):
        """计算评价指标"""
        mse = mean_squared_error(test_y, pre_result)
        mae = mean_absolute_error(test_y, pre_result)
        evs = explained_variance_score(test_y, pre_result)
        print 'MSE: ',mse
        print 'MAE: ',mae
        print 'EVS: ',evs
        return mse, mae, evs

if __name__ == "__main__":
    pass<file_sep>/project4/code/TraderSpi/build/src/CMakeFiles/TraderServer.dir/cmake_clean.cmake
file(REMOVE_RECURSE
  "CMakeFiles/TraderServer.dir/TraderServer.cpp.o"
  "../../bin/TraderServer.pdb"
  "../../bin/TraderServer"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/TraderServer.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/project4/code/TraderSpi/src/CTraderSpi.cpp
#include "CTraderSpi.h"
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <stdlib.h>
#include <Ini.h>

using namespace std;

CTraderSpi::CTraderSpi()
{
	pUserApi = nullptr;
	strcpy(FRONT_ADDR, "");
	strcpy(BROKER_ID, "");
	strcpy(INVESTOR_ID, "");
	strcpy(PASSWORD, "");
	strcpy(INSTRUMENT_ID, "");
	isConnected = 0;
	isLogin = 0;
	iRequestID = 0;
}

void CTraderSpi::SetConfigInfo(char *configFilePath)
{
	CIni ini;
	ini.OpenFile(configFilePath,"r");
	char *broId = ini.GetStr("Broker","ID");
	strcpy(BROKER_ID, broId);
	char *invId = ini.GetStr("Investor","ID");
	strcpy(INVESTOR_ID, invId);
	char *pwd = ini.GetStr("Investor","Password");
	strcpy(PASSWORD, pwd);
	char *insId = ini.GetStr("Instrument", "Ins");
	strcpy(INSTRUMENT_ID, insId);
	char *frontAddr = ini.GetStr("FrontAddr", "Addr");
	strcpy(FRONT_ADDR, frontAddr);
}

/*void CTraderSpi::Init()
{
	if(pUserApi == nullptr)
	{
		pUserApi = CThostFtdcTraderApi::CreateFtdcTraderApi();
		pUserApi->RegisterSpi(this);
	}
	if(!isConnected)
	{
		pUserApi->SubscribePublicTopic(THOST_TERT_QUICK);
		pUserApi->SubscribePrivateTopic(THOST_TERT_QUICK);
		pUserApi->RegisterFront(FRONT_ADDR);
		pUserApi->Init();
	}
}*/

bool IsFlowControl(int iResult)
{
	return ((iResult == -2) || (iResult == -3));
}

void CTraderSpi::OnFrontConnected()
{
	cout << "--->>> connect succeed" << endl;
	isConnected = 1;
}

void CTraderSpi::ReqUserLogin()
{
	while(!isConnected) { }
	CThostFtdcReqUserLoginField req;
	memset(&req, 0, sizeof(req));
	strcpy(req.BrokerID, BROKER_ID);
	strcpy(req.UserID, INVESTOR_ID);
	strcpy(req.Password, <PASSWORD>);
	int iResult = pUserApi->ReqUserLogin(&req, ++iRequestID);
}

void CTraderSpi::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	if(bIsLast && !IsErrorRspInfo(pRspInfo))
	{
		FRONT_ID = pRspUserLogin->FrontID;
		SESSION_ID = pRspUserLogin->SessionID;
		int iNextOrderRef = atoi(pRspUserLogin->MaxOrderRef);
		iNextOrderRef++;
		sprintf(ORDER_REF, "%d", iNextOrderRef);
		isLogin = 1;
		cout << "--->>> Login succeed" << endl;
		cout << "Date: " << pRspUserLogin->TradingDay << endl;
		cout << "LoginTime: " << pRspUserLogin->LoginTime << endl;
		cout << "BrokerID: " << pRspUserLogin->BrokerID << endl;
		cout << "userID: " << pRspUserLogin->UserID << endl;
		cout << "SystemName: " << pRspUserLogin->SystemName << endl;
		cout << "FrontID: " << pRspUserLogin->FrontID << endl;
		cout << "SessionID: " << pRspUserLogin->SessionID << endl;
		cout << "MaxOrderRef: " << pRspUserLogin->MaxOrderRef << endl << endl;

		ReqSettlementInfoConfirm();

		char filePath[100] = {'\0'};
		sprintf(filePath, "%s_order.csv", pRspUserLogin->UserID);
		ofstream outFile;
		outFile.open(filePath, ios::out);
		outFile << "OrderSysID" << ","
				<< "InstrumentID" << ","
				<< "LimitPrice" << ","
				<< "Volume" << ","
				<< "OrderStatus" << "," << endl;
	}
	else
	{
		cout << "--->>> Login default" << endl;
	}
}

void CTraderSpi::ReqSettlementInfoConfirm()
{
	CThostFtdcSettlementInfoConfirmField req;
	memset(&req, 0, sizeof(req));
	strcpy(req.BrokerID, BROKER_ID);
	strcpy(req.InvestorID, INVESTOR_ID);
	int iResult = pUserApi->ReqSettlementInfoConfirm(&req, ++iRequestID);
}

void CTraderSpi::OnRspSettlementInfoConfirm(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	if (bIsLast && !IsErrorRspInfo(pRspInfo))
	{
		cout << "--->>> Settlement Information Confirm succeed" << endl;
		cout << "Confirm date: " << pSettlementInfoConfirm->ConfirmDate << endl;
		cout << "Confirm time: " << pSettlementInfoConfirm->ConfirmTime << endl << endl;
	}
	else
	{
		cout << "--->>> Settlement Information Confirm default" << endl;
	}
}

void CTraderSpi::ReqQryInstrument()
{
	CThostFtdcQryInstrumentField req;
	memset(&req, 0, sizeof(req));
	strcpy(req.InstrumentID, INSTRUMENT_ID);
	while (true)
	{
		int iResult = pUserApi->ReqQryInstrument(&req, ++iRequestID);
		if (!IsFlowControl(iResult)){
			break;
		}
		else{
			cout << "--->>> Query instrument iResult: " << iResult << endl;
			usleep(10000);
		}
	} // while
}

void CTraderSpi::OnRspQryInstrument(CThostFtdcInstrumentField *pInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	if (bIsLast && !IsErrorRspInfo(pRspInfo))
	{
		cout << "--->>> Query instrument succeed" << endl;
		cout << "InstrumentID: " << pInstrument->InstrumentID << endl;
		cout << "DeliveryYear: " << pInstrument->DeliveryYear << endl;
		cout << "DeliveryMonth: " << pInstrument->DeliveryMonth << endl;
		cout << "MaxMarketOrderVolume: " << pInstrument->MaxMarketOrderVolume << endl;
		cout << "MinMarketOrderVolume: " << pInstrument->MinMarketOrderVolume << endl;
		cout << "MaxLimitOrderVolume: " << pInstrument->MaxLimitOrderVolume << endl;
		cout << "MinLimitOrderVolume: " << pInstrument->MinLimitOrderVolume << endl;
		cout << "PriceTick: " << pInstrument->PriceTick << endl;
		cout << "IsTrading: " << pInstrument->IsTrading << endl;
		cout << "ExpireDate: " << pInstrument->ExpireDate << endl;
		cout << "InstLifePhase: " << pInstrument->InstLifePhase << endl;
		cout << "CombinationType: " << pInstrument->CombinationType << endl;
		cout << "MinBuyVolume: " << pInstrument->MinBuyVolume << endl;
		cout << "MinSellVolume: " << pInstrument->MinSellVolume << endl << endl;
	}
	else
	{
		cout << "--->>> Query instrument default" << endl;
	}
}

void CTraderSpi::ReqQryTradingAccount()
{
	CThostFtdcQryTradingAccountField req;
	memset(&req, 0, sizeof(req));
	strcpy(req.BrokerID, BROKER_ID);
	strcpy(req.InvestorID, INVESTOR_ID);
	while (true){
		int iResult = pUserApi->ReqQryTradingAccount(&req, ++iRequestID);
		if (!IsFlowControl(iResult))
		{
			break;
		}
		else
		{
			cout << "--->>> Query account iResult: " << iResult << endl;
			usleep(10000);
		}
	} // while
}

void CTraderSpi::OnRspQryTradingAccount(CThostFtdcTradingAccountField *pTradingAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	if (bIsLast && !IsErrorRspInfo(pRspInfo))
	{
		cout << "--->>> Query account succeed" << endl;
		cout << "AccountID: " << pTradingAccount->AccountID << endl;
		cout << "CurrMargin: " << pTradingAccount->CurrMargin << endl;
		cout << "CashIn: " << pTradingAccount->CashIn << endl;
		cout << "Commission: " << pTradingAccount->Commission << endl;
		cout << "CloseProfit: " << pTradingAccount->CloseProfit << endl;
		cout << "PositionProfit: " << pTradingAccount->PositionProfit << endl;
		cout << "Available: " << pTradingAccount->Available << endl;
		cout << "WithdrawQuota: " << pTradingAccount->WithdrawQuota << endl << endl;
	}
	else
	{
		cout << "--->>> Query account default" << endl;
	}
}

void CTraderSpi::ReqQryInvestorPosition()
{
	CThostFtdcQryInvestorPositionField req;
	memset(&req, 0, sizeof(req));
	strcpy(req.BrokerID, BROKER_ID);
	strcpy(req.InvestorID, INVESTOR_ID);
	strcpy(req.InstrumentID, INSTRUMENT_ID);
	while (true){
		int iResult = pUserApi->ReqQryInvestorPosition(&req, ++iRequestID);
		if (!IsFlowControl(iResult))
		{
			break;
		}
		else
		{
			cout << "--->>> Query investor position iResult " << iResult << endl;
			usleep(10000);
		}
	} // while
}

void CTraderSpi::OnRspQryInvestorPosition(CThostFtdcInvestorPositionField *pInvestorPosition, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	if (bIsLast && !IsErrorRspInfo(pRspInfo))
	{

		cout << "--->>> Query investor position succeed" << endl;

		if(pInvestorPosition)
		{
			cout << "InstrumentID: " << pInvestorPosition->InstrumentID << endl;
			cout << "InvestorID: " << pInvestorPosition->InvestorID << endl;
			cout << "YdPosition: " << pInvestorPosition->YdPosition << endl;
			cout << "Position: " << pInvestorPosition->Position << endl;
			cout << "OpenVolume: " << pInvestorPosition->OpenVolume << endl;
			cout << "OpenAmount: " << pInvestorPosition->OpenAmount << endl;
			cout << "CloseVolume: " << pInvestorPosition->CloseVolume << endl;
			cout << "CloseAmount: " << pInvestorPosition->CloseAmount << endl;
			cout << "PositionCost: " << pInvestorPosition->PositionCost << endl;
			cout << "UseMargin: " << pInvestorPosition->UseMargin << endl;
			cout << "PreSettlementPrice: " << pInvestorPosition->PreSettlementPrice << endl;
			cout << "SettlementPrice: " << pInvestorPosition->SettlementPrice << endl << endl;		}
		else
		{
			cout << "No position" << endl;
		}
	}
	else
	{
		cout << "--->>> Query investor position default" << endl;
	}
}

void CTraderSpi::ReqOrderInsert(char *OrderFilePath)
{
	int iNextOrderRef = atoi(ORDER_REF);
	iNextOrderRef++;
	sprintf(ORDER_REF, "%d", iNextOrderRef);

	SetOrderType(OrderFilePath);

	int iResult = pUserApi->ReqOrderInsert(&InsertOrder, ++iRequestID);
}

void CTraderSpi::OnRspOrderInsert(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	if(!IsErrorRspInfo(pRspInfo))
	{
		cout << "--->>> Order insert succeed" << endl;
		cout << "InstrumentID: " << pInputOrder->InstrumentID << endl;
		cout << "LimitPrice: " << pInputOrder->LimitPrice << endl;
		cout << "VolumeTotalOriginal: " << pInputOrder->VolumeTotalOriginal << endl;
		cout << "Direction: " << pInputOrder->Direction << endl;
	}
	else
	{
		cout << "--->>> Order insert default" << endl;
	}
}

void CTraderSpi::ReqOrderAction(CThostFtdcOrderField *pOrder)
{

	CThostFtdcInputOrderActionField req;
	memset(&req, 0, sizeof(req));

	strcpy(req.BrokerID, pOrder->BrokerID);

	strcpy(req.InvestorID, pOrder->InvestorID);

//	TThostFtdcOrderActionRefType	OrderActionRef;

	strcpy(req.OrderRef, pOrder->OrderRef);

//	TThostFtdcRequestIDType	RequestID;

	req.FrontID = pOrder->FrontID;
	// req.FrontID = FRONT_ID;

	req.SessionID = pOrder->SessionID;
	// req.SessionID = SESSION_ID;

//	TThostFtdcExchangeIDType	ExchangeID;

//	TThostFtdcOrderSysIDType	OrderSysID;

	req.ActionFlag = THOST_FTDC_AF_Delete;

//	TThostFtdcPriceType	LimitPrice;

//	TThostFtdcVolumeType	VolumeChange;

//	TThostFtdcUserIDType	UserID;

	strcpy(req.InstrumentID, pOrder->InstrumentID);

	int iResult = pUserApi->ReqOrderAction(&req, ++iRequestID);
	//cout << iResult << endl;

}

void CTraderSpi::OnRspOrderAction(CThostFtdcInputOrderActionField *pInputOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	if(!IsErrorRspInfo(pRspInfo))
	{
		cout << "--->>> Order action succeed" << endl;
		cout << "InstrumentID: " << pInputOrderAction->InstrumentID << endl;
		cout << "ActionFlag: " << pInputOrderAction->ActionFlag <<endl;
	}
	else
	{
		cout << "--->>> Order action default" << endl;
	}
}

void CTraderSpi::OnRtnOrder(CThostFtdcOrderField *pOrder)
{
	cout << "--->>> Receive order response"  << endl;
	if (IsMyOrder(pOrder))
	{
		cout << "InstruentID: " << pOrder->InstrumentID << endl;
		cout << "OrderSysID: " << pOrder->OrderSysID << endl;
		cout << "OrderStatus: " << pOrder->OrderStatus << endl << endl;
		if(pOrder->OrderStatus == THOST_FTDC_OST_Canceled){
			cout << "--->>> Revoke order succeed" << endl << endl;
		}
		if(pOrder->OrderSysID){
			char filePath[100] = {'\0'};
			sprintf(filePath, "%s_order.csv", pOrder->InvestorID);
			ofstream outFile;
			outFile.open(filePath, ios::app);
			outFile << pOrder->OrderSysID << ","
					<< pOrder->InstrumentID << ","
					<< pOrder->LimitPrice << ","
					<< pOrder->VolumeTotalOriginal << ","
					<< pOrder->OrderStatus << endl;
		}
	}
	else {
		cout << endl;
	}
}

void CTraderSpi::OnRtnTrade(CThostFtdcTradeField *pTrade)
{
	cout << "--->>> Trade succeed" << endl;
	cout << "Time: " << pTrade->TradeTime << endl;
	cout << "InstrumentID: " << pTrade->InstrumentID << endl;
	cout << "Price: " << pTrade->Price << endl;
	cout << "Volume: " << pTrade->Volume << endl;
	cout << "OffsetFlag: " << pTrade->OffsetFlag << endl;
	cout << "HedgeFlag: " << pTrade->HedgeFlag << endl;
	cout << "Direction: " << pTrade->Direction << endl;
	cout << "TradeType: " << pTrade->TradeType << endl;
	cout << "SettlementID: " << pTrade->SettlementID << endl << endl;
}

void CTraderSpi:: OnFrontDisconnected(int nReason)
{
	cout << "--->>> " << "OnFrontDisconnected" << endl;
	cout << "--->>> Reason = " << nReason << endl;
}

void CTraderSpi::OnHeartBeatWarning(int nTimeLapse)
{
	cout << "--->>> " << "OnHeartBeatWarning" << endl;
	cout << "--->>> nTimerLapse = " << nTimeLapse << endl;
}

void CTraderSpi::OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	cout << "--->>> " << "OnRspError" << endl;
	IsErrorRspInfo(pRspInfo);
}

bool CTraderSpi::IsErrorRspInfo(CThostFtdcRspInfoField *pRspInfo)
{
	bool bResult = ((pRspInfo) && (pRspInfo->ErrorID != 0));
	if (bResult)
		cout << "--->>> ErrorID=" << pRspInfo->ErrorID << ", ErrorMsg=" << pRspInfo->ErrorMsg << endl;
	return bResult;
}

bool CTraderSpi::IsMyOrder(CThostFtdcOrderField *pOrder)
{
	return ((pOrder->FrontID == FRONT_ID) &&
			(pOrder->SessionID == SESSION_ID));
}

bool CTraderSpi::IsTradingOrder(CThostFtdcOrderField *pOrder)
{
	return ((pOrder->OrderStatus != THOST_FTDC_OST_PartTradedNotQueueing) &&
			(pOrder->OrderStatus != THOST_FTDC_OST_Canceled) &&
			(pOrder->OrderStatus != THOST_FTDC_OST_AllTraded));
}

void CTraderSpi::ReqQryOrder(char *instrumentId, char *orderSysId)
{
	CThostFtdcQryOrderField req;
	memset(&req, 0, sizeof(req));
	strcpy(req.BrokerID, BROKER_ID);
	strcpy(req.InvestorID, INVESTOR_ID);
	strcpy(req.InstrumentID, instrumentId);
	strcpy(req.OrderSysID, orderSysId);

	while (true)
	{
		int iResult = pUserApi->ReqQryOrder(&req, ++iRequestID);
		if (!IsFlowControl(iResult)){
			break;
		}
		else{
			cout << "--->>> Query instrument iResult: " << iResult << endl;
			usleep(10000);
		}
	} // while
}

void CTraderSpi::OnRspQryOrder(CThostFtdcOrderField *pOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
	if (bIsLast && !IsErrorRspInfo(pRspInfo))
	{
		cout << "--->>> Query order succeed" << endl;
		cout << "InstrumentID: " << pOrder->InstrumentID << endl;
		cout << "LimitPrice: " << pOrder->LimitPrice << endl;
		cout << "OrderStatus: " << pOrder->OrderStatus << endl << endl;

		ReqOrderAction(pOrder);
	}
	else
	{
		cout << "--->>> Query order default" << endl;
	}
}

void CTraderSpi::SetOrderType(char *OrderFilePath)
{
	CIni ini;
	ini.OpenFile(OrderFilePath,"r");

	memset(&InsertOrder, 0, sizeof(InsertOrder));

	int OrderType = ini.GetInt("OrderType", "ot");

	strcpy(InsertOrder.BrokerID, BROKER_ID);

	strcpy(InsertOrder.InvestorID, INVESTOR_ID);

	strcpy(InsertOrder.OrderRef, ORDER_REF);

//	TThostFtdcUserIDType	UserID;

	switch(OrderType){
		case 1:
			InsertOrder.OrderPriceType = THOST_FTDC_OPT_LimitPrice;
			InsertOrder.TimeCondition = THOST_FTDC_TC_GFD;
			InsertOrder.VolumeCondition = THOST_FTDC_VC_AV;
			InsertOrder.ContingentCondition = THOST_FTDC_CC_Immediately;
			break;
		case 2:
			InsertOrder.OrderPriceType = THOST_FTDC_OPT_AnyPrice;
			InsertOrder.TimeCondition = THOST_FTDC_TC_IOC;
			InsertOrder.VolumeCondition = THOST_FTDC_VC_AV;
			InsertOrder.ContingentCondition = THOST_FTDC_CC_Immediately;
			break;
		case 3:
			InsertOrder.OrderPriceType = THOST_FTDC_OPT_LimitPrice;
			InsertOrder.TimeCondition = THOST_FTDC_TC_IOC;
			InsertOrder.VolumeCondition = THOST_FTDC_VC_CV;
			InsertOrder.ContingentCondition = THOST_FTDC_CC_Immediately;
			break;
		case 4:
			InsertOrder.OrderPriceType = THOST_FTDC_OPT_LimitPrice;
			InsertOrder.TimeCondition = THOST_FTDC_TC_IOC;
			InsertOrder.VolumeCondition = THOST_FTDC_VC_CV;
			InsertOrder.ContingentCondition = THOST_FTDC_CC_Immediately;
			break;
		default:
			cout << "this type can not be identified" << endl;
			break;
	}

	strcpy(InsertOrder.InstrumentID, ini.GetStr("Instrument" ,"ins"));
	InsertOrder.Direction = ini.GetStr("Direction", "dir")[0];
	InsertOrder.CombOffsetFlag[0] = ini.GetStr("CombOffsetFlag", "cof")[0];
	InsertOrder.CombHedgeFlag[0] = ini.GetStr("CombHedgeFlag", "chf")[0];
	InsertOrder.LimitPrice = (double)ini.GetInt("LimitPrice", "pri");
	InsertOrder.VolumeTotalOriginal = ini.GetInt("VolumeTotalOriginal", "vto");
	InsertOrder.MinVolume = ini.GetInt("MinVolume", "mv");
	InsertOrder.ForceCloseReason = ini.GetStr("ForceCloseReason", "fcr")[0];
	InsertOrder.IsAutoSuspend = ini.GetInt("IsAutoSuspend", "ias");
	InsertOrder.UserForceClose = ini.GetInt("UserForceClose", "ufc");

//	req.TimeCondition = THOST_FTDC_TC_GFD;

//	TThostFtdcDateType	GTDDate;

//	TThostFtdcPriceType	StopPrice;
}

bool CTraderSpi::CompairInfo(CTraderSpi &spiTemp)
{
	if(strcmp(spiTemp.GetBrokerID(), BROKER_ID) == 0 && strcmp(spiTemp.GetInvstorID(), INVESTOR_ID) == 0){
		return 1;
	}
	else {
		return 0;
	}
}

languages: Shell INI CMake Markdown Python C++

repo_language: Shell