#include <Trade\Trade.mqh>
//--- 输入参数
input int BreakEvenPoints = 20; // 启动平保的点数
input int LockPoints = 0; // 平保锁定利润点数
CTrade trade;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
// 检查交易权限
if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
{
Alert("脚本检测到你没有允许自动交易,请先设置允许自动交易,再重新加载脚本");
return;
}
int total_positions = PositionsTotal();
if(total_positions == 0)
{
Print("没有持仓订单");
return;
}
// 遍历所有持仓
for(int i = total_positions - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket > 0)
{
string symbol = PositionGetString(POSITION_SYMBOL);
long type = PositionGetInteger(POSITION_TYPE);
double current_sl = PositionGetDouble(POSITION_SL);
double open_price = PositionGetDouble(POSITION_PRICE_OPEN);
// 获取当前价格
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
double new_sl = current_sl;
double profit_points = 0;
if(type == POSITION_TYPE_BUY)
{
profit_points = (bid - open_price) / point;
// 平保逻辑:当盈利达到指定点数且当前无止损时,设置止损到开仓价+锁定利润
if(current_sl == 0 && profit_points >= BreakEvenPoints)
{
new_sl = open_price + (LockPoints * point);
new_sl = NormalizeDouble(new_sl, digits);
}
}
else if(type == POSITION_TYPE_SELL)
{
profit_points = (open_price - ask) / point;
// 平保逻辑:当盈利达到指定点数且当前无止损时,设置止损到开仓价-锁定利润
if(current_sl == 0 && profit_points >= BreakEvenPoints)
{
new_sl = open_price - (LockPoints * point);
new_sl = NormalizeDouble(new_sl, digits);
}
}
// 如果需要修改止损
if(new_sl != current_sl)
{
double current_tp = PositionGetDouble(POSITION_TP);
if(trade.PositionModify(ticket, new_sl, current_tp))
{
Print("平保设置成功: ", symbol,
" 新止损: ", DoubleToString(new_sl, digits),
" 利润点数: ", DoubleToString(profit_points, 1));
}
else
{
Print("平保设置失败: ", symbol, " 错误代码: ", GetLastError());
}
}
}
}
Print("自动平保脚本执行完成");
}
//+------------------------------------------------------------------+