English Русский Español Deutsch 日本語 Português
preview
MQL5交易策略自动化(第三十一部分):构建基于价格行为的三重推进谐波形态系统

MQL5交易策略自动化(第三十一部分):构建基于价格行为的三重推进谐波形态系统

MetaTrader 5 — 交易 |
31 3
Allan Munene Mutiiria
Allan Munene Mutiiria

引言

在前一篇文章(第三十部分)中,我们开发了一套AB=CD形态系统,使用的语言是MetaQuotes Language 5(MQL5)。该系统利用斐波那契比率检测看涨和看跌的AB=CD谐波形态,根据计算得出的入场、止损和止盈价位自动执行交易,并通过三角形和趋势线等图表对象进行可视化展示。 在本系列的第三十一部分中,我们将构建一个三重推进形态系统,通过拐点以及特定的斐波那契回撤和扩展来识别看涨和看跌的三重推进谐波形态。 该系统支持自定义止盈和止损选项以执行交易,并通过三角形、趋势线和标签清晰地呈现形态。 我们将探讨以下主题:

  1. 理解三重推进谐波形态框架
  2. 在MQL5中的实现
  3. 回测
  4. 结论

阅读完本文,您将拥有一套稳健且可自定义的三重推进谐波形态MQL5交易策略——让我们开始吧!


理解三重推进谐波形态框架

三重推进形态是一种由六个关键波段转折点(A、B、C、D、E和F)定义的谐波交易形态,分为看涨和看跌两种形式,通过三次连续的价格推进以及特定的斐波那契回撤和扩展来识别反转区域。 在看涨的三重推进形态中,结构呈"高—低—高—低—高—低"序列:A为波段高点,B为波段低点(第一次推进),C为波段高点,D为波段低点(第二次推进),E为波段高点,F为波段低点(第三次推进,低于D和B)。每次回撤(BC、DE)的幅度约为前一次推进幅度的0.618或0.786倍,每次推进(CD、EF)的幅度则扩展至前一次回撤幅度的1.13至1.618倍;看跌形态的高低点序列与此相反,F高于D和B。 以下是这些形态的示意图:

看跌谐波三重推进形态:

看跌谐波三重推进形态

看涨谐波三重推进形态:

看涨谐波三重推进形态

我们的方法包括:在指定的K线范围内检测这些波段拐点,根据斐波那契标准验证形态的各个波段,使用三角形和趋势线等图表对象将A-B-C-D-E-F结构可视化,并在 F 点执行交易,同时设置可自定义的止损位(基于斐波那契或固定值)和止盈位(0.382、0.618或拐点E),以把握预期的反转机会。 接下来让我们开始实现吧!


在MQL5中的实现

要在MQL5中创建程序,请打开MetaEditor,转到"导航器",找到"指标"文件夹,点击"新建"选项卡,然后按照提示创建文件。 创建完成后,在编程环境中,我们需要声明一些将在整个程序中使用的全局变量。

//+------------------------------------------------------------------+
//|                                          3 Drives Pattern EA.mq5 |
//|                        Copyright 2025, Forex Algo-Trader, Allan. |
//|                                 "https://t.me/Forex_Algo_Trader" |
//+------------------------------------------------------------------+
#property copyright "Forex Algo-Trader, Allan"
#property link "https://t.me/Forex_Algo_Trader"
#property version "1.00"
#property description "This EA trades based on 3 Drives Strategy"
#property strict

//--- Include the trading library for order functions
#include <Trade\Trade.mqh>   //--- Include Trade library
CTrade obj_Trade;            //--- Instantiate a obj_Trade object
//--- Enumeration for TP levels
enum ENUM_TAKE_PROFIT_LEVEL {
   TP1 = 1, // 0.382 Fibonacci Retracement
   TP2 = 2, // 0.618 Fibonacci Retracement
   TP3 = 3  // Pivot E Price
};
//--- Enumeration for SL types
enum ENUM_STOP_LOSS_TYPE {
   SL_FIBO = 1, // Fibonacci Extension
   SL_FIXED = 2 // Fixed Points
};
//--- Input parameters for user configuration
input int PivotLeft = 5;                              // Number of bars to the left for pivot check
input int PivotRight = 5;                             // Number of bars to the right for pivot check
input double Tolerance = 0.10;                        // Allowed deviation (10% of move)
input double LotSize = 0.01;                          // Lot size for new orders
input bool AllowTrading = true;                       // Enable or disable trading
input ENUM_TAKE_PROFIT_LEVEL TakeProfitLevel = TP2;   // Take Profit Level
input ENUM_STOP_LOSS_TYPE StopLossType = SL_FIBO;     // Stop Loss Type
input double SL_FiboExtension = 1.618;                // Fibonacci Extension for SL
input double SL_FixedPoints = 50;                     // Fixed Points for SL (in points)
//---------------------------------------------------------------------------
//--- 3 Drives pattern definition:
//
//--- Bullish 3 Drives:
//--- Pivots (A-B-C-D-E-F): A swing high, B swing low (drive 1), C swing high, D swing low (drive 2), E swing high, F swing low (drive 3).
//--- Retracements at 0.618, drives at 1.272 extensions.
//
//--- Bearish 3 Drives:
//--- Pivots (A-B-C-D-E-F): A swing low, B swing high (drive 1), C swing low, D swing high (drive 2), E swing low, F swing high (drive 3).
//--- Retracements at 0.618, drives at 1.272 extensions.
//---------------------------------------------------------------------------
//--- Structure for a pivot point
struct Pivot {
   datetime time; //--- Bar time of the pivot
   double price;  //--- Pivot price (High for swing high, low for swing low)
   bool isHigh;   //--- True if swing high; false if swing low
};
//--- Global dynamic array for storing pivots in chronological order
Pivot pivots[]; //--- Declare a dynamic array to hold identified pivot points
//--- Global variables to lock in a pattern (avoid trading on repaint)
int g_patternFormationBar = -1; //--- Bar index where the pattern was formed (-1 means none)
datetime g_lockedPatternA = 0;  //--- The key A pivot time for the locked pattern
//--- Global array to track traded patterns (using A.time as identifier)
datetime tradedPatterns[];

为实现三重推进形态奠定基础,我们首先引入"<Trade\Trade.mqh>"库,并创建名为"obj_Trade"的 CTrade 对象,用于管理执行买入和卖出订单等交易操作。 然后,我们定义枚举类型"ENUM_TAKE_PROFIT_LEVEL"(TP1对应0.382,TP2对应0.618,TP3对应拐点E的价格)和"ENUM_STOP_LOSS_TYPE"(SL_FIBO表示斐波那契扩展,SL_FIXED 表示固定点数),以便灵活设置交易,并设置以下输入参数:将"PivotLeft"和"PivotRight"均设为5根K线,用于拐点检测;"Tolerance"设为0.10,用于斐波那契比率的偏差容限;"LotSize"设为0.01;"AllowTrading"设为 true;"TakeProfitLevel"设为TP2;"StopLossType"设为 SL_FIBO;"SL_FiboExtension"设为1.618;"SL_FixedPoints"设为50。

接下来,我们定义包含"time"、"price"和"isHigh"字段的"Pivot"结构体,用于存储波段拐点,将"pivots"声明为动态数组,将全局变量"g_patternFormationBar"初始化为-1,将用于形态锁定的全局变量"g_lockedPatternA"初始化为0,并声明"tradedPatterns"数组,用于根据A点的时间跟踪已交易的形态。 这些设置构成了三重推进形态检测及相关交易的核心框架。 为了可视化,我们可以使用一些函数来绘制直线、标签和三角形。

//+------------------------------------------------------------------+
//| Helper: Draw a filled triangle                                   |
//+------------------------------------------------------------------+
void DrawTriangle(string name, datetime t1, double p1, datetime t2, double p2, datetime t3, double p3, color cl, int width, bool fill, bool back) {
   //--- Attempt to create a triangle object with three coordinate points
   if(ObjectCreate(0, name, OBJ_TRIANGLE, 0, t1, p1, t2, p2, t3, p3)) {
      //--- Set the triangle's color
      ObjectSetInteger(0, name, OBJPROP_COLOR, cl);
      //--- Set the triangle's line style to solid
      ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID);
      //--- Set the line width of the triangle
      ObjectSetInteger(0, name, OBJPROP_WIDTH, width);
      //--- Determine if the triangle should be filled
      ObjectSetInteger(0, name, OBJPROP_FILL, fill);
      //--- Set whether the object is drawn in the background
      ObjectSetInteger(0, name, OBJPROP_BACK, back);
   }
}
//+------------------------------------------------------------------+
//| Helper: Draw a trend line                                        |
//+------------------------------------------------------------------+
void DrawTrendLine(string name, datetime t1, double p1, datetime t2, double p2, color cl, int width, int style) {
   //--- Create a trend line object connecting two points
   if(ObjectCreate(0, name, OBJ_TREND, 0, t1, p1, t2, p2)) {
      //--- Set the trend line's color
      ObjectSetInteger(0, name, OBJPROP_COLOR, cl);
      //--- Set the trend line's style (solid, dotted, etc.)
      ObjectSetInteger(0, name, OBJPROP_STYLE, style);
      //--- Set the width of the trend line
      ObjectSetInteger(0, name, OBJPROP_WIDTH, width);
   }
}
//+------------------------------------------------------------------+
//| Helper: Draw a dotted trend line                                 |
//+------------------------------------------------------------------+
void DrawDottedLine(string name, datetime t1, double p, datetime t2, color lineColor) {
   //--- Create a horizontal trend line at a fixed price level with dotted style
   if(ObjectCreate(0, name, OBJ_TREND, 0, t1, p, t2, p)) {
      //--- Set the dotted line's color
      ObjectSetInteger(0, name, OBJPROP_COLOR, lineColor);
      //--- Set the line style to dotted
      ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_DOT);
      //--- Set the line width to 1
      ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
   }
}
//+------------------------------------------------------------------+
//| Helper: Draw anchored text label (for pivots)                    |
//| If isHigh is true, anchor at the bottom (label appears above);   |
//| if false, anchor at the top (label appears below).               |
//+------------------------------------------------------------------+
void DrawTextEx(string name, string text, datetime t, double p, color cl, int fontsize, bool isHigh) {
   //--- Create a text label object at the specified time and price
   if(ObjectCreate(0, name, OBJ_TEXT, 0, t, p)) {
      //--- Set the text of the label
      ObjectSetString(0, name, OBJPROP_TEXT, text);
      //--- Set the color of the text
      ObjectSetInteger(0, name, OBJPROP_COLOR, cl);
      //--- Set the font size for the text
      ObjectSetInteger(0, name, OBJPROP_FONTSIZE, fontsize);
      //--- Set the font type and style
      ObjectSetString(0, name, OBJPROP_FONT, "Arial Bold");
      //--- Anchor the text depending on whether it's a swing high or low
      if(isHigh)
         ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_BOTTOM);
      else
         ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_TOP);
      //--- Center-align the text
      ObjectSetInteger(0, name, OBJPROP_ALIGN, ALIGN_CENTER);
   }
}

接下来,我们将实现可视化函数,以图表形式清晰地展示三重推进谐波形态及其交易价位。 首先,我们编写"DrawTriangle"函数,使用 ObjectCreate 绘制一个由三个点的时间("t1"、"t2"、"t3")和价格("p1"、"p2"、"p3")定义的填充三角形(OBJ_TRIANGLE),并通过 OBJPROP_COLOR 指定颜色,通过"OBJPROP_STYLE"指定"STYLE_SOLID"样式,通过"OBJPROP_WIDTH"指定线宽,通过"OBJPROP_FILL"启用或禁用填充,以及通过"OBJPROP_BACK"指定置于背景或前景;这些属性均使用 ObjectSetInteger 函数设置。 接下来,我们将创建"DrawTrendLine"函数,该函数用于在两个点之间绘制一条趋势线("OBJ_TREND")。

接下来,我们实现"DrawDottedLine"函数,该函数会在指定价格处绘制一条水平点线(OBJ_TREND)。 最后,我们编写"DrawTextEx"函数,使用"ObjectCreate"在坐标("t"、"p")处创建文本标签(OBJ_TEXT),并使用 ObjectSetString 和"ObjectSetInteger"将"OBJPROP_TEXT"设为指定文本,设置"OBJPROP_COLOR"和"OBJPROP_FONTSIZE",并将"OBJPROP_FONT"设为"Arial Bold";根据"isHigh",通过"OBJPROP_ANCHOR"将标签锚定在波段高点上方或波段低点下方,并通过"OBJPROP_ALIGN"使其居中对齐。 现在,我们可以继续编写 OnTick 事件处理器,尝试识别后续可用于形态识别的拐点。 以下是我们为实现这一目标所采用的逻辑。

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick() {
   //--- Declare a static variable to store the time of the last processed bar
   static datetime lastBarTime = 0;
   //--- Get the time of the current confirmed bar
   datetime currentBarTime = iTime(_Symbol, _Period, 1);
   //--- If the current bar time is the same as the last processed, exit
   if(currentBarTime == lastBarTime)
      return;
   //--- Update the last processed bar time
   lastBarTime = currentBarTime;
 
   //--- Clear the pivot array for fresh analysis
   ArrayResize(pivots, 0);
   //--- Get the total number of bars available on the chart
   int barsCount = Bars(_Symbol, _Period);
   //--- Define the starting index for pivot detection (ensuring enough left bars)
   int start = PivotLeft;
   //--- Define the ending index for pivot detection (ensuring enough right bars)
   int end = barsCount - PivotRight;
 
   //--- Loop through bars from 'end-1' down to 'start' to find pivot points
   for(int i = end - 1; i >= start; i--) {
      //--- Assume current bar is both a potential swing high and swing low
      bool isPivotHigh = true;
      bool isPivotLow = true;
      //--- Get the high and low of the current bar
      double currentHigh = iHigh(_Symbol, _Period, i);
      double currentLow = iLow(_Symbol, _Period, i);
      //--- Loop through the window of bars around the current bar
      for(int j = i - PivotLeft; j <= i + PivotRight; j++) {
         //--- Skip if the index is out of bounds
         if(j < 0 || j >= barsCount)
            continue;
         //--- Skip comparing the bar with itself
         if(j == i)
            continue;
         //--- If any bar in the window has a higher high, it's not a swing high
         if(iHigh(_Symbol, _Period, j) > currentHigh)
            isPivotHigh = false;
         //--- If any bar in the window has a lower low, it's not a swing low
         if(iLow(_Symbol, _Period, j) < currentLow)
            isPivotLow = false;
      }
      //--- If the current bar qualifies as either a swing high or swing low
      if(isPivotHigh || isPivotLow) {
         //--- Create a new pivot structure
         Pivot p;
         //--- Set the pivot's time
         p.time = iTime(_Symbol, _Period, i);
         //--- Set the pivot's price depending on whether it is a high or low
         p.price = isPivotHigh ? currentHigh : currentLow;
         //--- Set the pivot type (true for swing high, false for swing low)
         p.isHigh = isPivotHigh;
         //--- Get the current size of the pivots array
         int size = ArraySize(pivots);
         //--- Increase the size of the pivots array by one
         ArrayResize(pivots, size + 1);
         //--- Add the new pivot to the array
         pivots[size] = p;
      }
   }
}

在此,我们实现了OnTick事件处理器的初始逻辑。 首先,我们声明静态变量"lastBarTime"并将其初始化为 0,用于跟踪最后处理的K线时间;然后将其与"currentBarTime"进行比较,后者通过iTime获取,使用当前交易品种、当前周期和偏移量1。若时间未变,则退出以避免重复处理;若检测到新K线,则更新"lastBarTime"。 然后,我们使用ArrayResize清空"pivots"数组,以确保进行全新的分析。

接下来,我们使用Bars获取K线总数,并设置拐点检测范围:将"start"设为"PivotLeft",将"end"设为K线总数减去"PivotRight",然后从"end - 1"到"start"遍历K线。 对于每根K线,我们先假设它既是波段高点("isPivotHigh"为 true),也是波段低点("isPivotLow"为 true),使用iHigh和iLow获取其最高价和最低价,再通过"iHigh"和"iLow"检查"PivotLeft"和"PivotRight"范围内的相邻K线,以验证拐点。若任一相邻K线的最高价更高或最低价更低,则分别判定当前K线不是波段高点或波段低点。 最后,如果该K线符合拐点条件,我们就创建一个"Pivot"结构体,使用"iTime"设置其"time"字段,根据"isPivotHigh"将"price"设为最高价或最低价,并设置"isHigh"标志;随后使用ArrayResize调整"pivots"数组的大小,将该结构体追加并存储到数组中。 打印各拐点结构体的内容时,我们会得到如下数据。

拐点数据

借助这些数据,我们可以提取拐点;如果拐点数量足够,就可以进行分析并检测形态。 以下是我们为实现这一目标所采用的逻辑。

//--- Determine the total number of pivots found
int pivotCount = ArraySize(pivots);
//--- If fewer than six pivots are found, the pattern cannot be formed
if(pivotCount < 6) {
   //--- Reset pattern lock variables
   g_patternFormationBar = -1;
   g_lockedPatternA = 0;
   //--- Exit the OnTick function
   return;
}

//--- Extract the last six pivots as A, B, C, D, E, F
Pivot A = pivots[pivotCount - 6];
Pivot B = pivots[pivotCount - 5];
Pivot C = pivots[pivotCount - 4];
Pivot D = pivots[pivotCount - 3];
Pivot E = pivots[pivotCount - 2];
Pivot F = pivots[pivotCount - 1];

//--- Initialize a flag to indicate if a valid 3 Drives pattern is found
bool patternFound = false;
//--- Initialize pattern type
string patternType = "";
double used_ext = 0.0;
//--- Define fib ratios
double retr_levels[] = {0.618, 0.786};
double ext_levels[] = {1.13, 1.272, 1.618};
//--- Check for the high-low-high-low-high-low (Bullish reversal) structure
if(A.isHigh && (!B.isHigh) && C.isHigh && (!D.isHigh) && E.isHigh && (!F.isHigh)) {
   //--- Calculate drive 1
   double drive1 = A.price - B.price;
   if(drive1 > 0) {
      //--- Retrace A
      double retraceA = C.price - B.price;
      bool valid_retrA = false;
      double used_retrA = 0.0;
      for(int k=0; k<ArraySize(retr_levels); k++) {
         double ideal_retraceA = retr_levels[k] * drive1;
         if(MathAbs(retraceA - ideal_retraceA) <= Tolerance * drive1) {
            valid_retrA = true;
            used_retrA = retr_levels[k];
            break;
         }
      }
      if(valid_retrA) {
         //--- Drive 2
         double drive2 = C.price - D.price;
         bool valid_drive2 = false;
         double used_ext2 = 0.0;
         for(int k=0; k<ArraySize(ext_levels); k++) {
            double ideal_drive2 = ext_levels[k] * retraceA;
            if(MathAbs(drive2 - ideal_drive2) <= Tolerance * retraceA) {
               valid_drive2 = true;
               used_ext2 = ext_levels[k];
               break;
            }
         }
         if(valid_drive2) {
            //--- Retrace B
            double retraceB = E.price - D.price;
            bool valid_retrB = false;
            double used_retrB = 0.0;
            for(int k=0; k<ArraySize(retr_levels); k++) {
               double ideal_retraceB = retr_levels[k] * drive2;
               if(MathAbs(retraceB - ideal_retraceB) <= Tolerance * drive2) {
                  valid_retrB = true;
                  used_retrB = retr_levels[k];
                  break;
               }
            }
            if(valid_retrB) {
               //--- Drive 3
               double drive3 = E.price - F.price;
               bool valid_drive3 = false;
               for(int k=0; k<ArraySize(ext_levels); k++) {
                  double ideal_drive3 = ext_levels[k] * retraceB;
                  if(MathAbs(drive3 - ideal_drive3) <= Tolerance * retraceB) {
                     valid_drive3 = true;
                     used_ext = ext_levels[k];
                     break;
                  }
               }
               if(valid_drive3 && F.price < D.price && D.price < B.price) {
                  patternFound = true;
                  patternType = "Bullish";
               }
            }
         }
      }
   }
}
//--- Check for the low-high-low-high-low-high (Bearish reversal) structure
if((!A.isHigh) && B.isHigh && (!C.isHigh) && D.isHigh && (!E.isHigh) && F.isHigh) {
   //--- Calculate drive 1
   double drive1 = B.price - A.price;
   if(drive1 > 0) {
      //--- Retrace A
      double retraceA = B.price - C.price;
      bool valid_retrA = false;
      double used_retrA = 0.0;
      for(int k=0; k<ArraySize(retr_levels); k++) {
         double ideal_retraceA = retr_levels[k] * drive1;
         if(MathAbs(retraceA - ideal_retraceA) <= Tolerance * drive1) {
            valid_retrA = true;
            used_retrA = retr_levels[k];
            break;
         }
      }
      if(valid_retrA) {
         //--- Drive 2
         double drive2 = D.price - C.price;
         bool valid_drive2 = false;
         double used_ext2 = 0.0;
         for(int k=0; k<ArraySize(ext_levels); k++) {
            double ideal_drive2 = ext_levels[k] * retraceA;
            if(MathAbs(drive2 - ideal_drive2) <= Tolerance * retraceA) {
               valid_drive2 = true;
               used_ext2 = ext_levels[k];
               break;
            }
         }
         if(valid_drive2) {
            //--- Retrace B
            double retraceB = D.price - E.price;
            bool valid_retrB = false;
            double used_retrB = 0.0;
            for(int k=0; k<ArraySize(retr_levels); k++) {
               double ideal_retraceB = retr_levels[k] * drive2;
               if(MathAbs(retraceB - ideal_retraceB) <= Tolerance * drive2) {
                  valid_retrB = true;
                  used_retrB = retr_levels[k];
                  break;
               }
            }
            if(valid_retrB) {
               //--- Drive 3
               double drive3 = F.price - E.price;
               bool valid_drive3 = false;
               for(int k=0; k<ArraySize(ext_levels); k++) {
                  double ideal_drive3 = ext_levels[k] * retraceB;
                  if(MathAbs(drive3 - ideal_drive3) <= Tolerance * retraceB) {
                     valid_drive3 = true;
                     used_ext = ext_levels[k];
                     break;
                  }
               }
               if(valid_drive3 && F.price > D.price && D.price > B.price) {
                  patternFound = true;
                  patternType = "Bearish";
               }
            }
         }
      }
   }
}

首先,我们通过"ArraySize(pivots)"获取拐点总数,并将其存储在"pivotCount"中。若找到的拐点少于6个,则将"g_patternFormationBar"和"g_lockedPatternA"分别重置为-1和0,然后退出当前处理,因为三重推进形态需要A、B、C、D、E和F这六个点。

然后,我们从"pivots"数组中提取最后六个拐点,分别赋给"A"(最早)、"B"、"C"、"D"、"E"和"F"(最新)。 接下来,对于看涨形态(A为高点、B为低点、C为高点、D为低点、E为高点、F为低点),我们计算推进1的幅度("A.price - B.price"),并在"Tolerance"允许的误差范围内依次验证:回撤A("C.price - B.price")是否为推进1的0.618或0.786倍,推进2("C.price - D.price")是否为回撤A的1.13、1.272或1.618倍,回撤B("E.price - D.price")是否为推进2的0.618或0.786倍,以及推进3("E.price - F.price")是否为回撤B的1.13、1.272或1.618倍,同时确保"F.price < D.price < B.price"。若验证通过,则将"patternFound"设为true,将"patternType"设为"Bullish",并存储所用的扩展比率("used_ext")。最后,对于看跌形态(A为低点、B为高点、C为低点、D为高点、E为低点、F为高点),我们对推进1("B.price - A.price")、回撤A、推进2、回撤B 和推进3进行类似的验证,同时确保"F.price > D.price > B.price";若验证通过,则将"patternFound"设为true,将"patternType"设为"Bearish"。 如果发现了该形态,我们就可以将其在图表上可视化。

//--- If a valid 3 Drives pattern is detected
if(patternFound) {
   //--- Print a message indicating the pattern type and detection time
   Print(patternType, " 3 Drives pattern detected at ", TimeToString(F.time, TIME_DATE|TIME_MINUTES|TIME_SECONDS));
 
   //--- Create a unique prefix for all graphical objects related to this pattern
   string signalPrefix = "3D_" + IntegerToString(A.time);
 
   //--- Choose triangle color based on the pattern type
   color triangleColor = (patternType=="Bullish") ? clrBlue : clrRed;
 
   //--- Draw the first triangle connecting pivots B, C, D
   DrawTriangle(signalPrefix+"_Triangle1", B.time, B.price, C.time, C.price, D.time, D.price,
                triangleColor, 2, true, true);
   //--- Draw the second triangle connecting pivots D, E, F
   DrawTriangle(signalPrefix+"_Triangle2", D.time, D.price, E.time, E.price, F.time, F.price,
                triangleColor, 2, true, true);
}

在此,我们开始在图表上可视化检测到的形态。 首先,如果检测到有效形态("patternFound"为 true),我们会使用Print记录检测结果,输出"patternType"("Bullish"或"Bearish",即看涨或看跌)以及拐点F的时间;该时间使用TimeToString格式化,包含日期、分钟和秒。 然后,我们通过将"3D_"与使用IntegerToString转换为字符串的"A.time"拼接,生成一个唯一的标识符"signalPrefix",以确保图表对象的命名具有唯一性。

接下来,我们将"triangleColor"设置为蓝色(代表看涨形态)或红色(代表看跌形态),以便在视觉上加以区分。 最后,我们调用两次"DrawTriangle"来可视化该形态:先绘制连接拐点B、C和D的BCD三角形,再绘制连接拐点D、E 和F的DEF三角形。两次调用分别使用"signalPrefix"加上后缀"_Triangle1"和"_Triangle2"作为名称,并传入相应拐点的时间和价格、"triangleColor"以及宽度2,同时将填充和背景显示标志设置为true。 我们得到以下结果。

三角形绘制完成

从图中可以看出,我们可以正确地绘制检测到的形态并将其可视化。 现在,我们需要继续绘制趋势线,完整勾勒出形态的边界,并为其添加标签,以便更轻松地识别各个价位。

//--- Draw boundary trend lines connecting the pivots for clarity
DrawTrendLine(signalPrefix+"_TL_AB", A.time, A.price, B.time, B.price, clrBlack, 2, STYLE_SOLID);
DrawTrendLine(signalPrefix+"_TL_BC", B.time, B.price, C.time, C.price, clrBlack, 2, STYLE_SOLID);
DrawTrendLine(signalPrefix+"_TL_CD", C.time, C.price, D.time, D.price, clrBlack, 2, STYLE_SOLID);
DrawTrendLine(signalPrefix+"_TL_DE", D.time, D.price, E.time, E.price, clrBlack, 2, STYLE_SOLID);
DrawTrendLine(signalPrefix+"_TL_EF", E.time, E.price, F.time, F.price, clrBlack, 2, STYLE_SOLID);

//--- Retrieve the symbol's point size to calculate offsets for text positioning
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
//--- Calculate an offset (15 points) for positioning text above or below pivots
double offset = 15 * point;

//--- Determine the Y coordinate for each pivot label based on its type
double textY_A = (A.isHigh ? A.price + offset : A.price - offset);
double textY_B = (B.isHigh ? B.price + offset : B.price - offset);
double textY_C = (C.isHigh ? C.price + offset : C.price - offset);
double textY_D = (D.isHigh ? D.price + offset : D.price - offset);
double textY_E = (E.isHigh ? E.price + offset : E.price - offset);
double textY_F = (F.isHigh ? F.price + offset : F.price - offset);

//--- Draw text labels for each pivot with appropriate anchoring
DrawTextEx(signalPrefix+"_Text_A", "A", A.time, textY_A, clrBlack, 11, A.isHigh);
DrawTextEx(signalPrefix+"_Text_B", "B", B.time, textY_B, clrBlack, 11, B.isHigh);
DrawTextEx(signalPrefix+"_Text_C", "C", C.time, textY_C, clrBlack, 11, C.isHigh);
DrawTextEx(signalPrefix+"_Text_D", "D", D.time, textY_D, clrBlack, 11, D.isHigh);
DrawTextEx(signalPrefix+"_Text_E", "E", E.time, textY_E, clrBlack, 11, E.isHigh);
DrawTextEx(signalPrefix+"_Text_F", "F", F.time, textY_F, clrBlack, 11, F.isHigh);

//--- Calculate the central label's time as the midpoint between pivots A and D
datetime centralTime = (A.time + D.time) / 2;
//--- Set the central label's price at pivot F's price
double centralPrice = F.price;
//--- Create the central text label indicating the pattern type
if(ObjectCreate(0, signalPrefix+"_Text_Center", OBJ_TEXT, 0, centralTime, centralPrice)) {
   ObjectSetString(0, signalPrefix+"_Text_Center", OBJPROP_TEXT,
      (patternType=="Bullish") ? "Bullish 3 Drives" : "Bearish 3 Drives");
   ObjectSetInteger(0, signalPrefix+"_Text_Center", OBJPROP_COLOR, clrBlack);
   ObjectSetInteger(0, signalPrefix+"_Text_Center", OBJPROP_FONTSIZE, 11);
   ObjectSetString(0, signalPrefix+"_Text_Center", OBJPROP_FONT, "Arial Bold");
   ObjectSetInteger(0, signalPrefix+"_Text_Center", OBJPROP_ALIGN, ALIGN_CENTER);
}

我们通过添加更详细的图表对象来清晰展示形态结构,从而进一步增强检测到的形态的可视化效果。 首先,我们使用"DrawTrendLine",配合唯一的"signalPrefix",根据拐点的时间和价格(例如"A.time"和"A.price")绘制五条实线趋势线,依次连接关键拐点,形成AB、BC、CD、DE和EF。通过将OBJPROP_COLOR设为"clrBlack"、"OBJPROP_WIDTH"设为 2、"OBJPROP_STYLE"设为"STYLE_SOLID",并使用ObjectSetInteger应用这些属性,勾勒出形态的各个波段。 然后,我们使用SymbolInfoDouble(_Symbol, SYMBOL_POINT)获取该交易品种每点对应的价格值,并计算用于标签定位的15点偏移量。根据各拐点是波段高点("isHigh"设为true)还是波段低点,在其价格上加上或减去该偏移量,确定Y坐标("textY_A"、"textY_B"、"textY_C"、"textY_D"、"textY_E"、"textY_F"),从而将标签放置在高点上方或低点下方。

接下来,我们使用"DrawTextEx"为拐点 A、B、C、D、E 和 F 创建文本标签,以"signalPrefix"和"_Text_A"等后缀组合命名,显示对应字母。标签位于各拐点的时间坐标和调整后的Y坐标处,颜色为"clrBlack",字号为11,并根据拐点的"isHigh"状态设置锚定方式。 最后,我们计算中央标签的位置:将"centralTime"设为"A.time"和"D.time"的中点,将"centralPrice"设为"F.price"。使用"ObjectCreate"创建名为"signalPrefix + '_Text_Center'"的文本对象,根据"patternType"将OBJPROP_TEXT设为"Bullish 3 Drives"(看涨三重推进)或"Bearish 3 Drives"(看跌三重推进),并将"OBJPROP_COLOR"设为"clrBlack"、"OBJPROP_FONTSIZE"设为11、OBJPROP_FONT设为"Arial Bold"、"OBJPROP_ALIGN"设为"ALIGN_CENTER",通过ObjectSetString和"ObjectSetInteger"应用这些设置。 这段逻辑确保在图表上全面、直观地呈现三重推进形态的结构和类型。 运行程序后,以下是生成的输出结果的可视化展示。

带有标签和边线的形态

从图中可以看出,我们已为形态添加了边线和标签,使其更加清晰直观。 接下来我们需要做的是确定该形态的交易点位。

//--- Define start and end times for drawing horizontal dotted lines for trade levels
datetime lineStart = F.time;
datetime lineEnd = F.time + PeriodSeconds(_Period)*2;

//--- Declare variables for entry price and take profit levels
double entryPriceLevel, TP1Level, TP2Level, TP3Level;
//--- Calculate pattern range (drive 3 length)
double patternRange = (patternType=="Bullish") ? (E.price - F.price) : (F.price - E.price);
//--- Calculate trade levels based on whether the pattern is Bullish or Bearish
if(patternType=="Bullish") { //--- Bullish → BUY signal
   //--- Set entry at the pattern tip (F price)
   entryPriceLevel = F.price;
   //--- Set TP3 at pivot E's price
   TP3Level = E.price;
   //--- Set TP1 at 0.382 fib retrace from F to E
   TP1Level = F.price + 0.382 * patternRange;
   //--- Set TP2 at 0.618 fib retrace from F to E
   TP2Level = F.price + 0.618 * patternRange;
} else { //--- Bearish → SELL signal
   //--- Set entry at the pattern tip (F price)
   entryPriceLevel = F.price;
   //--- Set TP3 at pivot E's price
   TP3Level = E.price;
   //--- Set TP1 at 0.382 fib retrace from F to E
   TP1Level = F.price - 0.382 * patternRange;
   //--- Set TP2 at 0.618 fib retrace from F to E
   TP2Level = F.price - 0.618 * patternRange;
}

//--- Draw dotted horizontal lines to represent the entry and TP levels
DrawDottedLine(signalPrefix+"_EntryLine", lineStart, entryPriceLevel, lineEnd, clrMagenta);
DrawDottedLine(signalPrefix+"_TP1Line", lineStart, TP1Level, lineEnd, clrForestGreen);
DrawDottedLine(signalPrefix+"_TP2Line", lineStart, TP2Level, lineEnd, clrGreen);
DrawDottedLine(signalPrefix+"_TP3Line", lineStart, TP3Level, lineEnd, clrDarkGreen);

//--- Define a label time coordinate positioned just to the right of the dotted lines
datetime labelTime = lineEnd + PeriodSeconds(_Period)/2;

//--- Construct the entry label text with the price
string entryLabel = (patternType=="Bullish") ? "BUY (" : "SELL (";
entryLabel += DoubleToString(entryPriceLevel, _Digits) + ")";
//--- Draw the entry label on the chart
DrawTextEx(signalPrefix+"_EntryLabel", entryLabel, labelTime, entryPriceLevel, clrMagenta, 11, true);

//--- Construct and draw the TP1 label
string tp1Label = "TP1 (" + DoubleToString(TP1Level, _Digits) + ")";
DrawTextEx(signalPrefix+"_TP1Label", tp1Label, labelTime, TP1Level, clrForestGreen, 11, true);

//--- Construct and draw the TP2 label
string tp2Label = "TP2 (" + DoubleToString(TP2Level, _Digits) + ")";
DrawTextEx(signalPrefix+"_TP2Label", tp2Label, labelTime, TP2Level, clrGreen, 11, true);

//--- Construct and draw the TP3 label
string tp3Label = "TP3 (" + DoubleToString(TP3Level, _Digits) + ")";
DrawTextEx(signalPrefix+"_TP3Label", tp3Label, labelTime, TP3Level, clrDarkGreen, 11, true);

为了定义检测到的形态的交易价位并将其可视化,我们将"lineStart"设为拐点F的时间("F.time"),再加上两个周期时长"PeriodSeconds(_Period) * 2"作为"lineEnd",然后声明用于交易计算的变量"entryPriceLevel"、"TP1Level"、"TP2Level"和"TP3Level"。 然后,我们将"patternRange"计算为第三次推进的长度(看涨形态为"E.price - F.price",看跌形态为"F.price - E.price");对于看涨形态,将"entryPriceLevel"设为"F.price"、"TP3Level"设为"E.price"、"TP1Level"设为"F.price + 0.382 * patternRange"、"TP2Level"设为"F.price + 0.618 * patternRange";对于看跌形态,将"entryPriceLevel"设为"F.price"、"TP3Level"设为"E.price"、"TP1Level"设为"F.price - 0.382 * patternRange"、"TP2Level"设为"F.price - 0.618 * patternRange"。

接下来,我们使用"DrawDottedLine"绘制四条水平点线:在"entryPriceLevel"处绘制洋红色入场线,在"TP1Level"处绘制森林绿色止盈线,在"TP2Level"处绘制绿色止盈线,在"TP3Level"处绘制深绿色止盈线,所有线段均从"lineStart"延伸至"lineEnd"。 最后,我们将"labelTime"设为"lineEnd"加上半个周期,使用经DoubleToString格式化的价格生成标签文本(例如,入场标签为"BUY (price)"或"SELL (price)",止盈标签为"TP1 (price)"等),并使用"DrawTextEx"在"labelTime"处绘制这些标签,采用对应的颜色和11号字体,将其锚定在相应价位上方。 编译后,我们得到了以下结果。

看跌形态:

看跌形态

看涨形态:

看涨形态

由图可见,我们已正确标注了交易价位。 接下来只需开立实际交易头寸。

//--- Retrieve the index of the current bar
int currentBarIndex = Bars(_Symbol, _Period) - 1;
//--- If no pattern has been previously locked, lock the current pattern formation
if(g_patternFormationBar == -1) {
   g_patternFormationBar = currentBarIndex;
   g_lockedPatternA = A.time;
   //--- Print a message that the pattern is detected and waiting for confirmation
   Print("Pattern detected on bar ", currentBarIndex, ". Waiting for confirmation on next bar.");
   return;
}
//--- If still on the same formation bar, the pattern is considered to be repainting
if(currentBarIndex == g_patternFormationBar) {
   Print("Pattern is repainting; still on locked formation bar ", currentBarIndex, ". No trade yet.");
   return;
}
//--- If we are on a new bar compared to the locked formation
if(currentBarIndex > g_patternFormationBar) {
   //--- Check if the locked pattern still corresponds to the same A pivot
   if(g_lockedPatternA == A.time) {
      Print("Confirmed pattern (locked on bar ", g_patternFormationBar, "). Opening trade on bar ", currentBarIndex, ".");
      //--- Update the pattern formation bar to the current bar
      g_patternFormationBar = currentBarIndex;
      //--- Only proceed with trading if allowed and if there is no existing position
      if(AllowTrading && !PositionSelect(_Symbol)) {
         //--- Check if this pattern has already been traded
         bool alreadyTraded = false;
         for(int k = 0; k < ArraySize(tradedPatterns); k++) {
            if(tradedPatterns[k] == A.time) {
               alreadyTraded = true;
               break;
            }
         }
         if(alreadyTraded) {
            Print("This pattern has already been traded. No new trade executed.");
            return;
         }
         double entryPriceTrade = 0, stopLoss = 0, takeProfit = 0;
         point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
         bool tradeResult = false;
         //--- Select TP level based on user input
         switch(TakeProfitLevel) {
            case TP1:
               takeProfit = TP1Level;
               break;
            case TP2:
               takeProfit = TP2Level;
               break;
            case TP3:
               takeProfit = TP3Level;
               break;
            default:
               takeProfit = TP2Level; // Fallback to TP2
         }
         //--- Calculate SL based on user-selected method
         if(patternType=="Bullish") { //--- BUY signal
            entryPriceTrade = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
            if(StopLossType == SL_FIBO) {
               double third_drive = E.price - F.price;
               stopLoss = F.price - (SL_FiboExtension - 1.0) * third_drive;
            } else { // SL_FIXED
               stopLoss = entryPriceTrade - SL_FixedPoints * point;
            }
            // Ensure SL is below entry for BUY
            if(stopLoss >= entryPriceTrade) {
               stopLoss = entryPriceTrade - 10 * point;
            }
            tradeResult = obj_Trade.Buy(LotSize, _Symbol, entryPriceTrade, stopLoss, takeProfit, "3 Drives Signal");
            if(tradeResult)
               Print("Buy order opened successfully.");
            else
               Print("Buy order failed: ", obj_Trade.ResultRetcodeDescription());
         }
         //--- For a Bearish pattern, execute a SELL trade
         else if(patternType=="Bearish") { //--- SELL signal
            entryPriceTrade = SymbolInfoDouble(_Symbol, SYMBOL_BID);
            if(StopLossType == SL_FIBO) {
               double third_drive = F.price - E.price;
               stopLoss = F.price + (SL_FiboExtension - 1.0) * third_drive;
            } else { // SL_FIXED
               stopLoss = entryPriceTrade + SL_FixedPoints * point;
            }
            // Ensure SL is above entry for SELL
            if(stopLoss <= entryPriceTrade) {
               stopLoss = entryPriceTrade + 10 * point;
            }
            tradeResult = obj_Trade.Sell(LotSize, _Symbol, entryPriceTrade, stopLoss, takeProfit, "3 Drives Signal");
            if(tradeResult)
               Print("Sell order opened successfully.");
            else
               Print("Sell order failed: ", obj_Trade.ResultRetcodeDescription());
         }
         //--- If trade was successful, mark the pattern as traded
         if(tradeResult) {
            int size = ArraySize(tradedPatterns);
            ArrayResize(tradedPatterns, size + 1);
            tradedPatterns[size] = A.time;
         }
      }
      else {
         //--- If a position is already open, do not execute a new trade
         Print("A position is already open for ", _Symbol, ". No new trade executed.");
      }
   }
   else {
      //--- If the pattern has changed, update the lock with the new formation bar and A pivot
      g_patternFormationBar = currentBarIndex;
      g_lockedPatternA = A.time;
      Print("Pattern has changed; updating lock on bar ", currentBarIndex, ". Waiting for confirmation.");
      return;
   }
}
else {
   //--- If no valid 3 Drives pattern is detected, reset the pattern lock variables
   g_patternFormationBar = -1;
   g_lockedPatternA = 0;
}

最后,我们通过管理检测到的形态的交易执行与确认流程,完成程序实现。 首先,我们使用"Bars(_Symbol, _Period) - 1"获取当前K线索引,并将其存储在"currentBarIndex"中。 然后,如果尚未锁定任何形态("g_patternFormationBar == -1"),我们将"g_patternFormationBar"设为"currentBarIndex",将A拐点的时间"A.time"存入"g_lockedPatternA",以此锁定该形态的关键拐点,使用"Print"记录检测结果并提示等待确认,然后退出。

接下来,如果仍处于形态形成时的K线("currentBarIndex == g_patternFormationBar"),我们会记录重绘情况并退出,以防止过早交易。 最后,如果已形成一根新K线("currentBarIndex > g_patternFormationBar"),且A拐点的时间与"g_lockedPatternA"匹配,我们就确认该形态、记录确认结果并更新"g_patternFormationBar",然后通过"AllowTrading"检查是否允许交易,并通过PositionSelect函数检查是否已有未平仓头寸;接着检查"tradedPatterns",确认尚未基于该形态进行过交易,根据"TakeProfitLevel"选择止盈价位("TP1Level"、"TP2Level"或"TP3Level"),使用"SL_FIBO"("F.price ± (SL_FiboExtension - 1.0) * third_drive")或"SL_FIXED"("entryPriceTrade ± SL_FixedPoints * point")计算止损价位,并确保方向有效,再以"LotSize"为交易手数、"3 Drives Signal"为交易注释,调用"obj_Trade.Buy"或"obj_Trade.Sell"执行买入或卖出操作,记录成功或失败,并在"tradedPatterns"中将该形态标记为已交易;如果不允许交易、存在未平仓头寸或该形态已交易过,则记录未执行交易;如果形态发生变化,则用新K线和新A拐点更新锁定变量,并等待确认;如果未找到任何形态,则重置全局变量。 编译后,我们得到了以下结果。

看跌信号:

看跌信号

看涨信号:

看涨信号

从图中可以看出,我们绘制了谐波形态,并能在形态得到确认后据此进行交易,从而实现了识别、绘制和交易该形态的目标。 接下来要做的就是对该程序进行回测,这将在下一节中进行说明。


回测

经过全面的回测,我们得到了以下结果。

回测图表:

图表

回测报告:

报告


结论

总而言之,我们使用MQL5开发了一套三重推进形态系统,利用价格行为,结合精确的斐波那契回撤和斐波那契扩展来识别看涨和看跌的三重推进谐波形态,通过可自定义的入场点、止损点和多级止盈点实现自动交易,并利用三角形和趋势线等图表对象将形态可视化。

免责声明:本文仅供教育参考之用。 交易存在重大财务风险,市场波动可能导致亏损。 在将该程序部署到真实市场之前,必须进行彻底的回测和谨慎的风险管理。

通过运用本文介绍的概念和实现方法,您可以调整这一三重推进形态系统,使其适合您的交易风格,从而优化您的算法交易策略。 祝您交易顺利!

本文由MetaQuotes Ltd译自英文
原文地址: https://www.mql5.com/en/articles/19449

附加的文件 |
最近评论 | 前往讨论 (3)
Pawlos6
Pawlos6 | 12 9月 2025 在 20:07
为什么图表上没有显示该EA?使用该EA时,优化参数应设为多少,最低交易金额是多少?
Allan Munene Mutiiria
Allan Munene Mutiiria | 12 9月 2025 在 23:58
Pawlos6 #:
为什么EA没有显示在图表上?要使用该EA,优化参数应设为多少,最低交易金额是多少?

您好。您可以在“优化”选项卡中进行优化。

Cyberdude
Cyberdude | 16 9月 2025 在 18:43
这位作者发表了大量文章,这本身就是第一个异常迹象。尽管如此,我还是选择相信他,仔细研究了其中几篇文章,亲自重现了这些策略,并将其与他的EA进行了对比。每篇文章,无一例外,都附带了一个半吊子的EA,其实际表现与描述不符。 截图也极具可疑之处:该EA总是在行情已经发展到更远的未来之后才检测到某种形态,随后才在过去的时间轴上绘制出该形态,并标注各种止盈位。我读过他的一些文章,全都是彻头彻尾的浪费时间。
基于图论的算法套利交易 基于图论的算法套利交易
本文将三角套利表述为在有向图中寻找环的问题,其中顶点代表货币,边代表货币对,并以汇率为权重。 盈利环:权重乘积 > 1。 我们的弗洛伊德-沃沙尔(Floyd–Warshall)算法和深度优先搜索(DFS)算法能够找到返回起点并获得利润的最优货币兑换路径。
MetaTrader 5 机器学习蓝图(第二部分):为机器学习标注金融数据 MetaTrader 5 机器学习蓝图(第二部分):为机器学习标注金融数据
在 MetaTrader 5 机器学习蓝图系列的第二部分中,您将了解为何简单的标签可能会使您的模型误入歧途,以及如何应用三重屏障和趋势扫描等高级技术来定义稳健且具有风险意识的目标。本实践指南包含大量实用的 Python 示例,旨在优化这些计算密集型技术,并指导您如何将嘈杂的市场数据转化为反映真实交易环境的可靠标签。
在 MQL5 中将动态模态分解应用于单变量时间序列 在 MQL5 中将动态模态分解应用于单变量时间序列
动态模态分解(DMD)是一种通常应用于高维数据集的技术。 在本文中,我们演示了 DMD 在单变量时间序列中的应用,展示了它既能刻画时间序列特征、又能进行预测的能力。 在此过程中,我们将研究 MQL5 中内置的动态模态分解实现,并特别关注新的矩阵方法 DynamicModeDecomposition()。
通过协整股票进行统计套利(第四部分):实时模型更新 通过协整股票进行统计套利(第四部分):实时模型更新
本文介绍了一条简单而全面的统计套利流水线,用于交易一篮子协整股票。 文中提供了一个功能齐全的 Python 脚本,用于下载和存储数据,以及进行相关性、协整和平稳性检验;还提供了用于更新数据库的 MetaTrader 5 服务程序实现示例及相应的智能交易系统(EA)。 本文记录了一些设计选择,供读者参考,并帮助读者复现实验。