Home Scripts Search
Back

马丁格尔做多 EURUSD(MartingaleEURUSD)

MQL4 EA · Expert Advisors v1.00
trader01 👁 5 Views ⬇ 2 Downloads 📅 2026-11-29 03:08:38 Updated: 2026-11-29 03:08:38

Details

EURUSD 马丁格尔做多 EA:首仓亏损超过间距后按倍数加仓,整体浮盈达到目标点数后一次性全部平掉,然后重新开始。

  • 可配置首仓手数、加仓倍数、间距(pips)、整体止盈点数
  • 最大加仓次数上限,防止无限加仓
  • 硬止损:equity 回撤到设定百分比时强平所有仓位
  • EA 重启后自动恢复已有仓位状态(断点续跑)
  • 平仓失败自动重试(最多 3 轮),处理 requotes

⚠ 马丁格尔策略在趋势性下跌中会连续加仓直至爆仓。请务必先在模拟账户测试,并始终启用硬止损。不要用生活资金跑马丁。

安装:复制到 MQL4/Experts,F7 编译,挂到 EURUSD 图表。仅支持 BUY 方向。

Source Code

MQL4
//+------------------------------------------------------------------+
//| MartingaleEURUSD.mq4                                             |
//| 马丁格尔做多 EURUSD EA:亏损加仓、盈利平仓                          |
//+------------------------------------------------------------------+
//  策略说明:
//  - 只在 EURUSD 上做多(BUY)
//  - 首次开仓 N 手,如果亏损超过加仓间距,按倍数加仓
//  - 所有仓位加权重后整体盈利超过目标点数,一次性全部平掉
//  - 重置后重新开始
//
//  ⚠ 风险警告:
//  马丁格尔策略在趋势性下跌行情中会连续加仓直至爆仓。
//  请务必在模拟账户上充分测试,并设置最大加仓次数与
//  硬止损(资金百分比)作为最后防线。不要用生活资金跑马丁。
//
//  安装:
//  1. 复制到 MQL4/Experts/ → F7 编译
//  2. 挂到 EURUSD 任意图表( timeframe 无关,逻辑只在 tick 里)
//  3. 确认「自动交易」开启
//+------------------------------------------------------------------+
#property copyright "mql4.xyz"
#property link      "https://mql4.xyz"
#property version   "1.00"
#property strict

//--- 输入参数
input double   InitialLots      = 0.01;    // 首次开仓手数
input double   LotMultiplier    = 2.0;     // 加仓倍数(2.0 = 每次翻倍)
input int      GridPips         = 30;      // 加仓间距(点,30 = 30 pips)
input int      TakeProfitPips   = 20;      // 整体止盈(点)
input int      MaxTrades        = 8;       // 最大加仓次数(含首仓)
input int      MagicNumber      = 20241129; // EA 标识
input double   HardStopPercent  = 50.0;    // 硬止损:回撤到 equity 的此百分比时强平所有(0=禁用)
input int      Slippage         = 3;       // 允许滑点(点)
input string   TradeComment     = "MartingaleEURUSD"; // 订单注释

//--- 全局变量
string   Symbol_Trade   = "EURUSD";
int      Ticket_First   = 0;         // 首仓 ticket
double   LastEntryPrice = 0;         // 最近一次开仓价
double   TotalLots      = 0;         // 当前总手数
int      TradeCount     = 0;         // 当前加仓次数

//+------------------------------------------------------------------+
int OnInit()
{
   if(Symbol() != Symbol_Trade)
   {
      Print("警告:此 EA 设计用于 ", Symbol_Trade, ",当前图表 ", Symbol(),
            "。请在 EURUSD 图表上运行。");
      // 不阻止运行,但警告
   }

   // 恢复已有仓位状态(EA 重启后)
   RestoreState();

   Print("MartingaleEURUSD 启动: lots=", DoubleToString(InitialLots, 2),
         " x", DoubleToString(LotMultiplier, 1),
         " grid=", GridPips, "pips TP=", TakeProfitPips, "pips max=", MaxTrades);

   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason)
{
   Print("MartingaleEURUSD 停止, reason=", reason);
}

//+------------------------------------------------------------------+
void OnTick()
{
   // 硬止损检查
   if(HardStopPercent > 0)
      CheckHardStop();

   // 没有仓位 → 开首仓
   if(CountMyOrders() == 0)
   {
      ResetState();
      OpenInitial();
      return;
   }

   // 有仓位 → 检查是否需要加仓
   CheckGrid();

   // 检查是否达到整体止盈
   CheckTakeProfit();
}

//+------------------------------------------------------------------+
//| 开首仓                                                             |
//+------------------------------------------------------------------+
void OpenInitial()
{
   double price = Ask;
   int ticket = OrderSend(Symbol_Trade, OP_BUY, InitialLots, price, Slippage,
                          0, 0, TradeComment + "-F0", MagicNumber, 0, clrGreen);

   if(ticket > 0)
   {
      Ticket_First = ticket;
      LastEntryPrice = price;
      TotalLots = InitialLots;
      TradeCount = 1;
      Print("[首仓] ticket=", ticket, " lots=", DoubleToString(InitialLots, 2),
            " price=", DoubleToString(price, Digits));
   }
   else
   {
      Print("[首仓失败] err=", GetLastError());
   }
}

//+------------------------------------------------------------------+
//| 网格加仓                                                           |
//+------------------------------------------------------------------+
void CheckGrid()
{
   if(TradeCount >= MaxTrades)
      return;

   double price = Ask;
   double distance = (LastEntryPrice - price) / Point;  // 正 = 价格跌了(浮亏方向)

   if(distance >= GridPips)
   {
      double nextLots = NormalizeLots(InitialLots * MathPow(LotMultiplier, TradeCount));

      if(nextLots <= 0)
      {
         Print("[加仓跳过] 手数无效: ", nextLots);
         return;
      }

      int ticket = OrderSend(Symbol_Trade, OP_BUY, nextLots, price, Slippage,
                             0, 0, TradeComment + "-G" + IntegerToString(TradeCount),
                             MagicNumber, 0, clrOrange);

      if(ticket > 0)
      {
         LastEntryPrice = price;
         TotalLots += nextLots;
         TradeCount++;
         Print("[加仓#", TradeCount, "] ticket=", ticket,
               " lots=", DoubleToString(nextLots, 2),
               " price=", DoubleToString(price, Digits),
               " 距上仓=", DoubleToString(distance, 0), "pips");
      }
      else
      {
         Print("[加仓失败] lots=", DoubleToString(nextLots, 2),
               " err=", GetLastError());
      }
   }
}

//+------------------------------------------------------------------+
//| 整体止盈                                                           |
//+------------------------------------------------------------------+
void CheckTakeProfit()
{
   double totalProfit = 0;
   double avgPrice = 0;
   double totalLots = 0;

   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if(OrderMagicNumber() != MagicNumber) continue;
      if(OrderSymbol() != Symbol_Trade) continue;
      if(OrderType() != OP_BUY) continue;

      totalProfit += OrderProfit() + OrderSwap() + OrderCommission();
      avgPrice += OrderOpenPrice() * OrderLots();
      totalLots += OrderLots();
   }

   if(totalLots <= 0) return;
   avgPrice /= totalLots;

   // 整体浮盈点数:当前价格高于加权均价的 pips
   double profitPips = (Bid - avgPrice) / Point;

   if(profitPips >= TakeProfitPips && totalProfit > 0)
   {
      Print("[止盈触发] profitPips=", DoubleToString(profitPips, 1),
            " totalProfit=", DoubleToString(totalProfit, 2),
            " trades=", TradeCount,
            " 总手数=", DoubleToString(totalLots, 2));

      CloseAll("TP");
      ResetState();
   }
}

//+------------------------------------------------------------------+
//| 硬止损:equity 回撤到阈值时强平                                     |
//+------------------------------------------------------------------+
void CheckHardStop()
{
   // 简单实现:当前 equity 跌到初始 balance × (1 - HardStopPercent/100)
   // 注:需要 EA 自己记录初始 balance,此处用 AccountEquity vs AccountBalance
   // 如果 equity 跌到 balance × (1 - pct),说明浮亏已超过阈值

   double threshold = AccountBalance() * (1.0 - HardStopPercent / 100.0);

   if(AccountEquity() <= threshold && CountMyOrders() > 0)
   {
      Print("!!! [硬止损触发] equity=", DoubleToString(AccountEquity(), 2),
            " balance=", DoubleToString(AccountBalance(), 2),
            " threshold=", DoubleToString(threshold, 2),
            " 强平所有仓位 !!!");
      CloseAll("HARD_STOP");
      ResetState();
      // 停止后续交易,等人工重启
      Print("硬止损已触发,EA 停止新开仓。请人工检查后重启。");
      return;
   }
}

//+------------------------------------------------------------------+
//| 平掉所有本 EA 的多单                                               |
//+------------------------------------------------------------------+
void CloseAll(string reason)
{
   for(int attempt = 0; attempt < 3; attempt++)
   {
      bool allClosed = true;

      for(int i = OrdersTotal() - 1; i >= 0; i--)
      {
         if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
         if(OrderMagicNumber() != MagicNumber) continue;
         if(OrderSymbol() != Symbol_Trade) continue;
         if(OrderType() != OP_BUY) continue;

         double closePrice = Bid;
         bool closed = OrderClose(OrderTicket(), OrderLots(), closePrice, Slippage, clrRed);

         if(!closed)
         {
            Print("[平仓失败] ticket=", OrderTicket(),
                  " err=", GetLastError(),
                  " attempt=", attempt + 1);
            allClosed = false;
            Sleep(200);
         }
      }

      if(allClosed) break;
      RefreshRates();
   }
}

//+------------------------------------------------------------------+
//| 工具函数                                                           |
//+------------------------------------------------------------------+
int CountMyOrders()
{
   int count = 0;
   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if(OrderMagicNumber() != MagicNumber) continue;
      if(OrderSymbol() != Symbol_Trade) continue;
      if(OrderType() != OP_BUY) continue;
      count++;
   }
   return count;
}

void ResetState()
{
   Ticket_First = 0;
   LastEntryPrice = 0;
   TotalLots = 0;
   TradeCount = 0;
}

void RestoreState()
{
   // EA 重启后从已有订单恢复状态
   int count = 0;
   double totalLots = 0;
   double lastPrice = 0;

   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if(OrderMagicNumber() != MagicNumber) continue;
      if(OrderSymbol() != Symbol_Trade) continue;
      if(OrderType() != OP_BUY) continue;

      count++;
      totalLots += OrderLots();
      // 最近开的仓 = ticket 最大的
      if(OrderTicket() > Ticket_First) Ticket_First = OrderTicket();
      if(lastPrice == 0 || OrderOpenTime() > StrToInteger(TimeToString(lastPrice)))
         lastPrice = OrderOpenPrice();
      // 简化:取最后一个遍历到的价格作为 lastPrice
      lastPrice = OrderOpenPrice();
   }

   if(count > 0)
   {
      TradeCount = count;
      TotalLots = totalLots;
      LastEntryPrice = lastPrice;
      Print("[恢复状态] 找到 ", count, " 个已有仓位, 总手数=",
            DoubleToString(totalLots, 2), " 最近入场=",
            DoubleToString(lastPrice, Digits));
   }
}

double NormalizeLots(double lots)
{
   double minLots = MarketInfo(Symbol_Trade, MODE_MINLOT);
   double maxLots = MarketInfo(Symbol_Trade, MODE_MAXLOT);
   double lotStep = MarketInfo(Symbol_Trade, MODE_LOTSTEP);

   if(lotStep <= 0) lotStep = 0.01;

   lots = MathFloor(lots / lotStep) * lotStep;

   if(lots < minLots) return 0;  // 小于最小手数 → 无效
   if(lots > maxLots) lots = maxLots;

   return NormalizeDouble(lots, 2);
}
//+------------------------------------------------------------------+