Automatização de estratégias de trading em MQL5 (Parte 31): Criação de um sistema de reconhecimento do padrão harmônico "3 Drives" com base na ação do preço (Price Action)
Introdução
No artigo anterior (Parte 30), desenvolvemos um sistema de reconhecimento do padrão AB=CD em MetaQuotes Language 5 (MQL5). Implementamos a identificação de padrões harmônicos AB=CD de alta e de baixa com base em níveis precisos de Fibonacci, automatizamos as operações com base em níveis calculados de entrada, Stop Loss e Take Profit e adicionamos a representação visual dos padrões por meio de objetos gráficos, como triângulos e linhas de tendência. Na Parte 31, desenvolveremos um sistema de reconhecimento do padrão "3 Drives", capaz de identificar padrões harmônicos de alta e de baixa utilizando pontos de swing e níveis específicos de retração e extensão de Fibonacci. O sistema abrirá operações com parâmetros configuráveis de Take Profit e Stop Loss. Também incluiremos triângulos, linhas de tendência e rótulos para facilitar a identificação visual dos padrões no gráfico. Neste artigo, abordaremos os seguintes tópicos:
Ao final, você terá uma estratégia estável de trading em MQL5, baseada no padrão harmônico "3 Drives" e pronta para ser personalizada. Vamos à implementação!
Estrutura do padrão harmônico "3 Drives"
O padrão "3 Drives" é uma formação harmônica composta por seis pontos de swing principais, identificados pelas letras A, B, C, D, E e F, que pode apresentar uma configuração de alta ou de baixa. Esse padrão permite identificar possíveis zonas de reversão a partir de uma sequência de três impulsos consecutivos de preço, definidos por retrações e extensões específicas de Fibonacci. Na configuração de alta, o padrão apresenta a sequência "topo-fundo-topo-fundo-topo-fundo", em que A corresponde a um topo de swing, B a um fundo de swing (primeiro impulso), C a um topo de swing, D a um fundo de swing (segundo impulso), E a um topo de swing e F a um fundo de swing (terceiro impulso, abaixo de D e B). Cada retração (BC e DE) corresponde a aproximadamente 0,618 ou 0,786 do impulso anterior, enquanto os impulsos seguintes (CD e EF) apresentam extensões de 1,13 a 1,618 vezes a amplitude da retração anterior. Na configuração de baixa, essa sequência se inverte, com o ponto F situado acima dos pontos D e B. Veja a representação visual dos padrões:
Padrão harmônico "3 Drives" de baixa:

Padrão harmônico "3 Drives" de alta:

Nossa abordagem consiste em identificar esses pontos de swing em um intervalo definido de barras, verificar as ondas do padrão com base nos critérios de Fibonacci, representar visualmente a estrutura A-B-C-D-E-F por meio de objetos gráficos, como triângulos e linhas de tendência, e abrir operações no ponto F com Stop Loss configurável (baseado em Fibonacci ou em uma distância fixa) e níveis de Take Profit ajustáveis (0,382, 0,618 ou o nível de preço do ponto de swing E), buscando aproveitar a reversão esperada do preço. Vamos à implementação!
Implementação em MQL5
Para criar o programa em MQL5, abra o MetaEditor, acesse o Navegador, localize a pasta "Indicadores" (Indicators), clique em "Novo" (New) e siga as instruções para criar o arquivo. Depois disso, precisaremos declarar algumas variáveis globais no ambiente de desenvolvimento, que serão utilizadas em todo o programa.
//+------------------------------------------------------------------+ //| 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[];
Para estabelecer a base do sistema de reconhecimento do padrão "3 Drives", começaremos incluindo a biblioteca "<Trade\Trade.mqh>" e criando uma instância da classe CTrade chamada "obj_Trade", responsável por gerenciar operações de trading, como a abertura de posições de compra e venda. Em seguida, definiremos as enumerações "ENUM_TAKE_PROFIT_LEVEL" (TP1 para 0,382, TP2 para 0,618 e TP3 para o preço do ponto de swing E) e "ENUM_STOP_LOSS_TYPE" (SL_FIBO para a extensão de Fibonacci e SL_FIXED para uma distância fixa em pontos), permitindo configurar os parâmetros das operações. Também definiremos os parâmetros de entrada: "PivotLeft" e "PivotRight" terão o valor de 5 barras para identificar os pontos de swing; "Tolerance" será definido como 0,10 para estabelecer a margem de tolerância em relação aos níveis de Fibonacci; "LotSize" será 0,01; "AllowTrading" será true; "TakeProfitLevel" será TP2; "StopLossType" será SL_FIBO; "SL_FiboExtension" será 1,618; e "SL_FixedPoints" será 50.
Na sequência, definiremos a estrutura "Pivot", com os campos "time", "price" e "isHigh", para armazenar os pontos de swing do preço. Declararemos "pivots" como um array dinâmico e inicializaremos as variáveis globais "g_patternFormationBar" com -1 e "g_lockedPatternA" com 0 para manter o registro do padrão identificado, além de declarar "tradedPatterns" como um array destinado a rastrear os padrões já negociados, utilizando a marca de tempo do ponto A como referência. Esses elementos constituem a base para identificar o padrão "3 Drives" e executar operações a partir dele. Para a representação visual, podemos utilizar funções que desenham linhas, rótulos e triângulos no gráfico.
//+------------------------------------------------------------------+ //| 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); } }
Agora, implementaremos as funções de visualização para representar com clareza o padrão harmônico "3 Drives" e seus níveis de negociação. Primeiro, criaremos a função "DrawTriangle", que utiliza ObjectCreate para desenhar um triângulo preenchido (OBJ_TRIANGLE), definido por três pontos com coordenadas de tempo ("t1", "t2", "t3") e preço ("p1", "p2", "p3"). Com ObjectSetInteger, configuraremos "OBJPROP_COLOR" com a cor especificada, "OBJPROP_STYLE" como STYLE_SOLID, "OBJPROP_WIDTH" com a largura definida, "OBJPROP_FILL" para ativar ou desativar o preenchimento e "OBJPROP_BACK" para posicionar o objeto no plano de fundo ou em primeiro plano. Em seguida, implementaremos a função "DrawTrendLine", que cria uma linha de tendência (OBJ_TREND) entre dois pontos.
Em seguida, implementaremos a função "DrawDottedLine", que desenha uma linha horizontal pontilhada (OBJ_TREND) no nível de preço especificado. Por fim, desenvolveremos a função "DrawTextEx", que cria um rótulo de texto (OBJ_TEXT) nas coordenadas ("t", "p") utilizando ObjectCreate. Configuraremos "OBJPROP_TEXT" com o texto especificado, além de "OBJPROP_COLOR", "OBJPROP_FONTSIZE" e "OBJPROP_FONT", definindo a fonte como "Arial Bold", por meio de ObjectSetString e ObjectSetInteger. Com base em "isHigh", utilizaremos "OBJPROP_ANCHOR" para posicionar o texto acima dos topos de swing ou abaixo dos fundos de swing e "OBJPROP_ALIGN" para centralizá-lo. Agora, passaremos ao manipulador de eventos OnTick para identificar os pontos de swing que serão utilizados posteriormente no reconhecimento dos padrões. Veja a lógica que adotaremos para isso.
//+------------------------------------------------------------------+ //| 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; } } }
Neste bloco, implementaremos a parte inicial da lógica do manipulador OnTick. Primeiro, declararemos uma variável estática "lastBarTime", inicializada com 0, para acompanhar a última barra processada e comparar sua marca de tempo com "currentBarTime", obtida pela função iTime com deslocamento 1 para o símbolo e período atuais. Para evitar processamento redundante, interromperemos o processamento da chamada atual de OnTick caso a marca de tempo não tenha mudado. Quando uma nova barra for detectada, atualizaremos "lastBarTime". Em seguida, limparemos o array "pivots" utilizando ArrayResize para iniciar uma nova análise.
Depois, obteremos o número total de barras com Bars e definiremos o intervalo de busca dos pontos de swing, atribuindo a "start" o valor de "PivotLeft" e a "end" o número total de barras menos "PivotRight". Percorreremos as barras de "end - 1" até "start". Para cada barra, inicialmente consideraremos verdadeiras as condições de topo de swing ("isPivotHigh" igual a true) e fundo de swing ("isPivotLow" igual a true), obtendo seus preços máximo e mínimo por meio de iHigh e iLow. Em seguida, verificaremos se a barra corresponde a um ponto de swing, comparando-a com as barras vizinhas dentro dos intervalos definidos por "PivotLeft" e "PivotRight", utilizando iHigh e iLow. A condição de topo será invalidada se alguma barra vizinha apresentar uma máxima superior, enquanto a condição de fundo será invalidada se alguma delas apresentar uma mínima inferior. Por fim, se a barra atender aos critérios de identificação de um ponto de swing, criaremos uma estrutura "Pivot", atribuindo ao campo "time" a marca de tempo obtida por iTime, ao campo "price" o preço máximo ou mínimo conforme "isPivotHigh", e definindo o sinalizador "isHigh". Depois, ampliaremos o array "pivots" com ArrayResize e armazenaremos a estrutura. Ao exibir os dados das estruturas dos pontos de swing, obteremos o seguinte array de dados.

Com esses dados, podemos identificar os pontos de swing e, quando houver pontos suficientes, analisar a estrutura de preços para detectar possíveis padrões. A seguir, apresentamos a lógica utilizada na busca pelo padrão.
//--- 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"; } } } } } }
Primeiro, obteremos o número total de pontos de swing com "ArraySize(pivots)" e armazenaremos esse valor em "pivotCount". Se forem identificados menos de 6 pontos, encerraremos o processamento e redefiniremos "g_patternFormationBar" como -1 e "g_lockedPatternA" como 0, pois o padrão "3 Drives" exige os seis pontos A, B, C, D, E e F.
Em seguida, extrairemos os seis pontos de swing mais recentes do array "pivots" e os atribuiremos a "A" (o ponto mais antigo), "B", "C", "D", "E" e "F" (o ponto mais recente). Para o padrão de alta (topo A, fundo B, topo C, fundo D, topo E e fundo F), calcularemos o movimento 1 ("A.price - B.price") e verificaremos se a retração A ("C.price - B.price") corresponde a 0,618 ou 0,786 do movimento 1, respeitando a margem definida por "Tolerance". Em seguida, verificaremos se o movimento 2 ("C.price - D.price") corresponde a uma extensão de 1,13, 1,272 ou 1,618 da retração A, se a retração B ("E.price - D.price") corresponde a 0,618 ou 0,786 do movimento 2 e se o movimento 3 ("E.price - F.price") corresponde a uma extensão de 1,13, 1,272 ou 1,618 da retração B. Também verificaremos se a condição "F.price < D.price < B.price" é satisfeita. Se todas as condições forem atendidas, definiremos "patternFound" como true e "patternType" como "Bullish". Armazenaremos também a extensão utilizada em "used_ext". Para o padrão de baixa (fundo A, topo B, fundo C, topo D, fundo E e topo F), aplicaremos verificações equivalentes ao movimento 1 ("B.price - A.price"), à retração A, ao movimento 2, à retração B e ao movimento 3. Também verificaremos se a condição "F.price > D.price > B.price" é satisfeita. Se o padrão for confirmado, definiremos "patternFound" como true e "patternType" como "Bearish". Após identificar um padrão válido, poderemos representá-lo visualmente no gráfico.
//--- 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); }
Agora, vamos representar o padrão identificado no gráfico. Primeiro, quando um padrão válido for detectado ("patternFound" igual a true), registraremos sua identificação no log por meio da função Print, incluindo o valor de "patternType" ("Bullish" ou "Bearish") e a marca de tempo do ponto de swing F, formatada com TimeToString para incluir a data, os minutos e os segundos. Em seguida, criaremos um identificador exclusivo chamado "signalPrefix", concatenando "3D_" com o valor de "A.time", convertido em string pela função IntegerToString. Isso permitirá atribuir nomes específicos aos objetos gráficos de cada padrão.
Depois, definiremos "triangleColor" como azul para os padrões de alta ou vermelho para os padrões de baixa, facilitando sua diferenciação visual. Por fim, chamaremos a função "DrawTriangle" duas vezes para representar o padrão: primeiro, desenharemos o triângulo BCD, conectando os pontos de swing B, C e D; depois, desenharemos o triângulo DEF, conectando os pontos D, E e F. Utilizaremos "signalPrefix" com os sufixos "_Triangle1" e "_Triangle2", as respectivas coordenadas de tempo e preço dos pontos de swing, a cor definida em "triangleColor" e a largura 2. Também ativaremos o preenchimento e a exibição em segundo plano, definindo os respectivos sinalizadores como true. O resultado será o seguinte.

Na imagem, podemos observar que o padrão identificado foi representado corretamente no gráfico. Agora, adicionaremos linhas de tendência para completar o contorno do padrão, além de um rótulo que facilitará a identificação dos níveis.
//--- 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); }
Em seguida, aprimoraremos a visualização dos padrões identificados, adicionando objetos gráficos detalhados para exibir com clareza a sua estrutura. Primeiro, desenharemos cinco linhas de tendência contínuas com a função "DrawTrendLine", usando um "signalPrefix" exclusivo para conectar os principais pontos de swing: AB, BC, CD, DE e EF. Cada linha utilizará os valores de tempo e preço dos respectivos pontos de swing, como "A.time" e "A.price". Para exibir o contorno do padrão, configuraremos "OBJPROP_COLOR" como "clrBlack", "OBJPROP_WIDTH" como 2 e "OBJPROP_STYLE" como "STYLE_SOLID" por meio de ObjectSetInteger. Em seguida, obteremos o tamanho do ponto do símbolo com a função SymbolInfoDouble(_Symbol, SYMBOL_POINT) e calcularemos um deslocamento de 15 pontos para posicionar os rótulos. Depois, definiremos as coordenadas Y ("textY_A", "textY_B", "textY_C", "textY_D", "textY_E" e "textY_F"), somando ou subtraindo esse deslocamento conforme cada ponto de swing seja um topo ("isHigh" igual a true) ou um fundo, de modo que os rótulos fiquem acima dos topos e abaixo dos fundos.
Na sequência, utilizaremos "DrawTextEx" para criar rótulos de texto para os pontos de swing A, B, C, D, E e F, usando "signalPrefix" com sufixos como "_Text_A", exibindo a letra correspondente, posicionada no instante do respectivo ponto de swing e ajustada na coordenada Y. Para esses rótulos, usaremos "clrBlack", tamanho de fonte 11 e o valor do sinalizador "isHigh" do ponto de swing para definir a ancoragem. Por fim, calcularemos a posição central do rótulo em "centralTime" como o ponto médio entre "A.time" e "D.time", e em "centralPrice" como "F.price", criando um objeto de texto com ObjectCreate e o nome "signalPrefix + '_Text_Center'". Configuraremos "OBJPROP_TEXT" como "Bullish 3 Drives" ou "Bearish 3 Drives", de acordo com "patternType", e ajustaremos "OBJPROP_COLOR" para "clrBlack", "OBJPROP_FONTSIZE" para 11, "OBJPROP_FONT" para "Arial Bold" e "OBJPROP_ALIGN" para "ALIGN_CENTER" por meio de ObjectSetString e ObjectSetInteger. Essa lógica garante uma representação visual completa da estrutura e do tipo do padrão "3 Drives" no gráfico. Após executar o programa, obteremos a seguinte visualização.

Na imagem, podemos ver que adicionamos as linhas de contorno e os rótulos ao padrão, tornando sua visualização mais clara e informativa. O próximo passo é definir os níveis de negociação do padrão.
//--- 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);
Para definir e representar visualmente os níveis de negociação do padrão identificado, definiremos "lineStart" com a marca de tempo do ponto de swing F ("F.time") e "lineEnd" com dois períodos à frente, usando "PeriodSeconds(_Period) * 2". Declararemos as variáveis "entryPriceLevel", "TP1Level", "TP2Level" e "TP3Level" para os cálculos das operações. Em seguida, calcularemos "patternRange" como a amplitude do terceiro movimento ("E.price - F.price" no padrão de alta e "F.price - E.price" no padrão de baixa). Para o padrão de alta, definiremos "entryPriceLevel" como "F.price", "TP3Level" como "E.price", "TP1Level" como "F.price + 0.382 * patternRange" e "TP2Level" como "F.price + 0.618 * patternRange". Para o padrão de baixa, definiremos "entryPriceLevel" como "F.price", "TP3Level" como "E.price", "TP1Level" como "F.price - 0.382 * patternRange" e "TP2Level" como "F.price - 0.618 * patternRange".
Em seguida, utilizaremos a função "DrawDottedLine" para desenhar quatro linhas horizontais pontilhadas entre "lineStart" e "lineEnd": uma linha de entrada no nível "entryPriceLevel", na cor magenta, e três linhas de Take Profit nos níveis "TP1Level" (verde-floresta escuro), "TP2Level" (verde) e "TP3Level" (verde-escuro). Por fim, definiremos "labelTime" como "lineEnd" mais meio período e criaremos rótulos de texto com os preços formatados pela função DoubleToString, como "BUY (price)" ou "SELL (price)" para a entrada, "TP1 (price)" e assim por diante. Utilizaremos "DrawTextEx" para posicionar esses rótulos em "labelTime", com as respectivas cores, tamanho de fonte 11 e ancoragem acima dos níveis de preço. Após compilar o programa, obteremos o seguinte resultado.
Padrão de baixa:

Padrão de alta:

Nas imagens, podemos observar que os níveis de negociação foram representados corretamente no gráfico. Agora, resta implementar a abertura das posições.
//--- 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; }
Na etapa final, implementaremos a confirmação do padrão e a abertura das operações. Primeiro, obteremos o índice da barra atual por meio da expressão "Bars(_Symbol, _Period) - 1" e armazenaremos o resultado em "currentBarIndex". Em seguida, se não houver nenhum padrão armazenado ("g_patternFormationBar == -1"), atribuiremos "currentBarIndex" a "g_patternFormationBar", armazenaremos a marca de tempo do ponto de swing A ("A.time") em "g_lockedPatternA" e registraremos a identificação do padrão no log com Print, indicando que estamos aguardando sua confirmação. Depois, encerraremos o processamento da chamada atual de OnTick.
Se o padrão ainda estiver na barra em que foi identificado ("currentBarIndex == g_patternFormationBar"), consideraremos que sua formação ainda está sujeita a alterações (repainting) e interromperemos o processamento para evitar a abertura prematura de operações. Por fim, quando uma nova barra se formar ("currentBarIndex > g_patternFormationBar") e o ponto de swing A corresponder ao valor armazenado em "g_lockedPatternA", confirmaremos o padrão, registraremos a confirmação no log, atualizaremos "g_patternFormationBar" e verificaremos se as operações estão habilitadas por "AllowTrading" e se não há posições abertas, utilizando a função PositionSelect. Também consultaremos o array "tradedPatterns" para verificar se o padrão já foi negociado. Em seguida, selecionaremos o nível de Take Profit ("TP1Level", "TP2Level" ou "TP3Level") de acordo com "TakeProfitLevel" e calcularemos o Stop Loss conforme a opção escolhida: "SL_FIBO", utilizando a expressão "F.price ± (SL_FiboExtension - 1.0) * third_drive", ou "SL_FIXED", utilizando "entryPriceTrade ± SL_FixedPoints * point". Após verificar se o nível de Stop Loss é válido, abriremos uma posição de compra ou venda com "obj_Trade.Buy" ou "obj_Trade.Sell", utilizando "LotSize" e o comentário "3 Drives Signal". Registraremos o sucesso ou a falha da operação no log e adicionaremos o padrão ao array "tradedPatterns" para indicar que já foi negociado. Se as operações estiverem desabilitadas, já existir uma posição aberta ou o padrão tiver sido negociado anteriormente, registraremos no log uma mensagem informando que nenhuma nova operação foi aberta. Se o padrão sofrer alterações, atualizaremos os dados armazenados e aguardaremos uma nova confirmação. Caso nenhum padrão seja identificado, redefiniremos as variáveis globais. Após compilar o programa, obteremos o seguinte resultado.
Sinal de baixa:

Sinal de alta:

Na imagem, podemos observar que o padrão é representado corretamente no gráfico e pode ser utilizado para abrir operações após sua confirmação. Com isso, atingimos o objetivo de identificar o padrão, representá-lo visualmente e executar operações com base nele. Resta testar o programa com dados históricos, conforme veremos na próxima seção.
Testes com dados históricos
Após realizar testes detalhados com dados históricos, obtivemos os seguintes resultados.
Gráfico dos testes com dados históricos:

Relatório dos testes com dados históricos:

Conclusão
Em conclusão, desenvolvemos um sistema de reconhecimento do padrão "3 Drives" em MQL5. O sistema utiliza os movimentos do preço para identificar padrões harmônicos "3 Drives" de alta e de baixa, com níveis precisos de retração e extensão de Fibonacci, automatiza as operações com base em níveis calculados de entrada, Stop Loss e múltiplos níveis de Take Profit, além de representar visualmente os padrões por meio de objetos gráficos, como triângulos e linhas de tendência.
Aviso de isenção de responsabilidade: O conteúdo deste artigo destina-se exclusivamente a fins educacionais. O trading envolve riscos financeiros significativos, e a volatilidade do mercado pode resultar em perdas. A realização de testes rigorosos com dados históricos e a adoção de práticas adequadas de gestão de riscos são fundamentais antes de utilizar este programa em condições reais de mercado.
Com os conceitos e métodos de implementação apresentados, você poderá adaptar o sistema de reconhecimento do padrão "3 Drives" ao seu estilo de negociação e aprimorar suas estratégias algorítmicas. Bons trades!
Traduzido do Inglês pela MetaQuotes Ltd.
Artigo original: https://www.mql5.com/en/articles/19449
Aviso: Todos os direitos sobre esses materiais pertencem à MetaQuotes Ltd. É proibida a reimpressão total ou parcial.
Esse artigo foi escrito por um usuário do site e reflete seu ponto de vista pessoal. A MetaQuotes Ltd. não se responsabiliza pela precisão das informações apresentadas nem pelas possíveis consequências decorrentes do uso das soluções, estratégias ou recomendações descritas.
Por que o EA não aparece no gráfico e qual deve ser o número de otimização para usar o EA e o valor mínimo de negociação?
Olá. Você pode realizar a otimização na aba “Otimização”.