头文件(自有文件)
//Common.h
#pragma once
//
#include <string>
#include <iomanip>
#include <vector>
#include ".\ThostTraderApi\ThostFtdcTraderApi.h"
#include ".\ThostTraderApi\ThostFtdcMdApi.h"
#include "TraderSpi.h"
#include "MdSpi.h"
#pragma warning(disable : 4996)
// USER_API参数
extern CThostFtdcTraderApi* pUserApi;
// 配置参数
extern TThostFtdcBrokerIDType BROKER_ID; //经纪商
extern TThostFtdcInvestorIDType INVESTOR_ID; //
extern TThostFtdcPasswordType PASSWORD; //
extern TThostFtdcInstrumentIDType INSTRUMENT_ID; // 交易合约代码
extern TThostFtdcDirectionType DIRECTION ; // 交易买卖方向
extern TThostFtdcOffsetFlagType MARKETState ; // 开平仓
extern TThostFtdcPriceType LIMIT_PRICE ; // 交易价格
// 会话参数
//extern bool RunMode;
extern TThostFtdcFrontIDType FRONT_ID; //前置编号
extern TThostFtdcSessionIDType SESSION_ID; //会话编号
extern TThostFtdcOrderRefType ORDER_REF; //报单引用
extern TThostFtdcOrderActionRefType ORDERACTION_REF[20]; //撤单引用
// 请求编号
extern int iRequestID;
extern TThostFtdcDateExprType TradingDay;
// User行情数据
extern char *InstrumentID_name; //
extern string Q_BarTime_s; //时间字符串
extern int Q_BarTime_1; //时间采用秒计
extern double Q_BarTime_2; //时间格式0.145100
extern double Q_UpperLimit; //
extern double Q_LowerLimit; //
extern double NewPrice; //
extern int FirstVolume; //前一次成交量数据
extern double Mn_open[3]; //
extern double Mn_high[3]; //
extern double Mn_low[3]; //
extern double Mn_close[3]; //
extern double BuyPrice; //开仓价
extern double SellPrice; //开仓价
extern int BNum; //开仓次数
extern int SNum; //开仓次数
extern bool BuySignal; //
extern bool SellSignal; //
extern double BSVolume; //开仓量
extern int TickABS;
extern double TickAPrice[4]; //
extern int TickBNum;
extern double TickBPrice[4]; //
extern char LogFilePaths[80]; //
void SendOrder(TThostFtdcInstrumentIDType FuturesId,int BuySell,int OpenClose)
{
//INSTRUMENT_ID = FuturesId;
DIRECTION = BuySell;
MARKETState = OpenClose;
if (BuySell==0 && OpenClose==0)
{
BuySignal = true;
SellSignal= false;
}
if (BuySell==1 && OpenClose==0)
{
BuySignal = false;
SellSignal = true;
}
if (BuySell==0 && OpenClose==3)
{
BuySignal = false;
SellSignal = false;
}
if (BuySell==1 && OpenClose==3)
{
BuySignal = false;
SellSignal = false;
}
//Sleep(050);
CThostFtdcInputOrderField req;
memset(&req, 0, sizeof(req));
strcpy_s(req.ExchangeID, "SHFE");
///经纪公司代码
strcpy_s(req.BrokerID, BROKER_ID);
///投资者代码
strcpy_s(req.InvestorID, INVESTOR_ID);
///合约代码 //INSTRUMENT_ID
strcpy_s(req.InstrumentID, INSTRUMENT_ID);
///报单引用
//strcpy_s(req.OrderRef, ORDER_REF);
///用户代码
// TThostFtdcUserIDType UserID;
///报单价格条件: 限价
req.OrderPriceType = THOST_FTDC_OPT_LimitPrice;
///买卖方向: //THOST_FTDC_D_Buy,THOST_FTDC_D_Sell
if (BuySell==0)
{
req.Direction = THOST_FTDC_D_Buy;
}
else if (BuySell==1)
{
req.Direction = THOST_FTDC_D_Sell;
}
///组合开平标志: 开仓 //THOST_FTDC_OF_Open,THOST_FTDC_OF_Close,THOST_FTDC_OF_CloseToday
if (OpenClose==0)
{
req.CombOffsetFlag[0] = THOST_FTDC_OF_Open; //开仓
}
else if(OpenClose==1)
{
req.CombOffsetFlag[0] = THOST_FTDC_OF_Close; //平仓
}
else if(OpenClose==3)
{
req.CombOffsetFlag[0] = THOST_FTDC_OF_CloseToday; //平今
}
///组合投机套保标志
req.CombHedgeFlag[0] = THOST_FTDC_HF_Speculation; //投机
///价格
if (BuySell==0)
{
//LIMIT_PRICE = Q_UpperLimit; //涨停价
LIMIT_PRICE = NewPrice; //最新价
}
else if (BuySell==1)
{
//LIMIT_PRICE = Q_LowerLimit; //跌停价
LIMIT_PRICE = NewPrice; //最新价
}
req.LimitPrice = LIMIT_PRICE;
///数量: 1 // 开平仓数量
req.VolumeTotalOriginal = 1;
///有效期类型: 当日有效
req.TimeCondition = THOST_FTDC_TC_GFD;
///GTD日期
// TThostFtdcDateType GTDDate;
///成交量类型: 任何数量
req.VolumeCondition = THOST_FTDC_VC_AV;
///最小成交量: 1
req.MinVolume = 1;
///触发条件: 立即
req.ContingentCondition = THOST_FTDC_CC_Immediately;
///止损价
// TThostFtdcPriceType StopPrice;
///强平原因: 非强平
req.ForceCloseReason = THOST_FTDC_FCC_NotForceClose;
///自动挂起标志: 否
req.IsAutoSuspend = 0;
///业务单元
// TThostFtdcBusinessUnitType BusinessUnit;
///请求编号
// TThostFtdcRequestIDType RequestID;
///用户强评标志: 否
req.UserForceClose = 0;
///报单引用,必须大于上次
int iNextOrderRef = atoi(ORDER_REF);
iNextOrderRef++;
sprintf(ORDER_REF,"%d",iNextOrderRef);
strcpy_s(req.OrderRef, ORDER_REF);
//测试,不真正下单
//if(RunMode) // 仿真=0;实盘=1;
//{
int iResult = pUserApi->ReqOrderInsert(&req, ++iRequestID); //实盘,会正式下单
cerr << "--->>> 报单录入请求: " << ((iResult == 0) ? "成功" : "失败") << endl;
//}
}
void _record0(double system_times, char *txt, double SPrice, double BPrice)
{
ofstream o_file(LogFilePaths,ios::app);
o_file << TradingDay << "_" << system_times << "_" << INSTRUMENT_ID << "_" << BSVolume << txt << "_" << SPrice << "_" << BPrice << endl; //将内容写入到文本文件中
o_file.close(); //关闭文件
}
bool ReadConfiguration(char *filepaths)
{
ifstream config(filepaths);
if (!config)
{
cerr << "--->>> " << "Configuration File is missing!" << endl;
return false;
}
else
{
cerr << "--->>> " << "Read Configuration File!" << endl;
}
vector < double > data(8);
for (int i = 0; i < 8; i++)
{
config >> data[i];
//cout << "Configuration:" << data[i] << endl;
}
Sleep(100);
// //
//Q_BarTime_2 = data[1]; //Q_BarTime_2
BSVolume = data[2]; //BSVolume
// //
Mn_open[0] = data[4]; //Mn_open
Mn_high[0] = data[5]; //Mn_high
Mn_low[0] = data[6]; //Mn_low
Mn_close[0] = data[7]; //Mn_close
NewPrice = data[7];
config.close();
return true;
}
void WriteConfiguration(char *filepaths)
{
ofstream o_file(filepaths,ios::trunc);
o_file << "20140428" << "\t" <<Q_BarTime_2<< "\t" << BSVolume <<"\t"<<"1409" <<"\t"<< Mn_open << "\t" << Mn_high << "\t" << Mn_low << "\t" << Mn_close << endl; //将内容写入到文本文件中
o_file.close(); //关闭文件
}
void Erasefiles()
{
system("del .\\thostmduserapi.dllDialogRsp.con");
system("del .\\thostmduserapi.dllQueryRsp.con");
system("del .\\thostmduserapi.dllTradingDay.con");
system("del .\\thosttraderapi.dllDialogRsp.con");
system("del .\\thosttraderapi.dllPrivate.con");
system("del .\\thosttraderapi.dllPublic.con");
system("del .\\thosttraderapi.dllQueryRsp.con");
system("del .\\thosttraderapi.dllTradingDay.con");
}
//DataSniffer.h
#pragma once
#include <string>
#include <iomanip>
#include <vector>
#include <math.h>
#include <windows.h>
#include ".\ThostTraderApi\ThostFtdcTraderApi.h"
#include ".\ThostTraderApi\ThostFtdcMdApi.h"
#include "TraderSpi.h"
#include "MdSpi.h"
#pragma warning(disable : 4996)
#define EPSILON_E4 (float)(1E-2)
#define EPSILON_E5 (float)(1E-3)
extern int TickABS;
extern double TickAPrice[4]; //
extern int TickBNum;
extern double TickBPrice[4]; //
extern bool CloseAll; //收盘标志
void Sniffer() //监听Tick数据已经指标计算 实盘用
{
if (Q_BarTime_2>=0.1500 && CloseAll==false)
{
cerr << "--->>> " <<TradingDay<<"准备收盘!" << endl;
cerr << "--->>> " <<"WriteConfiguration!" << endl;
WriteConfiguration("./AutoTrader.cfg"); //备份数据
Sleep(3000);
//ErasingTradeConfiguration();
cerr << "--->>> " <<TradingDay<<"收盘!" << endl;
CloseAll=true;
}
if (TickAPrice[0]>TickAPrice[1] && TickAPrice[1]>TickAPrice[2])
{
TickABS=1; //连续2个TICK涨,buy
}
else if (TickAPrice[0]<TickAPrice[1] && TickAPrice[1]<TickAPrice[2])
{
TickABS=2; //连续2个TICK跌,Sell
}
else
{
TickABS=0;
}
}
//InFile.h
#ifndef __INIFILE__H__
#define __INIFILE__H__
#include <windows.h>
#include <tchar.h>
//#include "STD.h"
char * ltrim(char *str) {
char *s = str;
while (*s == ' ') s++;
//strcpy(str, s); //自己修改 sizeof
strcpy_s(str,sizeof(str), s); //自己修改 sizeof
return str;
}
char *rtrim(char *str) {
char *s = str + strlen(str) - 1;
while (s - str >= 0 && (*s == ' ' || *s == '\n')) s--;
s++;
*s = 0;
return str;
}
char * alltrim(char *str)
{
ltrim(str);
rtrim(str);
return str;
}
class CIniFile
{
protected:
TCHAR m_szFileName[500];
WCHAR m_wszFileName[500];
public:
CIniFile(LPCTSTR FileName) { lstrcpyn(m_szFileName, FileName, sizeof(m_szFileName) ); m_wszFileName[0] = 0; }
virtual ~CIniFile() {};
public:
/*
LPTSTR ReadString(LPCTSTR Section, LPCTSTR Name, LPCTSTR Default, LPTSTR out, DWORD size)
{
GetPrivateProfileString(Section, Name, Default, out, size, m_szFileName);
//STD::
alltrim(out);
return out;
}
WCHAR* ReadWString(WCHAR* Section, WCHAR* Name, WCHAR* Default, WCHAR* out, DWORD size)
{
if (m_wszFileName[0] == 0)
{
STD::ConvertToUnicode(m_wszFileName, dim(m_wszFileName), m_szFileName);
}
GetPrivateProfileStringW(Section, Name, Default, out, size, m_wszFileName);
return out;
} */
int ReadInt(LPCTSTR Section, LPCTSTR Name, int Default)
{
return GetPrivateProfileInt(Section, Name, Default, m_szFileName);
}
int ReadInteger(LPCTSTR Section, LPCTSTR Name, int Default)
{
return ReadInt(Section, Name, Default);
}
/*
bool ReadBool(LPCTSTR Section, LPCTSTR Name, bool Default)
{
char str[50];
ReadString(Section, Name, "", str, dim(str));
if (str[0] == 0)
{
return Default;
}
///else if (stricmp_s(str, "yes") == 0)
else if (stricmp(str, "yes") == 0)
{
return true;
}
else
{
return false;
}
}
*/
public:
BOOL WriteString(LPCTSTR Section, LPCTSTR Name, LPCTSTR Value)
{
return WritePrivateProfileString(Section, Name, Value, m_szFileName);
}
BOOL WriteInt(LPCTSTR Section, LPCTSTR Name, int Value)
{
TCHAR tempbuf[256];
_sntprintf_s(tempbuf,256,256,_T("%d"),Value);
return WritePrivateProfileString(Section, Name, tempbuf, m_szFileName);
}
};
//--------------------------------------------------------------------------------------------------------------------------------
#endif
//--------------------------------------------------------------------------------------------------------------------------------
//MdSpi.h
#pragma once
#include ".\ThostTraderApi\ThostFtdcMdApi.h"
class CMdSpi : public CThostFtdcMdSpi
{
public:
///错误应答
virtual void OnRspError(CThostFtdcRspInfoField *pRspInfo,
int nRequestID, bool bIsLast);
///当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。
///@param nReason 错误原因
/// 0x1001 网络读失败
/// 0x1002 网络写失败
/// 0x2001 接收心跳超时
/// 0x2002 发送心跳失败
/// 0x2003 收到错误报文
virtual void OnFrontDisconnected(int nReason);
///心跳超时警告。当长时间未收到报文时,该方法被调用。
///@param nTimeLapse 距离上次接收报文的时间
virtual void OnHeartBeatWarning(int nTimeLapse);
///当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。
virtual void OnFrontConnected();
///登录请求响应
virtual void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, 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 OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData);
private:
void ReqUserLogin();
void SubscribeMarketData();
//
bool IsErrorRspInfo(CThostFtdcRspInfoField *pRspInfo);
};
//MyTrader.h
#pragma once
//
#include <string>
#include <iomanip>
#include <vector>
#include ".\ThostTraderApi\ThostFtdcTraderApi.h"
#include ".\ThostTraderApi\ThostFtdcMdApi.h"
#include "TraderSpi.h"
#include "MdSpi.h"
#pragma warning(disable : 4996)
// User行情数据
extern char *InstrumentID_name; //
extern string Q_BarTime_s; //时间字符串
extern int Q_BarTime_1; //时间采用秒计
extern double Q_BarTime_2; //时间格式0.145100
extern double Q_UpperLimit; //
extern double Q_LowerLimit; //
extern double NewPrice; //
extern int FirstVolume; //前一次成交量数据
extern double Mn_open[3]; //
extern double Mn_high[3]; //
extern double Mn_low[3]; //
extern double Mn_close[3]; //
extern double BuyPrice; //开仓价
extern double SellPrice; //开仓价
extern int BNum; //开仓次数
extern int SNum; //开仓次数
extern bool BuySignal; //
extern bool SellSignal; //
extern double BSVolume; //开仓量
extern int TickABS;
extern double TickAPrice[4]; //
extern int TickBNum;
extern double TickBPrice[4]; //
extern char LogFilePaths[80]; //
void Trading() //下单以及订单管理
{
void SendOrder(TThostFtdcInstrumentIDType FuturesId,int BuySell,int OpenClose);
void _record0(double system_times, char *txt, double SPrice, double BPrice);
void StopLoss(double system_times);
bool TradingTime=(Q_BarTime_2>0.0910 && Q_BarTime_2<0.2355); //交易时间
bool fanshou=false; //反手使能
//调用止损子程序 ************************优先判断是否符号止损止盈条件,在进行开仓处理;
StopLoss(Q_BarTime_2);
if (TickABS==1 && TradingTime)
{
if (SellSignal == true && fanshou) //如果有持仓,先平仓
{
SendOrder(INSTRUMENT_ID, 0, 3); //买平
cerr << "--->>> " << TradingDay << "_" << Q_BarTime_s << "_" << INSTRUMENT_ID << "_买_平仓" << endl;
_record0(Q_BarTime_2, "_买_平仓", NewPrice, NewPrice);
}
SendOrder(INSTRUMENT_ID, 0, 0);
BuyPrice=NewPrice;
SellPrice=0;
cerr << "--->>> " << TradingDay << "_" << Q_BarTime_s << "_" << INSTRUMENT_ID << "_买_开仓" << endl;
_record0(Q_BarTime_2, "_买_开仓", BuyPrice, BuyPrice);
}
if (TickABS==2 && TradingTime)
{
if (BuySignal == true && fanshou) //如果有持仓,先平仓
{
SendOrder(INSTRUMENT_ID, 1, 3);
cerr << "--->>> " << TradingDay << "_" << Q_BarTime_s << "_" << INSTRUMENT_ID << "_卖_平仓" << endl;
_record0(Q_BarTime_2, "_卖_平仓", NewPrice, NewPrice);
}
SendOrder(INSTRUMENT_ID, 1, 0);
BuyPrice=0;
SellPrice=NewPrice;
cerr << "--->>> " << TradingDay << "_" << Q_BarTime_s << "_" << INSTRUMENT_ID << "_卖_开仓" << endl;
_record0(Q_BarTime_2, "_卖_开仓", SellPrice, SellPrice);
}
}
void StopLoss(double system_times)
{
void SendOrder(TThostFtdcInstrumentIDType FuturesId,int a,int b);
void _record0(double system_times, char *txt, double SPrice, double BPrice);
bool stopwin =true; //使能止盈
bool stoploss=true; //使能止损
bool stoptime=true; //使能收盘平仓
double surplus =20; //止赢幅度
double Stopline =30; //止损幅度
//止赢平仓
if (BuySignal == true && (NewPrice-BuyPrice) >= surplus && stopwin)
{
SendOrder(INSTRUMENT_ID, 1, 3);
cerr << "--->>> " << TradingDay << "_" << Q_BarTime_s << "_" << INSTRUMENT_ID << "_卖_平仓止赢_" << BuyPrice << endl;
_record0(system_times, "_卖_平仓止赢_", BuyPrice, BuyPrice);
}
if (SellSignal == true && (SellPrice-NewPrice) >= surplus && stopwin)
{
SendOrder(INSTRUMENT_ID, 0, 3);
cerr << "--->>> " << TradingDay << "_" << Q_BarTime_s << "_" << INSTRUMENT_ID << "_买_平仓止赢_" << SellPrice << endl;
_record0(system_times, "_买_平仓止赢_", SellPrice, SellPrice);
}
//止损平仓
if (BuySignal == true && (BuyPrice-NewPrice)>Stopline && stoploss)
{
SendOrder(INSTRUMENT_ID,1,3);
cerr << "--->>> " << TradingDay << "_" << Q_BarTime_s << "_" << INSTRUMENT_ID << "_卖_平仓止损_" << BuyPrice << endl;
_record0(system_times, "_卖_平仓止损_", BuyPrice, BuyPrice);
}
if (SellSignal == true && (NewPrice-SellPrice)>Stopline && stoploss)
{
SendOrder(INSTRUMENT_ID,0,3);
cerr << "--->>> " << TradingDay << "_" << Q_BarTime_s << "_" << INSTRUMENT_ID << "_买_平仓止损_" << SellPrice << endl;
_record0(system_times, "_买_平仓止损_", SellPrice, SellPrice);
}
//收盘平仓
if (BuySignal == true && Q_BarTime_2>0.1455 && stoptime)
{
SendOrder(INSTRUMENT_ID,1,3);
cerr << "--->>> " << TradingDay << "_" << Q_BarTime_s << "_" << INSTRUMENT_ID << "_卖_平仓收盘_" << BuyPrice << endl;
_record0(system_times, "_卖_平仓收盘_", BuyPrice, BuyPrice);
}
if (SellSignal == true && Q_BarTime_2>0.1455 && stoptime)
{
SendOrder(INSTRUMENT_ID,0,3);
cerr << "--->>> " << TradingDay << "_" << Q_BarTime_s << "_" << INSTRUMENT_ID << "_买_平仓收盘_" << SellPrice << endl;
_record0(system_times, "_买_平仓收盘_", SellPrice, SellPrice);
}
}
// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//
#pragma once
#ifndef _WIN32_WINNT // 允许使用特定于 Windows XP 或更高版本的功能。
#define _WIN32_WINNT 0x0501 // 将此值更改为相应的值,以适用于 Windows 的其他版本。
#endif
#include <stdio.h>
#include <tchar.h>
#include <string.h>
#include <windows.h>
#include <iostream>
using namespace std;
// TODO: 在此处引用程序需要的其他头文件