根据用户输入不同的条件进行修改止损止盈
实现代码
// 盈利盈利止损止盈
bool moveSLTPProfit(const string symbol,
const int type,
const int sl,
const int tp,
const ulong magic
)
{
int len = PositionsTotal();
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
PositionInfo pos_info;
for(int i=0; i<len; i++)
{
// 如果订单没找到直接跳过该订单
if(!getPositionInfo(i,pos_info)) continue;
// 订单获取成功
printf("找到订单了!");
if(type == 0){
if(pos_info.sl <= ask - sl * point){
moveSLTP(pos_info, symbol, type, ask, sl, tp,magic);
}
}
else if(type == 1)
if(pos_info.sl >= bid + sl *point)
moveSLTP(pos_info, symbol, type, bid, sl, tp,magic);
}
return false;
}
bool moveSLTP(PositionInfo &pos_info,
const string symbol,
const int type,
const double price,
const int sl,
const int tp,
const ulong magic)
{
// 不满足条件直接退出
string m_sym = valSymbol(symbol);
if(m_sym == "") return false;
if(pos_info.magic != magic) return false;
if(pos_info.symbol != m_sym) return false;
if(pos_info.type != type) return false;
printf("条件满足,进入");
double m_sl = valStopLossPrice(m_sym, type, price,sl);
double m_tp = valTakeProfitPrice(m_sym, type, price,tp);
if(m_sl == pos_info.sl && m_tp == pos_info.tp) return false;
printf("止损价: %f, 止盈价: %f", m_sl, m_tp);
if(m_sl == 0 && m_tp == 0) return false;
else if(m_sl != pos_info.sl && m_tp == 0)
return moveSLTPBase(pos_info.ticket, m_sym, m_sl, pos_info.tp,magic);
else if(m_sl == 0 && m_tp != pos_info.tp)
return moveSLTPBase(pos_info.ticket, m_sym, pos_info.sl, m_tp,magic);
else if(m_sl != pos_info.sl && m_tp != pos_info.tp)
return moveSLTPBase(pos_info.ticket, m_sym, m_sl, m_tp,magic);
return false;
}
// 修改止损止盈发送请求组件
bool moveSLTPBase(const ulong ticket,
const string symbol,
const double stop_loss,
const double take_profit,
const ulong magic
)
{
// 3 创建和初始化交易请求体和返回响应结构体
MqlTradeRequest request = {};
MqlTradeResult result = {};
//--- 设置操作参数
request.action =TRADE_ACTION_SLTP; // 交易操作类型
request.position=ticket; // 持仓单号
request.symbol=symbol; // 交易品种
request.sl =stop_loss; // 持仓止损
request.tp =take_profit; // 持仓止赢
request.magic=magic; // 持仓的识别码
bool is_ok = OrderSend(request, result);
if(is_ok)
{
return true;
}
else
{
printf("发送交易请求修改失败,错误代码: %d", GetLastError());
// 重置错误代码
ResetLastError();
return false;
}
}