在MQL5中实现交易策略自动化(第三十二部分):构建基于价格行为的五驱动谐波形态交易系统
引言
在前一篇文章(第三十一部分)中,我们开发了一套三驱动形态系统,使用 MetaQuotes Language 5(MQL5)编写,利用斐波那契比率检测看涨和看跌的三驱动谐波形态,通过可自定义的止损和止盈价位实现自动交易,并借助三角形和趋势线等图表对象进行可视化展示。在本文(第三十二部分)中,我们将创建一个五驱动形态系统,通过枢轴点和特定的斐波那契回撤与斐波那契扩展,识别看涨和看跌的五驱动谐波形态,提供灵活的入场、止损和多级止盈选项来执行交易,并借助三角形、趋势线和标签清晰呈现形态。本文将依次探讨以下主题:
完成本教程后,您将拥有一套稳健且可自定义的 MQL5 五驱动谐波形态交易策略——让我们开始吧!
理解五驱动谐波形态框架
五驱动(5-0)形态是一种由 A、B、C、D、E 和 F 六个关键摆动点定义的谐波交易形态,分为看涨和看跌两种形式,旨在通过一系列具有特定斐波那契回撤比率的驱动和回撤走势识别反转区域。在看涨五驱动形态中,结构呈高—低—高—低—高—低的序列,其中A为摆动高点,B为摆动低点,C为摆动高点,D为摆动低点,E为摆动高点,F为摆动低点(高于 B);AB和CD波段延伸至前一波段的1.13至1.618倍,BC和DE波段的延伸比率为1.618至2.24倍,且CD与AB等长,回撤比例为0.5;看跌形态的序列则相反,F低于B。以下是这些形态的可视化展示:
看跌五驱动谐波形态:

看涨谐波五驱动形态:

我们的方法包括:在指定的K线范围内检测这些波段高低点(swingpivots),根据斐波那契标准验证形态的各个波段,利用三角形和趋势线等图表对象直观呈现A-B-C-D-E-F结构,并在F点执行交易,同时设置可自定义的止损(基于斐波那契或固定值)和止盈价位(三分之一、三分之二或枢轴点E),以把握预期的反转机会。让我们开始实现吧!
在MQL5中的实现
要在MQL5中创建程序,请打开MetaEditor,在“导航器”中找到“指标”文件夹,点击工具栏上的“新建”按钮,然后按照向导提示创建文件。创建完成后,在编程环境中,我们需要声明一些将在整个程序中使用的全局变量。
//+------------------------------------------------------------------+ //| 5 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 5 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, // One-third of the move to E TP2 = 2, // Two-thirds of the move to E 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) //--------------------------------------------------------------------------- //--- 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代表从入场价到枢轴点E价格的三分之一处,TP2则代表三分之二处,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,用于锁定枢轴点A的时间;并声明数组"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绘制一个填充三角形(OBJ_TRIANGLE),其三个顶点由时间("t1"、"t2"、"t3")和价格("p1"、"p2"、"p3")确定。该函数通过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",然后遍历所选范围内的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 5 Drives pattern is found bool patternFound = false; //--- Initialize pattern type string patternType = ""; //--- 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 XA length double XA_length = C.price - B.price; //--- Calculate AB length double AB_length = C.price - D.price; //--- Check AB extension of XA if(AB_length >= 1.13 * XA_length && AB_length <= 1.618 * XA_length) { //--- Calculate BC length double BC_length = E.price - D.price; //--- Check BC extension of AB if(BC_length >= 1.618 * AB_length && BC_length <= 2.24 * AB_length) { //--- Calculate CD length double CD_length = E.price - F.price; //--- Check 50% retracement of BC double ideal_retrace = 0.5 * BC_length; if(MathAbs(CD_length - ideal_retrace) <= Tolerance * BC_length) { //--- Check reciprocal AB=CD if(MathAbs(CD_length - AB_length) <= Tolerance * AB_length) { //--- Additional conditions: higher high at E, D above B if(E.price > C.price && F.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 XA length double XA_length = B.price - C.price; //--- Calculate AB length double AB_length = D.price - C.price; //--- Check AB extension of XA if(AB_length >= 1.13 * XA_length && AB_length <= 1.618 * XA_length) { //--- Calculate BC length double BC_length = D.price - E.price; //--- Check BC extension of AB if(BC_length >= 1.618 * AB_length && BC_length <= 2.24 * AB_length) { //--- Calculate CD length double CD_length = F.price - E.price; //--- Check 50% retracement of BC double ideal_retrace = 0.5 * BC_length; if(MathAbs(CD_length - ideal_retrace) <= Tolerance * BC_length) { //--- Check reciprocal AB=CD if(MathAbs(CD_length - AB_length) <= Tolerance * AB_length) { //--- Additional conditions: lower low at E, D below B if(E.price < C.price && F.price < B.price) { patternFound = true; patternType = "Bearish"; } } } } } }
首先,我们使用"ArraySize(pivots)"获取枢轴点总数,并将其存储在"pivotCount"中。如果找到的枢轴点少于6个(由于五驱动形态需要A、B、C、D、E和F这6个点),则将"g_patternFormationBar"和"g_lockedPatternA"分别重置为-1和0,然后退出。
然后,我们从"pivots"数组中提取最后六个枢轴点,并分别标记为"A"(最早)、"B"、"C"、"D"、"E"和"F"(最晚)。接下来,对于看涨形态(A为高点、B为低点、C为高点、D为低点、E为高点、F为低点),我们计算XA波段长度("C.price - B.price")和AB波段长度("C.price - D.price"),确保AB延伸至XA的1.13至1.618倍;计算BC波段长度("E.price - D.price"),确保BC延伸至AB的1.618至2.24倍;再计算CD波段长度("E.price - F.price"),确保CD回撤幅度约为BC的0.5倍,且CD长度约等于AB;两项检查均允许“Tolerance”规定的偏差。同时,确认E高于C、F高于B,然后将"patternFound"设为true,并将"patternType"设为"Bullish"。最后,对于看跌形态(A为低点、B为高点、C为低点、D为高点、E为低点、F为高点),我们对XA("B.price - C.price")、AB("D.price - C.price")、BC("D.price - E.price")和CD("F.price - E.price")进行类似的验证,确保E低于C且F低于B,然后将"patternFound"设为true,并将"patternType"设为Bearish。如果检测到该形态,我们就可以在图表上将其可视化。
//--- If a valid 5 Drives pattern is detected if(patternFound) { //--- Print a message indicating the pattern type and detection time Print(patternType, " 5 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 = "5D_" + 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格式化,包含日期、分钟和秒。接下来,我们将"5D_"与通过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 5 Drives" : "Bearish 5 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)"获取该交易品种的报价点大小(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'"的文本对象,并使用OBJPROP_TEXT属性,根据"patternType"将文本设为"Bullish 5 Drives"或"Bearish 5 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, tradeDiff; //--- Calculate trade levels based on whether the pattern is Bullish or Bearish if(patternType=="Bullish") { //--- Bullish → BUY signal //--- Use the current ASK price as the entry entryPriceLevel = SymbolInfoDouble(_Symbol, SYMBOL_ASK); //--- Set TP3 at pivot E's price TP3Level = E.price; //--- Calculate the total distance to be covered by the trade tradeDiff = TP3Level - entryPriceLevel; //--- Set TP1 at one-third of the total move TP1Level = entryPriceLevel + tradeDiff/3; //--- Set TP2 at two-thirds of the total move TP2Level = entryPriceLevel + 2*tradeDiff/3; } else { //--- Bearish → SELL signal //--- Use the current BID price as the entry entryPriceLevel = SymbolInfoDouble(_Symbol, SYMBOL_BID); //--- Set TP3 at pivot E's price TP3Level = E.price; //--- Calculate the total distance to be covered by the trade tradeDiff = entryPriceLevel - TP3Level; //--- Set TP1 at one-third of the total move TP1Level = entryPriceLevel - tradeDiff/3; //--- Set TP2 at two-thirds of the total move TP2Level = entryPriceLevel - 2*tradeDiff/3; } //--- 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"和"tradeDiff",用于交易计算。然后,对于看涨形态("patternType == 'Bullish'"),我们使用"SymbolInfoDouble"将"entryPriceLevel"设置为当前卖价,将"TP3Level"设置为E枢轴点的价格,将"tradeDiff"计算为"TP3Level - entryPriceLevel",再将"tradeDiff"的三分之一和三分之二分别加到"entryPriceLevel"上,得到"TP1Level"和"TP2Level";对于看跌形态,我们使用买价,将"TP3Level"设置为E枢轴点的价格,将"tradeDiff"计算为"entryPriceLevel - TP3Level",再从"entryPriceLevel"中分别减去"tradeDiff"的三分之一和三分之二,得到"TP1Level"和"TP2Level"。
接下来,我们使用"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, "5 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, "5 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 5 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")计算止损,并确保止损有效(买入时低于入场价,卖出时高于入场价,必要时将止损设在入场价下方或上方10个报价点处),再使用"obj_Trade.Buy"或"obj_Trade.Sell"执行买入或卖出,以"LotSize"指定交易手数,并使用"5 Drives Signal"作为交易注释,记录成功或失败,最后在"tradedPatterns"中将该形态标记为已交易。如果不允许交易、存在未平仓头寸或该形态已交易过,则记录不执行交易;如果形态发生变化,则更新锁定信息并等待;如果未找到形态,则重置全局变量。编译后,我们得到了以下结果。
看跌信号:

看涨信号:

从图中可以看出,我们绘制了谐波形态,并能在形态得到确认后据此进行交易,从而实现了识别、绘制和交易该形态的目标。剩下的工作就是对程序进行回测,详见下一节。
回测
经过全面的回测,我们得到了以下结果。
回测图表:

回测报告:

结论
总而言之,我们用 MQL5 开发了一套五驱动形态(5-0)系统,利用价格行为识别符合精确斐波那契比率的看涨和看跌五驱动形态(谐波形态),通过可自定义的入场、止损和多级止盈点位实现自动交易,并利用三角形和趋势线等图表对象将形态可视化。
免责声明:本文仅供教育参考之用。交易存在重大财务风险,市场波动可能导致亏损。在将该程序部署到实盘交易之前,充分的回测和审慎的风险管理至关重要。
通过运用本文介绍的概念和实现方法,您可以根据自己的交易风格调整这一五驱动形态系统,从而改进您的算法交易策略。祝您交易顺利!
本文由MetaQuotes Ltd译自英文
原文地址: https://www.mql5.com/en/articles/19463
注意: MetaQuotes Ltd.将保留所有关于这些材料的权利。全部或部分复制或者转载这些材料将被禁止。
本文由网站的一位用户撰写,反映了他们的个人观点。MetaQuotes Ltd 不对所提供信息的准确性负责,也不对因使用所述解决方案、策略或建议而产生的任何后果负责。