Automatização de estratégias de negociação em MQL5 (Parte 33): Desenvolvimento de um sistema de reconhecimento do padrão harmônico "Shark" utilizando Price Action
Introdução
No artigo anterior (Parte 32), desenvolvemos um sistema de reconhecimento do padrão gráfico "5 Drives (5-0)" em MetaQuotes Language 5 (MQL5), capaz de identificar padrões harmônicos de alta e de baixa "5 Drives" utilizando proporções de Fibonacci. Esse sistema automatizava a execução de operações com níveis configuráveis de stop-loss e take-profit, representando visualmente os padrões por meio de objetos gráficos, como triângulos e linhas de tendência. Na Parte 33, desenvolveremos um sistema de reconhecimento do padrão "Shark" (tubarão), capaz de identificar suas formações harmônicas de alta e de baixa com base em pontos de reversão e níveis específicos de retração e extensão de Fibonacci. O sistema executará operações com opções flexíveis de entrada, stop-loss e realização de lucros em vários níveis. Além disso, utilizaremos triângulos, linhas de tendência e rótulos para representar visualmente a estrutura dos padrões. Neste artigo, abordaremos os seguintes tópicos:
Ao final, você terá uma estratégia de negociação estável em MQL5, baseada no padrão harmônico "Shark" e pronta para ser personalizada. Vamos começar a implementação!
Estudo da estrutura do padrão harmônico "Shark"
O padrão Shark é uma formação harmônica utilizada na negociação, definida por cinco pontos de reversão principais: X, A, B, C e D. Ele pode apresentar uma configuração de alta ou de baixa e é utilizado para identificar zonas com elevada probabilidade de reversão por meio de retrações e extensões de Fibonacci. No padrão "Shark" de alta, a estrutura segue a sequência "fundo-topo-fundo-topo-fundo", em que: X representa um fundo de oscilação (swing low). A representa um topo de oscilação (swing high). B representa um fundo de oscilação, correspondente a uma retração de 0,32 a 0,50 do movimento XA. C representa um topo de oscilação, correspondente a uma extensão de 1,13 a 1,618 do movimento AB. D representa um fundo de oscilação, correspondente a uma extensão de 1,618 a 2,24 do movimento BC, situado abaixo do ponto B. No padrão "Shark" de baixa, essa sequência é invertida, e o ponto D fica acima do ponto B. A seguir, apresentamos as representações visuais desses padrões:
Padrão harmônico "Shark" de baixa:

Padrão harmônico "Shark" de alta:

Nossa abordagem consiste em identificar esses pontos de reversão dentro de um intervalo definido de barras, validar os movimentos do padrão de acordo com os critérios de Fibonacci, representar visualmente a estrutura X-A-B-C-D por meio de objetos gráficos, como triângulos e linhas de tendência, e abrir operações no ponto D para aproveitar a reversão esperada do preço. O sistema permitirá configurar o stop-loss, utilizando uma extensão de Fibonacci ou uma distância fixa, e selecionar diferentes níveis de take-profit, correspondentes a um terço, dois terços ou ao preço do ponto de reversão C. Vamos começar a implementação!
Implementação em MQL5
Para criar o programa em MQL5, abra o MetaEditor, acesse o "Navegador", selecione a pasta Indicators, clique em "Criar" e siga as instruções para criar o arquivo. Precisaremos declarar algumas variáveis globais que serão utilizadas ao longo do programa.
//+------------------------------------------------------------------+ //| Shark 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 Shark 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 C TP2 = 2, // Two-thirds of the move to C TP3 = 3 // Pivot C 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 XA move) input double MinRetrace = 0.32; // Minimum retracement for AB (strictness control) input double MaxRetrace = 0.50; // Maximum retracement for AB (strictness control) input double MinExt1 = 1.13; // Minimum extension for BC (strictness control) input double MaxExt1 = 1.618; // Maximum extension for BC (strictness control) input double MinExt2 = 1.618; // Minimum extension for CD (strictness control) input double MaxExt2 = 2.24; // Maximum extension for CD (strictness control) 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_lockedPatternX = 0; //--- The key X pivot time for the locked pattern //--- Global array to track traded patterns (using X.time as identifier) datetime tradedPatterns[];
Para estabelecer a base do sistema de reconhecimento do padrão Shark, começaremos incluindo a biblioteca "<Trade\Trade.mqh>" e criando uma instância chamada "obj_Trade" da classe CTrade, responsável por gerenciar operações de negociação, como a abertura de posições compradas e vendidas. Em seguida, definiremos as enumerações "ENUM_TAKE_PROFIT_LEVEL", com as opções TP1 para um terço, TP2 para dois terços e TP3 para o preço do ponto de reversão C, e "ENUM_STOP_LOSS_TYPE", com SL_FIBO para uma extensão de Fibonacci e SL_FIXED para uma distância fixa em pontos. Essas enumerações permitirão configurar os níveis de saída das operações com maior flexibilidade. Também definiremos os seguintes parâmetros de entrada: "PivotLeft" e "PivotRight": ambos com valor padrão de 5 barras, utilizados para identificar os pontos de reversão. "Tolerance": valor padrão de 0.10, que determina a tolerância em relação aos níveis de Fibonacci. "MinRetrace": 0.32 e "MaxRetrace": 0.50, que estabelecem os limites de retração do segmento AB. "MinExt1": 1.13 e "MaxExt1": 1.618, que definem os limites de extensão do segmento BC. "MinExt2": 1.618 e "MaxExt2": 2.24, que estabelecem os limites de extensão do segmento CD. "LotSize": 0.01, que define o volume das operações. "AllowTrading": true, que permite habilitar a execução de operações. "TakeProfitLevel": TP2, que seleciona o nível de take-profit correspondente a dois terços. "StopLossType": SL_FIBO, que define o stop-loss com base em uma extensão de Fibonacci. "SL_FiboExtension": 1.618, que estabelece o fator de extensão de Fibonacci utilizado no cálculo do stop-loss. "SL_FixedPoints": 50, que determina a distância fixa do stop-loss em pontos.
Depois, definiremos a estrutura "Pivot", com os campos "time", "price" e "isHigh", para armazenar os pontos de reversão dos preços. Declararemos "pivots" como um array dinâmico e inicializaremos as variáveis globais: "g_patternFormationBar" com o valor -1, "g_lockedPatternX" com o valor 0, para armazenar o horário do ponto de reversão X, e "tradedPatterns" como um array destinado a acompanhar os padrões já negociados, utilizando o horário do ponto X como referência. Essa estrutura fornecerá a base necessária para identificar os padrões "Shark" e executar operações com base neles. Para a representação visual, utilizaremos funções específicas para desenhar 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, vamos implementar as funções de visualização para representar claramente o padrão harmônico "Shark" e os níveis utilizados nas operações. Primeiro, criaremos a função "DrawTriangle", que utilizará ObjectCreate para desenhar um triângulo preenchido (OBJ_TRIANGLE), definido por três pontos. Cada ponto terá suas coordenadas de tempo ("t1", "t2", "t3") e preço ("p1", "p2", "p3"). Utilizando a função ObjectSetInteger, configuraremos as propriedades do objeto gráfico da seguinte maneira: "OBJPROP_COLOR": receberá a cor especificada para o triângulo. "OBJPROP_STYLE": será definida como "STYLE_SOLID", para utilizar linhas contínuas. "OBJPROP_WIDTH": receberá a largura de linha especificada. "OBJPROP_FILL": permitirá habilitar ou desabilitar o preenchimento do triângulo. "OBJPROP_BACK": determinará se o objeto será exibido no plano de fundo ou em primeiro plano. Em seguida, implementaremos a função "DrawTrendLine", responsável por criar uma linha de tendência (OBJ_TREND) entre dois pontos.
Em seguida, implementaremos a função "DrawDottedLine", responsável por desenhar uma linha horizontal pontilhada (OBJ_TREND) no nível de preço especificado, entre os instantes "t1" e "t2". Por fim, desenvolveremos a função "DrawTextEx", que utilizará ObjectCreate para criar um rótulo de texto (OBJ_TEXT) nas coordenadas de tempo e preço ("t", "p"). Configuraremos "OBJPROP_TEXT" com o texto especificado, além das propriedades "OBJPROP_COLOR" e "OBJPROP_FONTSIZE", e definiremos "OBJPROP_FONT" como "Arial Bold", utilizando as funções ObjectSetString e ObjectSetInteger. Com base no parâmetro "isHigh", posicionaremos o texto acima dos topos de oscilação (swing highs) ou abaixo dos fundos de oscilação (swing lows), utilizando "OBJPROP_ANCHOR". Também centralizaremos o texto por meio da propriedade "OBJPROP_ALIGN". Agora, vamos implementar o tratamento do evento OnTick para identificar os pontos de reversão que utilizaremos posteriormente no reconhecimento dos padrões. A lógica necessária é apresentada a seguir.
//+------------------------------------------------------------------+ //| 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; } } }
Começaremos implementando a parte inicial da função OnTick, responsável pela identificação dos pontos de reversão, uma etapa fundamental para reconhecer o padrão harmônico "Shark". Primeiro, declararemos uma variável estática chamada "lastBarTime", inicializada com 0, para acompanhar a última barra processada. Compararemos seu valor com "currentBarTime", obtido por meio da função iTime, utilizando o deslocamento 1 para o símbolo e o timeframe atuais. Para evitar processamento desnecessário, encerraremos a execução se o horário da barra não tiver mudado. Quando identificarmos uma nova barra, atualizaremos "lastBarTime" com o horário correspondente. Em seguida, limparemos o array "pivots" utilizando ArrayResize, preparando-o para uma nova análise. Depois, obteremos a quantidade total de barras por meio da função Bars e definiremos o intervalo de busca dos pontos de reversão: "start" receberá o valor de "PivotLeft", enquanto "end" corresponderá à quantidade total de barras menos "PivotRight". Percorreremos então as barras desse intervalo.
Para cada barra, inicialmente consideraremos que ela pode representar tanto um topo de oscilação ("isPivotHigh" = true) quanto um fundo de oscilação ("isPivotLow" = true). Obteremos seus preços máximo e mínimo utilizando as funções iHigh e iLow. Em seguida, verificaremos as barras vizinhas dentro dos limites definidos por "PivotLeft" e "PivotRight", novamente utilizando iHigh e iLow, para confirmar se a barra analisada representa um ponto de reversão. A condição de topo será invalidada se alguma barra vizinha apresentar uma máxima superior. Da mesma forma, a condição de fundo será invalidada se alguma barra vizinha apresentar uma mínima inferior. Se a barra atender aos critérios de identificação de um ponto de reversão, criaremos uma estrutura "Pivot". Atribuiremos ao campo "time" o horário obtido por iTime, ao campo "price" o preço máximo ou mínimo, conforme o valor de "isPivotHigh", e configuraremos o sinalizador "isHigh" para indicar o tipo de ponto identificado. Por fim, ampliaremos o array "pivots" utilizando ArrayResize e armazenaremos nele a estrutura criada. Ao exibir os dados dos pontos de reversão, obteremos o seguinte array:

Com esses dados, podemos identificar os pontos de reversão e, quando houver uma quantidade suficiente deles, analisar a estrutura formada para detectar padrões. A lógica necessária é apresentada a seguir.
//--- Determine the total number of pivots found int pivotCount = ArraySize(pivots); //--- If fewer than five pivots are found, the pattern cannot be formed if(pivotCount < 5) { //--- Reset pattern lock variables g_patternFormationBar = -1; g_lockedPatternX = 0; //--- Exit the OnTick function return; } //--- Extract the last five pivots as X, A, B, C, and D Pivot X = pivots[pivotCount - 5]; Pivot A = pivots[pivotCount - 4]; Pivot B = pivots[pivotCount - 3]; Pivot C = pivots[pivotCount - 2]; Pivot D = pivots[pivotCount - 1]; //--- Initialize a flag to indicate if a valid Shark pattern is found bool patternFound = false; //--- Initialize pattern type string patternType = ""; //--- Check for the low-high-low-high-low (Bullish reversal) structure if((!X.isHigh) && A.isHigh && (!B.isHigh) && C.isHigh && (!D.isHigh)) { //--- Calculate the difference between pivot A and X double diff = A.price - X.price; //--- Ensure the difference is positive if(diff > 0) { //--- Calculate the retracement from A to B double retrace = A.price - B.price; //--- Verify retracement is within user-defined range if((retrace >= MinRetrace * diff) && (retrace <= MaxRetrace * diff)) { //--- Calculate the extension from B to C double extension1 = C.price - B.price; //--- Verify extension is within user-defined range of retrace if((extension1 >= MinExt1 * retrace) && (extension1 <= MaxExt1 * retrace)) { //--- Calculate the extension from C to D double extension2 = C.price - D.price; //--- Verify extension is within user-defined range of previous extension if((extension2 >= MinExt2 * extension1) && (extension2 <= MaxExt2 * extension1) && (D.price < B.price)) { patternFound = true; patternType = "Bullish"; } } } } } //--- Check for the high-low-high-low-high (Bearish reversal) structure if(X.isHigh && (!A.isHigh) && B.isHigh && (!C.isHigh) && D.isHigh) { //--- Calculate the difference between pivot X and A double diff = X.price - A.price; //--- Ensure the difference is positive if(diff > 0) { //--- Calculate the retracement from A to B double retrace = B.price - A.price; //--- Verify retracement is within user-defined range if((retrace >= MinRetrace * diff) && (retrace <= MaxRetrace * diff)) { //--- Calculate the extension from B to C double extension1 = B.price - C.price; //--- Verify extension is within user-defined range of retrace if((extension1 >= MinExt1 * retrace) && (extension1 <= MaxExt1 * retrace)) { //--- Calculate the extension from C to D double extension2 = D.price - C.price; //--- Verify extension is within user-defined range of previous extension if((extension2 >= MinExt2 * extension1) && (extension2 <= MaxExt2 * extension1) && (D.price > B.price)) { patternFound = true; patternType = "Bearish"; } } } } }
Primeiro, determinaremos a quantidade total de pontos de reversão utilizando "ArraySize(pivots)" e armazenaremos esse valor em "pivotCount". Se forem encontrados menos de cinco pontos de reversão, encerraremos a execução, redefinindo "g_patternFormationBar" para -1 e "g_lockedPatternX" para 0. Isso ocorre porque o reconhecimento do padrão "Shark" exige cinco pontos: X, A, B, C e D. Em seguida, extrairemos os cinco pontos de reversão mais recentes do array "pivots" e os atribuiremos às variáveis "X", "A", "B", "C" e "D", em que "X" representa o ponto mais antigo da sequência e "D", o mais recente.
Em seguida, para identificar um padrão de alta (fundo X, topo A, fundo B, topo C e fundo D), calcularemos a amplitude do movimento XA ("A.price - X.price") e verificaremos se seu valor é positivo. Depois, confirmaremos se a retração AB ("A.price - B.price") está entre "MinRetrace" (0.32) e "MaxRetrace" (0.50) do movimento XA, se a extensão BC ("C.price - B.price") está entre "MinExt1" (1.13) e "MaxExt1" (1.618) do movimento AB e se a extensão CD ("C.price - D.price") está entre "MinExt2" (1.618) e "MaxExt2" (2.24) do movimento BC, com a condição "D.price < B.price". Se todos os critérios forem atendidos, definiremos "patternFound" como true e "patternType" como "Bullish". Para identificar um padrão de baixa (topo X, fundo A, topo B, fundo C e topo D), aplicaremos verificações semelhantes ao movimento XA ("X.price - A.price"), à retração AB ("B.price - A.price"), à extensão BC ("B.price - C.price") e à extensão CD ("D.price - C.price"), exigindo também que "D.price > B.price". Se o padrão for válido, 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 Shark pattern is detected if(patternFound) { //--- Print a message indicating the pattern type and detection time Print(patternType, " Shark pattern detected at ", TimeToString(D.time, TIME_DATE|TIME_MINUTES|TIME_SECONDS)); //--- Create a unique prefix for all graphical objects related to this pattern string signalPrefix = "SH_" + IntegerToString(X.time); //--- Choose triangle color based on the pattern type color triangleColor = (patternType=="Bullish") ? clrBlue : clrRed; //--- Draw the first triangle connecting pivots X, A, and B DrawTriangle(signalPrefix+"_Triangle1", X.time, X.price, A.time, A.price, B.time, B.price, triangleColor, 2, true, true); //--- Draw the second triangle connecting pivots B, C, and D DrawTriangle(signalPrefix+"_Triangle2", B.time, B.price, C.time, C.price, D.time, D.price, triangleColor, 2, true, true); }
Agora, vamos implementar a visualização dos padrões identificados. Primeiro, quando "patternFound" for true, utilizaremos a função Print para registrar no log a identificação do padrão, incluindo o valor de "patternType" ("Bullish" ou "Bearish") e o horário do ponto de reversão D, formatado pela função TimeToString para apresentar a data e o horário com minutos e segundos. Em seguida, criaremos um identificador exclusivo chamado "signalPrefix", combinando o prefixo "SH_" com o valor de "X.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 identificação visual. Por fim, chamaremos a função "DrawTriangle" duas vezes para representar a estrutura do padrão. Na primeira chamada, desenharemos o triângulo XAB, conectando os pontos de reversão X, A e B. Na segunda, desenharemos o triângulo BCD, conectando os pontos B, C e D. Para identificar esses objetos, utilizaremos "signalPrefix" com os sufixos "_Triangle1" e "_Triangle2", respectivamente. Também forneceremos os horários e preços dos pontos de reversão correspondentes, a cor definida em "triangleColor" e a largura de linha 2. Os sinalizadores de preenchimento e exibição no plano de fundo serão definidos 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 mostrar todo o contorno do padrão, além de rótulos que facilitarão a identificação dos níveis.
//--- Draw boundary trend lines connecting the pivots for clarity DrawTrendLine(signalPrefix+"_TL_XA", X.time, X.price, A.time, A.price, clrBlack, 2, STYLE_SOLID); 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_XB", X.time, X.price, B.time, B.price, clrBlack, 2, STYLE_SOLID); DrawTrendLine(signalPrefix+"_TL_BD", B.time, B.price, D.time, D.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_X = (X.isHigh ? X.price + offset : X.price - offset); 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); //--- Draw text labels for each pivot with appropriate anchoring DrawTextEx(signalPrefix+"_Text_X", "X", X.time, textY_X, clrBlack, 11, X.isHigh); 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); //--- Calculate the central label's time as the midpoint between pivots X and B datetime centralTime = (X.time + B.time) / 2; //--- Set the central label's price at pivot D's price double centralPrice = D.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 Shark" : "Bearish Shark"); 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); }
Para aprimorar a visualização dos padrões identificados, incluiremos objetos gráficos adicionais que permitirão representar sua estrutura com mais detalhes. Primeiro, desenharemos seis linhas de tendência contínuas utilizando a função "DrawTrendLine" e o identificador exclusivo "signalPrefix". Essas linhas conectarão os principais pontos de reversão, formando os segmentos XA, AB, BC, CD, XB e BD. Cada linha utilizará os valores de tempo e preço dos pontos correspondentes, como "X.time" e "X.price". Para destacar o contorno do padrão, configuraremos "OBJPROP_COLOR" como "clrBlack", "OBJPROP_WIDTH" como 2 e "OBJPROP_STYLE" como "STYLE_SOLID", utilizando a função ObjectSetInteger. Em seguida, obteremos o tamanho de um ponto do símbolo por meio da função "SymbolInfoDouble(_Symbol, SYMBOL_POINT)" e calcularemos um deslocamento equivalente a 15 pontos para posicionar os rótulos. Definiremos então as coordenadas verticais "textY_X", "textY_A", "textY_B", "textY_C" e "textY_D", adicionando ou subtraindo esse deslocamento de acordo com o tipo de ponto de reversão. Quando o ponto representar um topo de oscilação ("isHigh" = true), posicionaremos o rótulo acima da máxima. Quando representar um fundo de oscilação, posicionaremos o rótulo abaixo da mínima.
Em seguida, utilizaremos a função "DrawTextEx" para criar rótulos de texto para os pontos de reversão X, A, B, C e D. Cada rótulo terá um nome formado por "signalPrefix" e um sufixo correspondente, como "_Text_A", e exibirá a letra do respectivo ponto. Os rótulos serão posicionados no horário de cada ponto de reversão, com a coordenada vertical ajustada anteriormente. Utilizaremos a cor "clrBlack", o tamanho de fonte 11 e o sinalizador "isHigh" para definir o posicionamento do texto em relação ao ponto. Por fim, calcularemos a posição central do rótulo, definindo "centralTime" como o ponto médio entre "X.time" e "B.time" e "centralPrice" como o preço "D.price". Utilizaremos ObjectCreate para criar um objeto de texto com o nome "signalPrefix + '_Text_Center'". Configuraremos "OBJPROP_TEXT" como "Bullish Shark" ou "Bearish Shark", conforme o valor de "patternType". Também definiremos "OBJPROP_COLOR" como "clrBlack", "OBJPROP_FONTSIZE" como 11, "OBJPROP_FONT" como "Arial Bold" e "OBJPROP_ALIGN" como "ALIGN_CENTER", utilizando as funções ObjectSetString e ObjectSetInteger. Após executar o programa, obteremos a seguinte representação visual:

Na imagem, podemos observar que as linhas de contorno e os rótulos foram adicionados ao padrão, tornando sua estrutura mais clara. O próximo passo será definir os níveis de negociação.
//--- Define start and end times for drawing horizontal dotted lines for trade levels datetime lineStart = D.time; datetime lineEnd = D.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 C's price TP3Level = C.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 C's price TP3Level = C.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);
Para calcular e representar visualmente os níveis de negociação do padrão identificado, definiremos "lineStart" como o horário do ponto de reversão D ("D.time") e "lineEnd" como dois períodos à frente, utilizando "PeriodSeconds(_Period) * 2". Declararemos as variáveis "entryPriceLevel", "TP1Level", "TP2Level", "TP3Level" e "tradeDiff", que serão utilizadas nos cálculos dos níveis de negociação. Para um padrão de alta ("patternType == 'Bullish'"), atribuiremos a "entryPriceLevel" o preço Ask atual, obtido por meio da função SymbolInfoDouble. Definiremos "TP3Level" como o preço do ponto de reversão C e calcularemos "tradeDiff" pela diferença "TP3Level - entryPriceLevel". Em seguida, calcularemos "TP1Level" e "TP2Level", adicionando ao preço de entrada, respectivamente, um terço e dois terços do valor de "tradeDiff". Para um padrão de baixa, utilizaremos o preço Bid como nível de entrada e definiremos "TP3Level" como o preço do ponto C. Calcularemos "tradeDiff" pela diferença "entryPriceLevel - TP3Level". Depois, determinaremos "TP1Level" e "TP2Level", subtraindo do preço de entrada, respectivamente, um terço e dois terços dessa diferença.
Em seguida, utilizaremos a função "DrawDottedLine" para desenhar quatro linhas horizontais pontilhadas, entre "lineStart" e "lineEnd": A linha de entrada, no nível "entryPriceLevel", será exibida em magenta. A linha do primeiro take-profit, no nível "TP1Level", será exibida em verde-floresta intenso. A linha do segundo take-profit, no nível "TP2Level", será exibida em verde. A linha do terceiro take-profit, no nível "TP3Level", será exibida em verde-escuro. Por fim, definiremos "labelTime" como o valor de "lineEnd" acrescido de metade da duração de um período. Criaremos rótulos de texto contendo os respectivos preços, formatados pela função DoubleToString. Para o nível de entrada, utilizaremos textos como "BUY (price)" ou "SELL (price)", conforme a direção da operação. Para os níveis de take-profit, utilizaremos "TP1 (price)", "TP2 (price)" e "TP3 (price)". A função "DrawTextEx" será utilizada para desenhar esses rótulos na posição temporal definida por "labelTime", com as cores correspondentes a cada nível, tamanho de fonte 11 e posicionamento acima dos respectivos preços. 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, precisamos 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_lockedPatternX = X.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 X pivot if(g_lockedPatternX == X.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] == X.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 second_drive = C.price - D.price; stopLoss = D.price - (SL_FiboExtension - 1.0) * second_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, "Shark 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 second_drive = D.price - C.price; stopLoss = D.price + (SL_FiboExtension - 1.0) * second_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, "Shark 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] = X.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 X pivot g_patternFormationBar = currentBarIndex; g_lockedPatternX = X.time; Print("Pattern has changed; updating lock on bar ", currentBarIndex, ". Waiting for confirmation."); return; } } else { //--- If no valid Shark pattern is detected, reset the pattern lock variables g_patternFormationBar = -1; g_lockedPatternX = 0; }
Concluiremos a implementação da função OnTick, adicionando a lógica de execução das operações e de confirmação dos padrões identificados. Primeiro, obteremos o índice da barra atual utilizando a expressão "Bars(_Symbol, _Period) - 1" e armazenaremos esse valor na variável "currentBarIndex". Em seguida, se ainda não houver um padrão registrado ("g_patternFormationBar == -1"), atribuiremos a "g_patternFormationBar" o valor de "currentBarIndex" e armazenaremos o horário do ponto de reversão X ("X.time") em "g_lockedPatternX". Utilizaremos a função Print para registrar no log a identificação do padrão e informar que ele está aguardando confirmação. Depois, encerraremos a execução.
Se o padrão ainda estiver na mesma barra em que foi identificado ("currentBarIndex == g_patternFormationBar"), consideraremos que sua formação ainda pode sofrer alterações. Nesse caso, encerraremos a execução para evitar a abertura prematura de posições. Quando uma nova barra for formada ("currentBarIndex > g_patternFormationBar") e o horário do ponto de reversão X corresponder ao valor armazenado em "g_lockedPatternX", confirmaremos o padrão. Registraremos essa confirmação no log, atualizaremos "g_patternFormationBar" e verificaremos se a negociação está habilitada e se já existe alguma posição aberta, utilizando a função PositionSelect. Também verificaremos o array "tradedPatterns" para confirmar que o padrão ainda não foi negociado. Em seguida, selecionaremos o nível de take-profit conforme a configuração escolhida pelo usuário, utilizando "TP1Level", "TP2Level" ou "TP3Level". Recalcularemos também o stop-loss de acordo com o método selecionado. Antes de executar a operação, verificaremos se o stop-loss está corretamente posicionado: abaixo do preço de entrada para uma compra ou acima dele para uma venda. Se necessário, ajustaremos o nível em 10 pontos para garantir que essa condição seja atendida. Depois, abriremos uma posição comprada ou vendida utilizando "obj_Trade.Buy" ou "obj_Trade.Sell", respectivamente, com o volume definido em "LotSize" e a identificação "Shark Signal". Registraremos no log o sucesso ou a falha da execução e adicionaremos o padrão ao array "tradedPatterns" para identificá-lo como já negociado. Se a negociação estiver desabilitada, já existir uma posição aberta ou o padrão tiver sido negociado anteriormente, registraremos no log uma mensagem informando que nenhuma operação foi executada. Caso o padrão identificado sofra alterações, atualizaremos as informações armazenadas e aguardaremos uma nova confirmação. Se nenhum padrão for encontrado, redefiniremos as variáveis globais utilizadas no controle da formação. Após compilar o programa, obteremos o seguinte resultado.
Sinal de baixa:

Sinal de alta:

Na imagem, podemos observar que o padrão harmônico é representado corretamente no gráfico e pode ser utilizado para executar operações após sua confirmação. Com isso, alcançamos nosso objetivo de identificar o padrão, representar visualmente sua estrutura e implementar a negociação baseada nele. Agora, resta avaliar o desempenho do programa por meio de testes históricos.
Testes históricos
Após realizar testes históricos detalhados, obtivemos os seguintes resultados.
Gráfico do teste:

Relatório do teste histórico:

Conclusão
Concluímos o desenvolvimento de um sistema de reconhecimento do padrão "Shark" em MQL5. O sistema utiliza a análise da ação do preço (Price Action) para identificar padrões harmônicos de alta e de baixa, com níveis específicos de retração e extensão de Fibonacci. Além disso, automatiza a execução de operações com pontos de entrada calculados, níveis de stop-loss e múltiplos níveis de take-profit, representando visualmente os padrões por meio de objetos gráficos, como triângulos e linhas de tendência.
Atenção: todo o conteúdo deste artigo tem finalidade exclusivamente educacional e não se destina a outros fins. A negociação nos mercados financeiros envolve riscos significativos, e a volatilidade pode provocar perdas. Antes de utilizar este programa em operações reais, é fundamental realizar testes históricos rigorosos e adotar práticas adequadas de gerenciamento de riscos.
Com os conceitos e métodos de implementação apresentados, você poderá adaptar esse sistema de reconhecimento do padrão "Shark" ao seu estilo de negociação e aprimorar suas estratégias algorítmicas. Boas negociações!
Traduzido do Inglês pela MetaQuotes Ltd.
Artigo original: https://www.mql5.com/en/articles/19479
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.