环森编程 24 段 · 零依赖

MQL4 工具 · 课程 35 配套

MQL4 代码片段库

把开仓、平仓、移动止损、时段过滤、指标信号这些高频逻辑拆成 24 段可复制的代码。每段都标注对应章节、常见错误和参数注意事项,复制后直接粘进 MetaEditor,不用再从论坛旧帖里翻。

24 段原创代码 6 类交易场景 每段标注课程位置 复制 / 下载 .mq4 不联网 · 不上传代码
先看边界:这些是函数/语句级片段,不是完整 EA。粘贴前先补齐 #property strict、input 参数和 OnTick() 调用;不同 broker 的 STOPLEVEL、点值和品种后缀不同,请先在模拟盘验证,不要直接上实盘。
24 段代码 按 / 或 Ctrl+K 聚焦搜索 · Esc 清除
下单与手数01

市价开仓(Buy / Sell)

一行 OrderSend 的下单模板:校验手数、刷新报价、按点数算 SL/TP,并把错误码打出来。

课程位置:下单函数·交易函数
// Send a market order with SL/TP and basic validation.
bool OpenMarketOrder(int type, double lots, int slippage,
                     double stopLossPoints, double takeProfitPoints,
                     int magic, string comment)
{
   if (type != OP_BUY && type != OP_SELL) return false;
   if (!IsTradeAllowed()) { Print("Trading is disabled"); return false; }
   if (lots <= 0) { Print("Invalid lots"); return false; }

   int stopLevel = (int)MarketInfo(Symbol(), MODE_STOPLEVEL);
   if (stopLossPoints > 0 && stopLossPoints < stopLevel) return false;
   if (takeProfitPoints > 0 && takeProfitPoints < stopLevel) return false;

   RefreshRates();
   double price = (type == OP_BUY) ? Ask : Bid;
   int    sign  = (type == OP_BUY) ? 1 : -1;
   double sl    = 0, tp = 0;

   if (stopLossPoints > 0)
      sl = NormalizeDouble(price - sign * stopLossPoints * Point, Digits);
   if (takeProfitPoints > 0)
      tp = NormalizeDouble(price + sign * takeProfitPoints * Point, Digits);

   if (AccountFreeMarginCheck(Symbol(), type, lots) <= 0 ||
       GetLastError() == ERR_NOT_ENOUGH_MONEY)
   {
      Print("Not enough free margin for ", lots, " lots");
      return false;
   }

   int ticket = OrderSend(Symbol(), type, lots, price, slippage,
                          sl, tp, comment, magic, 0, clrNONE);
   if (ticket < 0)
   {
      Print("OrderSend failed: ", GetLastError());
      return false;
   }
   return true;
}
  • OrderSend 的 price 必须用 RefreshRates() 后的 Ask/Bid;SL/TP 用 NormalizeDouble(..., Digits)。
  • 止损/止盈点数要 >= MODE_STOPLEVEL,否则报 130 invalid stops;ECN 账户可能要求先下单再改 SL/TP。
  • 下单前用 AccountFreeMarginCheck(),失败后立刻 GetLastError() 打印错误码;需要可读文本时用 error-text 片段里的 ErrorText()。
下单与手数02

挂单(Limit / Stop)

四种挂单类型的下单模板,带过期时间与 SL/TP,适合突破/回踩策略。

课程位置:下单函数·交易函数
// Place a pending order. price is the trigger price, not the current quote.
bool PlacePendingOrder(int type, double lots, double price,
                       double stopLossPoints, double takeProfitPoints,
                       datetime expiration, int magic)
{
   if (type != OP_BUYLIMIT && type != OP_SELLLIMIT &&
       type != OP_BUYSTOP  && type != OP_SELLSTOP) return false;

   int sign = (type == OP_BUYLIMIT || type == OP_BUYSTOP) ? 1 : -1;
   double sl = 0, tp = 0;

   if (stopLossPoints > 0)
      sl = NormalizeDouble(price - sign * stopLossPoints * Point, Digits);
   if (takeProfitPoints > 0)
      tp = NormalizeDouble(price + sign * takeProfitPoints * Point, Digits);

   int ticket = OrderSend(Symbol(), type, lots,
                          NormalizeDouble(price, Digits),
                          3, sl, tp, "pending", magic, expiration, clrNONE);
   if (ticket < 0)
   {
      Print("Pending order failed: ", GetLastError());
      return false;
   }
   return true;
}
  • BuyLimit 必须低于 Ask,BuyStop 必须高于 Ask;SellLimit 高于 Bid,SellStop 低于 Bid,否则 130。
  • expiration 为 0 表示 GTC;部分 broker 不支持挂单过期时间,会返回 130/147。
  • 挂单也占用保证金,单仓保护里要把挂单算进去。
下单与手数03

按风险百分比算手数

按“单笔风险百分比”反推手数,处理最小手数、最大手数和手数步长。

// Risk-based position size. stopLossPoints is the SL distance in points.
double LotsForRisk(double riskPercent, double stopLossPoints)
{
   if (riskPercent <= 0 || stopLossPoints <= 0) return 0;

   double riskMoney = AccountBalance() * riskPercent / 100.0;
   double tickValue = MarketInfo(Symbol(), MODE_TICKVALUE);
   double tickSize  = MarketInfo(Symbol(), MODE_TICKSIZE);
   if (tickSize <= 0 || tickValue <= 0) return 0;

   // Price distance / tick size * value per tick = loss for one lot.
   double lossPerLot = (stopLossPoints * Point / tickSize) * tickValue;
   if (lossPerLot <= 0) return 0;

   double minLot  = MarketInfo(Symbol(), MODE_MINLOT);
   double maxLot  = MarketInfo(Symbol(), MODE_MAXLOT);
   double lotStep = MarketInfo(Symbol(), MODE_LOTSTEP);

   double lots = riskMoney / lossPerLot;
   lots = MathFloor(lots / lotStep) * lotStep;
   lots = MathMax(minLot, MathMin(maxLot, lots));

   int digits = 2;
   if (lotStep < 0.01) digits = 3;
   else if (lotStep >= 1) digits = 0;
   return NormalizeDouble(lots, digits);
}
  • MODE_TICKVALUE 是每手每跳的账户货币价值;交叉盘/黄金要实测,不能硬编码。
  • 先按 MODE_LOTSTEP 向下取整,再夹在 MODE_MINLOT / MODE_MAXLOT 之间。
  • 这是“单笔风险”不是“保证盈利”;滑点、隔夜利息、点差会让实际亏损大于预算。
下单与手数04

止损止盈价格归一化

把点数换算成合法价格,检查 STOPLEVEL/FREEZELEVEL,避免 130 invalid stops。

// Convert point distances into valid SL/TP prices.
bool NormalizeStops(double price, int type, double stopLossPoints,
                    double takeProfitPoints, double &sl, double &tp)
{
   int stopLevel = (int)MarketInfo(Symbol(), MODE_STOPLEVEL);
   int freeze    = (int)MarketInfo(Symbol(), MODE_FREEZELEVEL);
   int minDist   = MathMax(stopLevel, freeze);
   int sign      = (type == OP_BUY) ? 1 : -1;

   if (stopLossPoints > 0 && stopLossPoints < minDist) return false;
   if (takeProfitPoints > 0 && takeProfitPoints < minDist) return false;

   sl = (stopLossPoints > 0)
      ? NormalizeDouble(price - sign * stopLossPoints * Point, Digits) : 0;
   tp = (takeProfitPoints > 0)
      ? NormalizeDouble(price + sign * takeProfitPoints * Point, Digits) : 0;
   return true;
}
  • MODE_STOPLEVEL / MODE_FREEZELEVEL 的单位是 point,不是价格。
  • 5 位报价的 1 点 = Point;很多平台口头的“10 点”指 pip,写代码统一用 point。
  • 先 RefreshRates() 再算;挂单还要检查 freeze level。
订单管理05

按 ticket 平仓(带重试)

按 ticket 平仓,带 3 次重试与报价刷新,处理 requote/context busy。

bool CloseTicket(int ticket, int slippage)
{
   if (!OrderSelect(ticket, SELECT_BY_TICKET)) return false;
   if (OrderCloseTime() != 0) return true;   // already closed

   int type = OrderType();
   double lots = OrderLots();

   for (int attempt = 1; attempt <= 3; attempt++)
   {
      RefreshRates();
      double price = (type == OP_BUY) ? Bid : Ask;
      if (OrderClose(ticket, lots, price, slippage, clrNONE))
         return true;

      Print("Close attempt ", attempt, " failed: ", GetLastError());
      Sleep(200);
   }
   return false;
}
  • OrderClose 的 price 对 Buy 用 Bid、对 Sell 用 Ask;传反了会 129 invalid price。
  • 平仓可能 146 context busy / 138 requote,重试前 Sleep(200) 并 RefreshRates()。
  • 平仓前确认 OrderCloseTime()==0,别对已平仓单重复操作。
订单管理06

平掉本 EA 全部持仓

按 magic + symbol 平掉本 EA 的全部持仓,倒序遍历避免漏单。

// Close all open positions of this EA. Pending orders are skipped.
int CloseAllOrders(int magic, int slippage)
{
   int closed = 0;
   for (int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if (OrderMagicNumber() != magic) continue;
      if (OrderSymbol() != Symbol()) continue;
      if (OrderType() > OP_SELL) continue;   // skip pending orders

      RefreshRates();
      double price = (OrderType() == OP_BUY) ? Bid : Ask;
      if (OrderClose(OrderTicket(), OrderLots(), price, slippage, clrNONE))
         closed++;
      else
         Print("Close failed: ", GetLastError());
   }
   return closed;
}
  • 边遍历边平仓必须倒序 for (i=OrdersTotal()-1; i>=0; i--),否则索引会跳单。
  • 只平 OrderType()<=OP_SELL 的持仓;挂单要用 OrderDelete。
  • 先按 magic + symbol 过滤,避免误平其他 EA 或手工单。
订单管理07

部分平仓

只平掉一部分手数,保留 ticket 和剩余仓位,适合分批止盈。

课程位置:交易函数
bool PartialClose(int ticket, double lotsToClose, int slippage)
{
   if (!OrderSelect(ticket, SELECT_BY_TICKET)) return false;
   if (OrderType() > OP_SELL) return false;
   if (lotsToClose <= 0 || lotsToClose >= OrderLots()) return false;

   double step = MarketInfo(OrderSymbol(), MODE_LOTSTEP);
   double minLot = MarketInfo(OrderSymbol(), MODE_MINLOT);
   lotsToClose = MathFloor(lotsToClose / step) * step;
   if (lotsToClose < minLot) return false;
   if (OrderLots() - lotsToClose < minLot) return false;

   RefreshRates();
   double price = (OrderType() == OP_BUY) ? Bid : Ask;
   if (!OrderClose(ticket, lotsToClose, price, slippage, clrNONE))
   {
      Print("Partial close failed: ", GetLastError());
      return false;
   }
   return true;
}
  • 剩余手数必须 >= MODE_MINLOT,且是 MODE_LOTSTEP 的整数倍。
  • 部分平仓后 ticket 不变,但手数变少;不要用旧 OrderLots() 继续算。
  • 部分平仓在一些平台会拆成新 deal,报表里按 deal 统计。
订单管理08

统计订单数与总手数

统计本 EA 的订单数与总手数,支持按持仓/挂单类型过滤。

// typeFilter: OP_BUY / OP_SELL / OP_BUYLIMIT ... or -1 for all.
int CountOrders(int magic, int typeFilter, double &totalLots)
{
   int count = 0;
   totalLots = 0;

   for (int i = 0; i < OrdersTotal(); i++)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if (OrderMagicNumber() != magic || OrderSymbol() != Symbol()) continue;
      if (typeFilter >= 0 && OrderType() != typeFilter) continue;

      count++;
      totalLots += OrderLots();
   }
   return count;
}
  • OrdersTotal() 包含挂单;要区分持仓/挂单用 OrderType()。
  • 引用参数 double &totalLots 调用前必须先声明变量。
  • 统计用正序遍历即可,平仓/删除才需要倒序。
订单管理09

订单池倒序遍历模板

订单池倒序遍历模板:打印 ticket、类型、手数、浮盈,平仓/改单都从它改。

void ScanOrders()
{
   for (int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;

      int    ticket = OrderTicket();
      int    type   = OrderType();
      double lots   = OrderLots();
      double profit = OrderProfit() + OrderSwap() + OrderCommission();

      Print(ticket, " type=", type, " lots=", lots, " profit=", profit);
   }
}
  • OrderSelect(i, SELECT_BY_POS) 的顺序不保证按开仓时间;要排序先收集 ticket。
  • 平仓/删单会让后面的索引前移,所以从 OrdersTotal()-1 开始。
  • 浮盈要加 OrderSwap() 和 OrderCommission(),只看 OrderProfit() 会偏高。
止损止盈10

保本(Move to Breakeven)

盈利达到触发点数后把 SL 移到开仓价+锁定点数,先把风险降为零。

课程位置:交易函数
void MoveToBreakeven(int magic, int triggerPoints, int lockPoints)
{
   for (int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if (OrderMagicNumber() != magic || OrderSymbol() != Symbol()) continue;
      if (OrderType() > OP_SELL) continue;

      double open = OrderOpenPrice();
      double sl   = OrderStopLoss();
      double bid  = MarketInfo(Symbol(), MODE_BID);
      double ask  = MarketInfo(Symbol(), MODE_ASK);

      if (OrderType() == OP_BUY)
      {
         if (bid - open < triggerPoints * Point) continue;
         double newSL = NormalizeDouble(open + lockPoints * Point, Digits);
         if (sl < newSL)
            OrderModify(OrderTicket(), open, newSL, OrderTakeProfit(), 0, clrBlue);
      }
      else
      {
         if (open - ask < triggerPoints * Point) continue;
         double newSL = NormalizeDouble(open - lockPoints * Point, Digits);
         if (sl == 0 || sl > newSL)
            OrderModify(OrderTicket(), open, newSL, OrderTakeProfit(), 0, clrRed);
      }
   }
}
  • 触发距离要覆盖点差+佣金,否则“保本”实际小亏。
  • 改 SL 前检查 MODE_STOPLEVEL,新 SL 离现价太近会 130。
  • 只在盈利方向移动,别把 SL 改到比开仓价更差的位置。
止损止盈11

移动止损(Trailing Stop)

按固定点数移动止损,带步长节流,只向盈利方向移动。

课程位置:交易函数
void TrailStop(int magic, int trailPoints, int stepPoints)
{
   for (int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if (OrderMagicNumber() != magic || OrderSymbol() != Symbol()) continue;
      if (OrderType() > OP_SELL) continue;

      double bid = MarketInfo(Symbol(), MODE_BID);
      double ask = MarketInfo(Symbol(), MODE_ASK);
      double sl  = OrderStopLoss();
      double newSL;

      if (OrderType() == OP_BUY)
      {
         newSL = NormalizeDouble(bid - trailPoints * Point, Digits);
         if (newSL - sl >= stepPoints * Point)
            OrderModify(OrderTicket(), OrderOpenPrice(), newSL,
                        OrderTakeProfit(), 0, clrGreen);
      }
      else
      {
         newSL = NormalizeDouble(ask + trailPoints * Point, Digits);
         if (sl == 0 || sl - newSL >= stepPoints * Point)
            OrderModify(OrderTicket(), OrderOpenPrice(), newSL,
                        OrderTakeProfit(), 0, clrRed);
      }
   }
}
  • 步长 stepPoints 防止每 tick 都 OrderModify,减少 146/130。
  • 新 SL 必须满足 stoplevel,且只向盈利方向移动。
  • 移动止损在跳空/新闻时可能滑点成交,回测和实盘会不同。
止损止盈12

跟踪止盈(回撤平仓)

从开仓以来的最高/最低价回撤固定点数就平仓,锁住趋势利润。

// Close when price gives back a fixed number of points from the extreme.
void TrailTakeProfit(int magic, int giveBackPoints)
{
   for (int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if (OrderMagicNumber() != magic || OrderSymbol() != Symbol()) continue;
      if (OrderType() > OP_SELL) continue;

      int shift = iBarShift(Symbol(), 0, OrderOpenTime());
      if (shift < 1) shift = 1;   // use closed bars only

      RefreshRates();
      if (OrderType() == OP_BUY)
      {
         int hi = iHighest(Symbol(), 0, MODE_HIGH, shift, 1);
         if (hi < 0) continue;
         double peak = High[hi];
         if (Bid <= peak - giveBackPoints * Point)
            OrderClose(OrderTicket(), OrderLots(), Bid, 3, clrNONE);
      }
      else
      {
         int lo = iLowest(Symbol(), 0, MODE_LOW, shift, 1);
         if (lo < 0) continue;
         double trough = Low[lo];
         if (Ask >= trough + giveBackPoints * Point)
            OrderClose(OrderTicket(), OrderLots(), Ask, 3, clrNONE);
      }
   }
}
  • iHighest/iLowest 的 count 从开仓 bar 算起,iBarShift 返回 -1 时要兜底。
  • 当前 bar 的最高/最低会变,稳健做法只用已收盘 bar(shift 1 起)。
  • 回撤点数要大于点差+滑点,否则容易被正常波动扫出。
止损止盈13

按 ATR 设止损止盈

用 ATR 算止损止盈点数,并按 STOPLEVEL 夹紧,适应不同波动率。

bool AtrStops(int atrPeriod, double slMultiplier, double tpMultiplier,
              double &slPoints, double &tpPoints)
{
   double atr = iATR(Symbol(), 0, atrPeriod, 1);
   if (atr == EMPTY_VALUE || atr <= 0) return false;

   slPoints = atr * slMultiplier / Point;
   tpPoints = atr * tpMultiplier / Point;

   int stopLevel = (int)MarketInfo(Symbol(), MODE_STOPLEVEL);
   if (slPoints < stopLevel) slPoints = stopLevel;
   if (tpPoints < stopLevel) tpPoints = stopLevel;

   slPoints = MathRound(slPoints);
   tpPoints = MathRound(tpPoints);
   return true;
}
  • iATR(..., 1) 用已收盘 bar,避免当前 bar 未完成导致信号跳动。
  • ATR 是价格距离,除以 Point 才是 point;5 位/3 位平台要验证。
  • 乘数越大越宽松;先用 1.5-3 倍做样本,不要拿“最优参数”当默认。
过滤14

交易时段过滤

按服务器时间过滤交易时段,支持跨夜 session 和周五提前收盘。

课程位置:日期和时间函数
// Hours are broker server time. Supports overnight sessions (22 -> 6).
bool IsTradingTime(int startHour, int endHour, bool closeOnFriday)
{
   datetime now = TimeCurrent();
   int hour = TimeHour(now);
   int dow  = TimeDayOfWeek(now);

   if (dow == 0 || dow == 6) return false;          // Sunday / Saturday
   if (closeOnFriday && dow == 5 && hour >= 20) return false;

   if (startHour <= endHour)
      return (hour >= startHour && hour < endHour);

   return (hour >= startHour || hour < endHour);    // overnight session
}
  • TimeCurrent() 是服务器时间,不是北京时间;先确认 broker 的 GMT 偏移。
  • 周五晚上/周一凌晨有跳空,closeOnFriday 建议在收盘前 1-2 小时。
  • 服务器夏令时(DST)会让固定小时漂移,必要时用 TimeGMTOffset() 校正。
过滤15

最大点差过滤

点差超过阈值就不开新仓,避开新闻和收盘前的异常点差。

bool SpreadOK(int maxSpreadPoints)
{
   double spread = (MarketInfo(Symbol(), MODE_ASK) -
                    MarketInfo(Symbol(), MODE_BID)) / Point;
   return (spread > 0 && spread <= maxSpreadPoints);
}
  • 用 (Ask-Bid)/Point 实时算,MODE_SPREAD 在部分平台是整数点、可能滞后。
  • 新闻/收盘前点差会瞬间放大,阈值要留余量。
  • 点差过滤只能减少不利成交,不能代替止损。
过滤16

最大订单数限制

限制同一 magic/symbol 的最大订单数,防止重复开仓。

bool CanOpenNewOrder(int magic, int maxOrders)
{
   int count = 0;
   for (int i = 0; i < OrdersTotal(); i++)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if (OrderMagicNumber() == magic && OrderSymbol() == Symbol())
         count++;
   }
   return (count < maxOrders);
}
  • 统计要包含挂单,否则“最多 1 单”会被挂单绕过。
  • 多品种 EA 要按 OrderSymbol() 分开计数。
  • 单仓保护最好再加“同一根 K 线只开一次”(配合 IsNewBar())。
过滤17

新 K 线检测

每根 K 线只执行一次,避免 OnTick 里反复下单/改单。

bool IsNewBar()
{
   static datetime lastBar = 0;
   if (Time[0] == lastBar) return false;
   lastBar = Time[0];
   return true;
}
  • static 变量按图表/EA 实例隔离,换周期或重载会重置。
  • 多品种 EA 不能共用一个 lastBar,要按 symbol 存数组。
  • 只适合“每根 K 线判断一次”的策略;剥头皮/tick 策略不要用。
指标与信号18

iMA 金叉 / 死叉信号

iMA 金叉/死叉信号,用 shift 1/2 的收盘值,返回 1/-1/0。

// method: MODE_SMA / MODE_EMA / MODE_SMMA / MODE_LWMA
int MaCrossSignal(int fastPeriod, int slowPeriod, int method)
{
   double fast1 = iMA(Symbol(), 0, fastPeriod, 0, method, PRICE_CLOSE, 1);
   double fast2 = iMA(Symbol(), 0, fastPeriod, 0, method, PRICE_CLOSE, 2);
   double slow1 = iMA(Symbol(), 0, slowPeriod, 0, method, PRICE_CLOSE, 1);
   double slow2 = iMA(Symbol(), 0, slowPeriod, 0, method, PRICE_CLOSE, 2);

   if (fast1 == EMPTY_VALUE || fast2 == EMPTY_VALUE ||
       slow1 == EMPTY_VALUE || slow2 == EMPTY_VALUE) return 0;

   if (fast2 <= slow2 && fast1 > slow1) return 1;    // golden cross
   if (fast2 >= slow2 && fast1 < slow1) return -1;   // death cross
   return 0;
}
  • 用 shift 1/2 的已收盘值,shift 0 会随当前价格跳动。
  • iMA 返回 EMPTY_VALUE 表示数据不足/参数错误,直接比较会把空值当信号。
  • 金叉死叉只是入场条件,必须再加过滤(趋势/波动/时段)和风控。
指标与信号19

iRSI 超买 / 超卖信号

iRSI 超买超卖信号,带 0 值保护,适合做过滤而不是单独入场。

课程位置:技术指标
int RsiSignal(int period, int oversold, int overbought)
{
   double rsi = iRSI(Symbol(), 0, period, PRICE_CLOSE, 1);
   if (rsi == EMPTY_VALUE || rsi <= 0) return 0;

   if (rsi < oversold)  return 1;
   if (rsi > overbought) return -1;
   return 0;
}
  • iRSI(..., 1) 用已收盘 bar;shift 0 会反复变,EMPTY_VALUE 表示数据不足。
  • 超买超卖在强趋势里会长期钝化,不能单独反向开仓。
  • 阈值 30/70 是默认值,不同品种/周期要回测,不要照搬。
指标与信号20

多品种报价与点差

多品种报价与点差读取模板,处理品种后缀和 Market Watch。

void PrintSymbolQuotes()
{
   string symbols[] = {"EURUSD", "GBPUSD", "USDJPY", "XAUUSD"};
   int total = ArraySize(symbols);

   for (int i = 0; i < total; i++)
   {
      string sym = symbols[i];
      double bid = MarketInfo(sym, MODE_BID);
      double ask = MarketInfo(sym, MODE_ASK);
      double point = MarketInfo(sym, MODE_POINT);
      if (bid <= 0 || ask <= 0 || point <= 0) continue;

      double spread = (ask - bid) / point;
      int digits = (int)MarketInfo(sym, MODE_DIGITS);
      Print(sym, " bid=", DoubleToString(bid, digits),
            " spread=", DoubleToString(spread, 1));
   }
}
  • 品种名要带 broker 后缀(如 EURUSD.a),否则 MarketInfo 返回 0。
  • 先把品种加入 Market Watch,否则部分平台取不到报价。
  • 多品种下单时 OrderSend 的 symbol 参数要传对应品种,不能写 Symbol()。
调试与运维21

错误码翻译与排查提示

把 OrderSend/OrderClose 的错误码翻译成可读日志,并给出 130/134/146 的排查提示。

string ErrorText(int code)
{
   switch (code)
   {
      case 129: return "Invalid price";
      case 130: return "Invalid stops";
      case 134: return "Not enough money";
      case 138: return "Requote";
      case 146: return "Trade context busy";
      case 147: return "Expiration denied";
      case 148: return "Too many orders";
      default:  return "Unknown error";
   }
}

void LogOrderError(string action, int code)
{
   Print(action, " failed. code=", code, " (", ErrorText(code), ")");

   if (code == ERR_INVALID_STOPS)
      Print("Check STOPLEVEL / FREEZELEVEL and NormalizeDouble().");
   else if (code == ERR_NOT_ENOUGH_MONEY)
      Print("Reduce lots or check AccountFreeMarginCheck().");
   else if (code == ERR_TRADE_CONTEXT_BUSY)
      Print("Another trade operation is running; retry after a tick.");
   else if (code == ERR_INVALID_PRICE)
      Print("RefreshRates() and send Bid/Ask for the right side.");
}
  • GetLastError() 要在失败后立刻取,后面的函数调用可能覆盖它。
  • 130/134/146 是最常见的三类:止损距离、保证金、并发交易。
  • 不要只 Print 错误码就继续下单;失败要 return,避免重复开仓。
调试与运维22

成交写入 CSV

把成交写入 CSV,方便回测后做 Excel 统计;含文件沙箱与分隔符说明。

课程位置:文件操作函数
void LogTradeToCsv(int ticket)
{
   if (!OrderSelect(ticket, SELECT_BY_TICKET)) return;

   int handle = FileOpen("ea-trades.csv",
                         FILE_READ | FILE_WRITE | FILE_CSV | FILE_ANSI, ';');
   if (handle == INVALID_HANDLE)
   {
      Print("FileOpen failed: ", GetLastError());
      return;
   }

   FileSeek(handle, 0, SEEK_END);
   FileWrite(handle,
             TimeToStr(TimeCurrent(), TIME_DATE | TIME_SECONDS),
             OrderTicket(), OrderSymbol(), OrderType(), OrderLots(),
             OrderOpenPrice(), OrderClosePrice(), OrderProfit());
   FileClose(handle);
}
  • MQL4 的文件只能写在 MQL4/Files(或测试器沙箱)里,路径不能用绝对路径。
  • 每次开/关文件很慢;高频策略用 FileFlush() + 保持 handle。
  • CSV 用分号分隔避免和中文/逗号冲突,Excel 打开时选对应分隔符。
调试与运维23

图表注释面板

在图表左上角显示订单数、浮盈和点差,1 秒节流刷新。

void ShowPanel(int magic)
{
   int count = 0;
   double floating = 0;

   for (int i = 0; i < OrdersTotal(); i++)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if (OrderMagicNumber() != magic || OrderSymbol() != Symbol()) continue;
      count++;
      floating += OrderProfit() + OrderSwap() + OrderCommission();
   }

   string text = StringFormat("EA %d | orders: %d | floating: %.2f | spread: %.1f",
                              magic, count, floating, (Ask - Bid) / Point);
   Comment(text);
}
  • Comment() 每 tick 调用会重绘,建议 1 秒节流(OnTimer)。
  • OnDeinit() 里要 Comment(""),否则面板会留在图表上。
  • 只做展示,不要用 ObjectCreate 每 tick 建对象,会泄漏图表对象。
调试与运维24

OnTimer 定时任务骨架

OnTimer 定时任务骨架:启动、清理、每秒/每分钟执行一次。

int OnInit()
{
   EventSetTimer(1);   // every second
   return INIT_SUCCEEDED;
}

void OnDeinit(const int reason)
{
   EventKillTimer();
   Comment("");
}

void OnTimer()
{
   static int ticks = 0;
   ticks++;

   if (ticks % 60 == 0)
      Print("timer alive, minutes=", ticks / 60);
}
  • EventSetTimer(1) 的单位是秒;策略测试器里的定时器行为与实盘不同。
  • OnDeinit() 必须 EventKillTimer(),否则重载 EA 会叠加定时器。
  • 定时器里不要做重活;下单/改单仍要检查 IsTradeAllowed()。

下一步:把片段拼成完整 EA

片段库解决“这一句怎么写”,参数生成器解决“第一份 EA 骨架长什么样”。两个工具都不上传代码、不连接账户。

使用说明

这些片段能直接编译吗?

不能单独编译。它们是函数或语句级示例,需要放进 EA 骨架,并补上 #property strict、input 参数和 OnTick() 里的调用。第一次写完整 EA,建议先看第 5 章「EA 的基本结构」和「实战:均线交叉 EA」。

为什么没有 MQL5 版本?

本站课程 35 讲的是 MetaTrader 4 的 MQL4。MQL5 的函数签名、订单处理和事件模型都不同,代码不能直接互搬;后续如果开 MQL5 课程,会单独做一套片段,而不是在这页混排。

能照着这些代码做真实交易吗?

不建议直接上实盘。片段只覆盖“怎么写”,不包含策略验证、资金管理、异常行情处理和 broker 兼容性测试。至少先在模拟盘跑 1–3 个月,并理解止损、点差、滑点和隔夜利息的影响。本站内容为教学用途,不构成投资建议。