30 Star 78 Fork 79

liuyinghua/FastTrader

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
FourPriceStrategy.cpp 10.78 KB
一键复制 编辑 原始数据 按行查看 历史
#include "stdafx.h"
#include "FourPriceStrategy.h"
#include "../ConfigLib/ConfigReader.h"
#include "../Log/logging.h"
#include "../FacilityBaseLib/Container.h"
#include "../FacilityBaseLib/InstrumentData.h"
#include "../FacilityBaseLib/Express.h"
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
FourPriceStrategy::FourPriceStrategy(const std::string& id)
:IStrategy(id)
{
LOGINIT("FourPriceStrategy");
}
void FourPriceStrategy::Initialize()
{
ReadConfig();
//数据存储;
auto& InstrumentHandsMap = GetInstruments();
for (auto iIter = InstrumentHandsMap.begin(); iIter != InstrumentHandsMap.end(); ++iIter)
{
FourPrice_Params& params = m_ParamsMap[iIter->first];
params.nBuyJumps = 1;
params.nSellJumps = 1;
params.dMoveProfit = 0.5;
params.dMaxProfit = 0;
params.nProfitJumps = 5;
params.cancelCount = 0;
params.nHands = iIter->second;
instrument_info infoA;
auto bFindA = instrument_container::get_instance().GetInstrumentInfo(iIter->first.c_str(), &infoA);
if (bFindA)
{
params.PriceTick = infoA.PriceTick;
}
else
{
params.PriceTick = 1;
}
}
}
void FourPriceStrategy::Finalize()
{
//界面退出后停止交易;
WriteConfig();
}
void FourPriceStrategy::OnOrder(boost::shared_ptr<Order> order)
{
if (!order)
{
return;
}
if (order->ErrorID != 0)
{
//LOGDEBUG("报单回报出错:"<<order->ErrorMsg);
}
if (order->OrderSysID.empty())
{
return;
}
//boost::mutex::scoped_lock lck(m_Mutex4Param);
bool bPriceMarginChanged = false;
FourPrice_Params* param = &m_ParamsMap[order->InstrumentID];
if (order->CombOffsetFlag[0] == OF_Open)
{
//开仓;
if (param->openInputOrder
&& (order->OrderRef == param->openInputOrder->OrderRef)
&& order->InstrumentID == param->InstrumentID)
{
if (order->ErrorID != 0 || order->OrderStatus == EnumOrderStatus::OST_Canceled)
{
param->openInputOrder = nullptr;
param->cancelOpenOrder = nullptr;
param->openOrder = nullptr;
param->cancelCount += 1;
LOGDEBUG("撤开仓单成功...");
}
else
{
param->openOrder = order;
if (param->openInputOrder)
{
param->openInputOrder->OrderSysID
= order->OrderSysID;
param->openInputOrder->InstrumentID
= order->InstrumentID;
param->openInputOrder->ExchangeID
= order->ExchangeID;
}
}
bPriceMarginChanged = true;
}
}
else
{
//平仓的情况;
if (param->closeInputOrder
&& (order->OrderRef == param->closeInputOrder->OrderRef)
&& order->InstrumentID == param->InstrumentID)
{
if (order->ErrorID != 0 || order->OrderStatus == EnumOrderStatus::OST_Canceled)
{
param->closeInputOrder = nullptr;
param->cancelCloseOrder = nullptr;
param->closeOrder = nullptr;
param->cancelCount += 1;
LOGDEBUG("平仓单撤单成功...");
}
else
{
param->closeOrder = order;
param->closeInputOrder->OrderSysID
= order->OrderSysID;
param->closeInputOrder->InstrumentID
= order->InstrumentID;
param->closeInputOrder->ExchangeID
= order->ExchangeID;
}
bPriceMarginChanged = true;
}
}
}
void FourPriceStrategy::OnTrade(boost::shared_ptr<Trade> trade)
{
if (!trade)
{
return;
}
//成交之后将InputOrder重置以便再次开仓;
if (trade->OffsetFlag == OF_Open)
{
//开仓;
LOGDEBUG("开仓成功");
}
else
{
//平仓;
FourPrice_Params& params = m_ParamsMap[trade->InstrumentID];
params.openInputOrder = nullptr;
params.closeInputOrder = nullptr;
params.openOrder = nullptr;
params.closeOrder = nullptr;
LOGDEBUG("平仓成功");
}
}
void FourPriceStrategy::OnTick(boost::shared_ptr< Tick > tick)
{
auto& param = m_ParamsMap[tick->InstrumentID()];
param.lastTick = tick;
boost::posix_time::ptime tickTime = boost::posix_time::from_time_t(tick->UpdateTime);
if (tickTime.time_of_day() >= param.ClosePositionTime)
{
//平所有仓位不再开;
LOGDEBUG("开始平仓");
CloseAllPositions();
return;
}
//止盈;
int signedPosition = GetSignedPosition(param.InstrumentID);
if (signedPosition > 0)
{
//多头止盈;
double PositionCost = 0;
if (GetPositionCost(tick->InstrumentID(), PositionCost))
{
//当前盈利;
double profit = tick->LastPrice-PositionCost;
if (profit > param.dMaxProfit)
{
param.dMaxProfit=profit;
}
else if (param.dMaxProfit > param.nProfitJumps* param.PriceTick && param.dMaxProfit*param.dMoveProfit <= profit)
{
//立即止盈;
if (!param.closeInputOrder)
{
//如果有多单,平多单;
LOGDEBUG("多头止盈");
param.closeInputOrder = MyOrderInsert(param.InstrumentID, param.nHands, tick->BidPrice[0], OF_CloseToday, D_Sell);
}
}
}
}
else if (signedPosition < 0)
{
//空头止盈;
double PositionCost = 0;
if (GetPositionCost(tick->InstrumentID(), PositionCost))
{
//当前盈利;
double profit = PositionCost - tick->LastPrice;
if (profit > param.dMaxProfit)
{
param.dMaxProfit = profit;
}
else if (param.dMaxProfit > param.nProfitJumps* param.PriceTick && param.dMaxProfit*param.dMoveProfit <= profit)
{
//立即止盈;
if (!param.closeInputOrder)
{
//如果有空单,则应先平空仓;
LOGDEBUG("空头止盈");
param.closeInputOrder = MyOrderInsert(param.InstrumentID, param.nHands, tick->AskPrice[0], OF_CloseToday, D_Buy);
}
}
}
}
if (tick->LastPrice > param.dYesterdayHighest)
{
//做多;
if (!param.openInputOrder && !param.closeInputOrder)
{
LOGDEBUG("直接开多");
param.openInputOrder = MyOrderInsert(param.InstrumentID, param.nHands, tick->AskPrice[0], OF_Open, D_Buy);
}
}
if (tick->LastPrice < param.dYesterdayLowest)
{
//做空;
if (!param.openInputOrder && !param.closeInputOrder)
{
LOGDEBUG("直接开空");
param.openInputOrder = MyOrderInsert(param.InstrumentID, param.nHands, tick->BidPrice[0], OF_Open, D_Sell);
}
}
}
bool FourPriceStrategy::ReadConfig()
{
//读取配置文件;
bool bRet = false;
TiXmlDocument document("user.xml");
if (!document.LoadFile())
{
return false;
}
//获得根元素,即Persons。
TiXmlElement* root = document.RootElement();
if (NULL == root)
{
return false;
}
std::string broker_tag_name = "Strategy";
TiXmlElement* elem = root->FirstChildElement(broker_tag_name.c_str());
if (!elem)
{
bRet = false;
}
while (NULL != elem)
{
do
{
std::string StrategyID = GetAttribute(elem, "StrategyID");
const std::string& myId = GetId();
if (StrategyID != myId)
{
continue;
}
std::string mainUserID = GetAttribute(elem, "UserID");
TiXmlElement* multiuser_elem = elem->FirstChildElement("HighestPriceList");
if (multiuser_elem)
{
std::vector<TiXmlElement*> users_elems = GetSubElements(multiuser_elem, "PriceMargin");
for (std::size_t k = 0; k < users_elems.size(); ++k)
{
if (users_elems[k])
{
FourPrice_Params params;
params.InstrumentID = GetAttribute(users_elems[k],"InstrumentID");
params.nHands = GetInstruments()[params.InstrumentID];
std::string szCloseTime = GetAttribute(users_elems[k], "ClosePositionTime");
params.ClosePositionTime = boost::posix_time::duration_from_string(szCloseTime);
params.dYesterdayHighest = std::stod(GetAttribute(users_elems[k],"YDHighestPrice"));
params.dYesterdayLowest = std::stod(GetAttribute(users_elems[k], "YDLowestPrice"));
m_ParamsMap[params.InstrumentID] = params;
}
}
bRet = true;
}
} while (0);
elem = elem->NextSiblingElement(broker_tag_name.c_str());
}
return bRet;
}
bool FourPriceStrategy::WriteConfig()
{
//读取配置文件;
bool bRet = false;
TiXmlDocument document("user.xml");
if (!document.LoadFile())
{
return false;
}
//获得根元素,即Persons。
TiXmlElement* root = document.RootElement();
if (NULL == root)
{
return false;
}
string broker_tag_name = "Strategy";
TiXmlElement* elem = root->FirstChildElement(broker_tag_name.c_str());
if (!elem)
{
bRet = false;
}
while (NULL != elem)
{
do
{
std::string StrategyID = GetAttribute(elem, "StrategyID");
const std::string& myId = GetId();
if (StrategyID != myId)
{
continue;
}
std::string mainUserID = GetAttribute(elem, "UserID");
TiXmlElement* multiuser_elem = elem->FirstChildElement("HighestPriceList");
if (multiuser_elem)
{
std::vector<TiXmlElement*> users_elems = GetSubElements(multiuser_elem, "PriceMargin");
for (size_t k = 0; k < users_elems.size(); ++k)
{
if (users_elems[k])
{
std::string InstrumentID = GetAttribute(users_elems[k],"InstrumentID" );
FourPrice_Params& params = m_ParamsMap[InstrumentID];
SetAttribute(users_elems[k], "InstrumentID", params.InstrumentID);
SetAttribute(users_elems[k], "ClosePositionTime",boost::posix_time::to_iso_string(params.ClosePositionTime));
SetAttribute(users_elems[k], "YDHighestPrice", params.lastTick->HighestPrice);
SetAttribute(users_elems[k], "YDLowestPrice", params.lastTick->LowerLimitPrice);
}
}
bRet = true;
document.SaveFile();
}
} while (0);
if (bRet)
{
break;
}
elem = elem->NextSiblingElement(broker_tag_name.c_str());
}
return bRet;
}
FourPriceStrategy::~FourPriceStrategy()
{
}
boost::shared_ptr<InputOrder> FourPriceStrategy::MyOrderInsert(const std::string& instId, int Volume, double Price,
EnumOffsetFlag OpenOrClose, EnumDirection BuyOrSell)
{
boost::shared_ptr<InputOrder> inputOrder = boost::make_shared<InputOrder>();
inputOrder->InstrumentID = instId;
inputOrder->VolumeTotalOriginal = Volume;
inputOrder->LimitPrice = Price;
inputOrder->MinVolume = Volume;
inputOrder->CombOffsetFlag[0] = OpenOrClose;
inputOrder->CombOffsetFlag[1] = OF_None;
inputOrder->CombOffsetFlag[2] = OF_None;
inputOrder->CombOffsetFlag[3] = OF_None;
inputOrder->CombOffsetFlag[4] = OF_None;
inputOrder->Direction = BuyOrSell;
inputOrder->OrderPriceType = OPT_LimitPrice;
inputOrder->CombHedgeFlag[0] = HF_Speculation;
inputOrder->CombHedgeFlag[1] = HF_None;
inputOrder->CombHedgeFlag[2] = HF_None;
inputOrder->CombHedgeFlag[3] = HF_None;
inputOrder->CombHedgeFlag[4] = HF_None;
return OrderInsert(inputOrder, GetMainTrader());
}
// boost::shared_ptr<InputOrderAction> DualMAStrategy::SafeCancelOrder(boost::shared_ptr<Order> order)
// {
// if (!order)
// {
// return false;
// }
// //DEBUG_METHOD();
// int frontId = order->FrontID, sessionId = order->SessionID;
// auto traderid = GetTraderIDByFronIDSessionID(frontId, sessionId);
// if (!traderid)
// {
// return false;
// }
// boost::shared_ptr<InputOrderAction> inputOrderAction = boost::make_shared<InputOrderAction>();
// inputOrderAction->FrontID = frontId;
// inputOrderAction->SessionID = sessionId;
// inputOrderAction->OrderRef = order->OrderRef;
// inputOrderAction->InvestorID = order->InvestorID;
// inputOrderAction->BrokerID = order->BrokerID;
// inputOrderAction->InstrumentID = order->InstrumentID;
// inputOrderAction->ExchangeID = order->ExchangeID;
// inputOrderAction->OrderSysID = order->OrderSysID;
// return OrderCancel(inputOrderAction, traderid);
//
// }
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/mongodb_client/FastTrader.git
[email protected]:mongodb_client/FastTrader.git
mongodb_client
FastTrader
FastTrader
master

搜索帮助