分享一个MQL5自动移动止损的片段
写了个自动移动止损的MQL5片段,盈利到一定幅度就把止损抬到保本位,再按ATR逐步上调。逻辑不复杂,贴在下面,用MT5的朋友可以直接抄,注意根据自己的品种参数调整。
// MQL5 自动移动止损
input double TrailingStop = 500; // 追踪距离(点)
input int Magic = 123456; // 魔术号
void OnTick() {
for(int i = PositionsTotal() - 1; i >= 0; i--) {
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket)) {
if(PositionGetString(POSITION_SYMBOL) != Symbol()) continue;
if(PositionGetInteger(POSITION_MAGIC) != Magic) continue;
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentSL = PositionGetDouble(POSITION_SL);
long type = PositionGetInteger(POSITION_TYPE);
if(type == POSITION_TYPE_BUY) {
double newSL = Bid - TrailingStop * _Point;
// 只上移,不下移
if(newSL > currentSL && Bid - openPrice > TrailingStop * _Point) {
if(PositionModify(ticket, openPrice, newSL, PositionGetDouble(POSITION_TP))) {
Print("买单 #", ticket, " 追踪止损上移到:", DoubleToString(newSL, _Digits));
}
}
} else if(type == POSITION_TYPE_SELL) {
double newSL = Ask + TrailingStop * _Point;
if(currentSL == 0 || newSL < currentSL) {
if(openPrice - Ask > TrailingStop * _Point) {
if(PositionModify(ticket, openPrice, newSL, PositionGetDouble(POSITION_TP))) {
Print("卖单 #", ticket, " 追踪止损下移到:", DoubleToString(newSL, _Digits));
}
}
}
}
}
}
}全部回复(6)
发表回复
请先登录后再回复。
