English Deutsch
preview
MQL5での取引戦略の自動化(第28回):視覚的フィードバックによるプライスアクションバットハーモニックパターンの作成

MQL5での取引戦略の自動化(第28回):視覚的フィードバックによるプライスアクションバットハーモニックパターンの作成

MetaTrader 5トレーディングシステム |
225 0
Allan Munene Mutiiria
Allan Munene Mutiiria

はじめに

前回の記事(第27回)では、ハーモニックパターンを用いて正確なフィボナッチ比に基づく高精度な反転ポイントを識別し、取引の自動化とチャートオブジェクトによるパターン可視化をおこなうクラブパターンシステムをMetaQuotes Language 5 (MQL5)で開発しました。今回の第28回では、ピボットポイントと特定のフィボナッチリトレースメント比を用いて、強気および弱気のバットハーモニックパターンを検出するバットパターンシステムを構築します。プログラムは、計算されたエントリー、ストップロス(SL)、複数段階のテイクプロフィット(TP)ポイントを自動設定し、さらに視認性を高めるために三角形、トレンドライン、ラベルなどの図形をチャート上に描画します。本記事では以下のトピックを扱います。

  1. バットハーモニックパターンのフレームワークを理解する
  2. MQL5での実装
  3. バックテスト
  4. 結論

この記事を読み終える頃には、バットハーモニックパターン取引のためのロバストなMQL5戦略を手に入れ、自由にカスタマイズできるようになります。それでは、さっそく始めましょう。


バットハーモニックパターンのフレームワークを理解する

バットパターンは、X、A、B、C、Dの5つの主要スイングポイントによって構成されるハーモニックパターンで、強気パターンと弱気パターンの2種類が存在します。いずれもフィボナッチ比に基づき、潜在的な反転ポイントを高精度で特定するための形成です。強気のバットでは、構造は低高低高低の順序で形成され、点Xはスイングロー、点Aはスイングハイ、点Bはスイングロー(XAの約0.5をリトレース)、点Cはスイングハイ(ABの0.382〜0.886をリトレース)、点Dはスイングロー(XAの0.886まで延長され、Xより上に位置)となります。逆に、弱気のバットでは高低高低高の順序となり、点Xはスイングハイ、点Aはスイングロー、点Bはスイングハイ、点Cはスイングロー、点Dはスイングハイ(XAの0.886まで延長され、Xより下に位置)となります。以下に、パターンの種類を図示します。

強気のバットハーモニックパターン

強気のバットパターン

弱気のバットハーモニックパターン

弱気のバットパターン

パターンを識別するために、以下のような構造化されたアプローチを採用します。

  • XAレッグの定義:点Xから点Aへの初動がパターンの方向(強気なら上向き、弱気なら下向き)を決定し、フィボナッチ計算の主基準となります。
  • ABレッグの確定:点BはXAレッグの約0.5をリトレースし、最初のインパルスに対する中程度の修正を示します。
  • BCレッグの分析:このレッグはABレッグの0.382〜0.886の範囲に収まり、最終的な反転ゾーンに向かうカウンタームーブを形成します。
  • CDレッグの設定:最終レッグはXAレッグの0.886まで延長され、点Dで潜在的な反転ゾーンが形成され、パターンが完了し取引シグナルが生成されます。

これらの幾何学的およびフィボナッチに基づく条件を適用することで、取引システムは価格データの中から有効なバットパターンを体系的に検出します。パターンが確認されると、EAはチャート上に三角形、トレンドライン、点X、A、B、C、Dのラベルに加えて、エントリーや利益確定の取引レベルを描画し、パターン形成を可視化します。これにより、計算されたストップロスおよび複数のテイクプロフィットゾーンを用いて点Dでの取引を自動的に実行でき、パターンが持つ反転予測の優位性を活用できるようになります。それでは、MQL5での実装に進みましょう。


MQL5での実装

MQL5でプログラムを作成するには、まずMetaEditorを開き、ナビゲータに移動して、Indicatorsフォルダを見つけ、[新規作成]タブをクリックして、表示される手順に従ってファイルを作成します。ファイルが作成されたら、コーディング環境で、まずプログラム全体で使用するグローバル変数をいくつか宣言する必要があります。

//+------------------------------------------------------------------+
//|                                              Bat 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 Bat 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

//--- 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 LotSize      = 0.01;   // Lot size for new orders  
input bool   AllowTrading = true;   // Enable or disable trading

//---------------------------------------------------------------------------  
//--- Bat pattern definition:  
//  
//--- Bullish Bat:  
//---   Pivots (X-A-B-C-D): X swing low, A swing high, B swing low, C swing high, D swing low.  
//---   Normally XA > 0; Ideal B = A - 0.5*(A-X); Legs within specified ranges.  
//  
//--- Bearish Bat:  
//---   Pivots (X-A-B-C-D): X swing high, A swing low, B swing high, C swing low, D swing high.  
//---   Normally XA > 0; Ideal B = A + 0.5*(X-A); Legs within specified ranges.  
//---------------------------------------------------------------------------

//--- 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
bool     g_tradeTaken          = false; //--- Flag to indicate if a trade has been taken for the current pattern

バットパターンシステムの基礎を築き、バットハーモニックパターンに基づいて取引を自動化するには、まず、<Trade\Trade.mqh>ライブラリをインクルードし、obj_TradeをCTradeオブジェクトとしてインスタンス化して、売買注文の実行などの取引操作を管理します。次に、ユーザーがカスタマイズできる入力パラメータを定義します。PivotLeftとPivotRightはそれぞれ5バーに設定してピボット検出のルックバック範囲を決定し、Toleranceは0.10に設定してフィボナッチ偏差の許容度を定め、LotSizeは0.01に設定して取引量を指定し、AllowTradingはtrueに設定して自動取引を有効化します。

続いて、スイングポイントを保存するためにtime(datetime)、price(double)、isHigh(bool)を保持するPivot構造体を定義し、これらの点を格納するためにpivotsを動的配列として宣言します。また、パターン形成を追跡するためにグローバル変数g_patternFormationBarを-1に初期化し、Xピボットの時間をロックするためにg_lockedPatternXを0に初期化し、同じパターンでの複数取引を防ぐためにg_tradeTakenをfalseに初期化して、バットパターンを検出し取引するためのEAの基盤を整えます。 可視化のために、ライン、ラベル、三角形を描画する関数を用意します。

//+------------------------------------------------------------------+  
//| 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);  
   }  
}

パターンとその主要レベルを明確に表すチャートを作成するために、ObjectCreateを使用して、時間(t1、t2、t3)と価格(p1、p2、p3)で定義される3つの点を持つ塗りつぶし三角形(OBJ_TRIANGLE)を描画するDrawTriangle関数を開発します。この関数では、OBJPROP_COLORを指定された色に設定し、OBJPROP_STYLEをSTYLE_SOLIDに、OBJPROP_WIDTHを指定された幅に設定し、OBJPROP_FILLで塗りつぶしの有無を指定し、OBJPROP_BACKを用いて背景または前景への配置をObjectSetIntegerで設定します。次に、三角形と同じ形式を用いて2点間にトレンドライン(OBJ_TREND)を描画するDrawTrendLine関数の作成に進みます。

続いて、水平の点線を作成し、同様にそのプロパティを定義するDrawDottedLine関数を実装します。最後に、座標(t、p)にテキストラベル(OBJ_TEXT)を作成し、ObjectSetStringとObjectSetIntegerを使用してOBJPROP_TEXTを指定テキストに設定し、OBJPROP_COLOR、OBJPROP_FONTSIZE、OBJPROP_FONTをArial Boldに設定し、OBJPROP_ANCHORを使用してisHighに基づきスイングハイの場合は上に、スイングローの場合は下にアンカーし、OBJPROP_ALIGNプロパティを用いて中央に配置するDrawTextEx関数を開発します。これで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イベントハンドラの初期ロジックを実装します。まず、最後に処理したバーを追跡するために0で初期化した静的変数lastBarTimeを宣言し、現在のシンボルと時間枠におけるシフト1のiTimeから取得したcurrentBarTimeと比較し、変化がない場合は冗長な処理を避けるため終了し、新しいバーが検出された時点でlastBarTimeを更新します。次に、ArrayResizeを使用してpivots配列をクリアし、分析を毎回新しい状態から開始できるようにします。

その後、Bars関数でバーの総数を取得し、ピボット検出の範囲としてstartをPivotLeft、endを総バー数からPivotRightを引いた値に設定し、end−1からstartまでのバーを順に処理します。各バーについて、スイングハイ(isPivotHighがtrue)およびスイングロー(isPivotLowがtrue)であると仮定し、iHighiLowを使ってそのバーの高値と安値を取得し、PivotLeftおよびPivotRightの範囲内にある周囲のバーをiHighとiLowでチェックし、隣接するバーにより高い高値またはより低い安値が存在する場合は、そのピボットを無効とします。最後に、バーがピボットとして有効であればPivot構造体を生成し、timeをiTimeで設定し、priceをisPivotHighに応じて高値または安値に設定し、isHighフラグを割り当てて、ArrayResizeを用いてpivots配列に追加します。この配列を出力すると、以下のような結果になります。

ピボットデータ

このデータを使ってピボットポイントを抽出でき、十分な数のピボットがあればパターンの解析と検出をおこなうことができます。これを実現するために、以下のロジックを実装しています。

//--- 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;  
   g_tradeTaken = false;  
   //--- 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 Bat pattern is found  
bool patternFound = false;  
//--- 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 ideal position for pivot B based on Fibonacci ratio  
      double idealB = A.price + 0.5 * diff;  
      //--- Check if actual B is within tolerance of the ideal position  
      if(MathAbs(B.price - idealB) <= Tolerance * diff) {  
         //--- Calculate the AB leg length  
         double AB = B.price - A.price;  
         //--- Calculate the BC leg length  
         double BC = B.price - C.price;  
         //--- Verify that BC is within the acceptable Fibonacci range  
         if((BC >= 0.382 * AB) && (BC <= 0.886 * AB)) {  
            //--- Calculate the extension  
            double extension = D.price - A.price;  
            //--- Verify that the extension is within tolerance of 0.886 and that D is below X  
            if(MathAbs(extension - 0.886 * diff) <= Tolerance * diff && (D.price < X.price))  
               patternFound = true;  
         }  
      }  
   }  
}  
//--- 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 ideal position for pivot B based on Fibonacci ratio  
      double idealB = A.price - 0.5 * diff;  
      //--- Check if actual B is within tolerance of the ideal position  
      if(MathAbs(B.price - idealB) <= Tolerance * diff) {  
         //--- Calculate the AB leg length  
         double AB = A.price - B.price;  
         //--- Calculate the BC leg length  
         double BC = C.price - B.price;  
         //--- Verify that BC is within the acceptable Fibonacci range  
         if((BC >= 0.382 * AB) && (BC <= 0.886 * AB)) {  
            //--- Calculate the extension  
            double extension = A.price - D.price;  
            //--- Verify that the extension is within tolerance of 0.886 and that D is above X  
            if(MathAbs(extension - 0.886 * diff) <= Tolerance * diff && (D.price > X.price))  
               patternFound = true;  
         }  
      }  
   }  
}

ここでは、正確なフィボナッチベースの基準を用いて強気パターンと弱気パターンの識別を続けます。まず、ArraySize(pivots)で得られるピボットの総数をpivotCountに格納し、ピボット数が5未満の場合は処理を終了し、g_patternFormationBar、g_lockedPatternX、g_tradeTakenをそれぞれ-1、0、falseにリセットします。これは、バットパターンではX、A、B、C、Dの5点が必須であるためです。次に、pivots配列から最後の5つのピボットを抽出し、最も古いものから順にX、A、B、C、Dを割り当ててパターン構造を形成します。

続いて、弱気のバットパターン(Xが高、Aが安、Bが高、Cが安、Dが高)を確認するため、まずXAレッグの差をX.price−A.priceとして計算し、それが正であることを確認します。次に、理想的なB点をA.price+0.5diffとして算出し、MathAbsを用いてBがTolerancediffの範囲内にあるかどうかを検証します。さらに、BCレッグがABの0.382〜0.886の範囲にあるかを確認し、AD拡張がXAの0.886であり、DがXより下に位置することを確かめ、すべての条件を満たす場合にはpatternFoundをtrueに設定します。最後に、強気のバットパターン(Xが安、Aが高、Bが安、Cが高、Dが安)を判定し、XAをA.price−X.priceとして計算して正であることを確認し、Bが0.5リトレースメントであること、BCがABの0.382〜0.886の範囲にあること、ADがXAの0.886でDがXより上に位置することを検証し、有効であればpatternFoundをtrueに設定します。これによりバットパターンを正確に検出でき、続く可視化処理および取引ロジックへと進むことができます。 パターンが検出された場合、チャート上にそのパターンを可視化する処理を進めることができます。

//--- If a valid Bat pattern is detected  
if(patternFound) {  
   //--- Print a message indicating the pattern type and detection time  
   Print(patternType, " Bat 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 = "BAT_" + 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);  
}

まず、有効なパターンが検出された場合(patternFoundがtrueの場合)、patternTypeを空文字列として初期化し、D.priceがX.priceより小さい場合は売りシグナルを示す「Bearish」に、大きい場合は買いシグナルを示す「Bullish」に設定します。次に、Printを用いて検出をログに記録し、patternTypeと、TimeToStringによって日付、分、秒形式で整形されたDピボットの時間を出力します。続いて、「BAT_」とX.timeをIntegerToStringで文字列に変換して連結し、一意の識別子であるsignalPrefixを作成します。最後に、triangleColorを強気パターンなら青、弱気パターンなら赤に設定し、DrawTriangleを2回呼び出します。最初はピボットX、A、Bを結ぶ三角形XABを、次にピボットB、C、Dを結ぶ三角形BCDを描画し、signalPrefixに「_Triangle1」と「_Triangle2」を付加したID、各ピボットの時間と価格、triangleColor、幅2、塗りつぶしと背景表示のtrueフラグを指定します。この処理によりバットパターンの構造が明確に可視化され、取引判断を支援できます。以下に結果を示します。

三角形セット

画像から、検出されたパターンを正しくマッピングおよび可視化できていることが確認できます。次に、トレンドラインを引き続きマッピングしてパターンを境界内で完全に可視化し、レベルをよりわかりやすく識別できるようにラベルを追加する必要があります。

//--- 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 Bat" : "Bearish Bat");  
   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);  
}

パターンをさらにわかりやすくするために、パターン構造を表す詳細なチャートオブジェクトを追加します。まず、主要なピボット点を結ぶために、固有のsignalPrefixを付けたDrawTrendLineを使用して6本の実線トレンドラインを描画します。XA、AB、BC、CD、XB、BDの各ラインは、それぞれのピボット時間と価格(例:X.time、X.price)を使用し、OBJPROP_COLORをclrBlack、OBJPROP_WIDTHを2、OBJPROP_STYLEをSTYLE_SOLIDに設定し、ObjectSetIntegerでパターンの各レッグを明確にします。次に、SymbolInfoDouble(_Symbol, SYMBOL_POINT)でシンボルの点サイズを取得し、ラベル配置のために15点のオフセットを計算し、各ピボットがスイングハイ(isHighがtrue)か安値かに応じてオフセットを加減してtextY_X、textY_A、textY_B、textY_C、textY_Dを決定し、高値の上、安値の下にラベルを配置します。この値は美観や使用するシンボルに応じて変更できます。

続いて、DrawTextExを使ってピボットX、A、B、C、Dのテキストラベルを作成します。signalPrefixに「_Text_X」などの接尾辞を付け、それぞれの文字を表示し、ピボット時間と調整済みのY座標に配置し、clrBlack、フォントサイズ11、ピボットのisHigh値をアンカーとして設定します。最後に、中央ラベルの位置をX.timeとB.timeの中点としてcentralTimeに、価格位置をD.priceとしてcentralPriceに設定し、ObjectCreateで「signalPrefix + _Text_Center」という名前のテキストオブジェクトを生成し、OBJPROP_TEXTをpatternTypeに応じて「Bullish Bat」または「Bearish Bat」に設定し、ObjectSetStringとObjectSetIntegerでOBJPROP_COLORをclrBlack、OBJPROP_FONTSIZEを11、OBJPROP_FONTをArial Bold、OBJPROP_ALIGNをALIGN_CENTERに設定します。このロジックにより、パターンの構造と種類がチャート上に包括的に表示されます。プログラムを実行すると、次のような表示が得られます。

ラベルとエッジのあるパターン

画像から、パターンにエッジ(トレンドライン)とラベルを追加したことで、より明確かつ視覚的に把握しやすくなったことが分かります。次におこなうべきことは、このパターンに基づいてトレードレベルを決定することです。

//--- Define start and end times for drawing horizontal dotted lines for obj_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 obj_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 obj_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 obj_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をピボットDの時間(D.time)に設定し、「PeriodSeconds(_Period) * 2」を用いてlineEndを2期間先に設定します。取引計算用の変数としてentryPriceLevel、TP1Level、TP2Level、TP3Level、tradeDiffを宣言します。次に、強気パターン(patternType == Bullish)の場合、SymbolInfoDoubleを使ってentryPriceLevelを現在の売値に設定し、TP3LevelをCピボットの価格に設定し、tradeDiffをTP3Level−entryPriceLevelとして計算し、TP1LevelとTP2LevelをtradeDiffの3分の1および3分の2をentryPriceLevelに加算して算出します。弱気パターンの場合は、買値を使用し、TP3LevelをCの価格に設定、tradeDiffをentryPriceLevel−TP3Levelとして計算し、取引差の3分の1および3分の2を減算してTP1LevelとTP2Levelを求めます。

次に、DrawDottedLineを使用して4本の点線水平線を描画します。マゼンタ色でentryPriceLevelのエントリーレベル線、TP1Levelをフォレストグリーン、TP2Levelをグリーン、TP3Levelをダークグリーンでテイクプロフィットラインとして、lineStartからlineEndまで描画します。最後に、labelTimeをlineEndに半期間を加えた値に設定し、DoubleToStringで価格をフォーマットしてラベルテキストを作成します(例:エントリーではBUY(price)またはSELL(price)、TP1は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_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 obj_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 obj_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) && !g_tradeTaken) {  
         double entryPriceTrade = 0, stopLoss = 0, takeProfit = 0;  
         point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);  
         bool tradeResult = false;  
         //--- For a Bullish pattern, execute a BUY obj_Trade  
         if(patternType=="Bullish") {  //--- BUY signal  
            entryPriceTrade = SymbolInfoDouble(_Symbol, SYMBOL_ASK);  
            double diffTrade = TP2Level - entryPriceTrade;  
            stopLoss = entryPriceTrade - diffTrade * 3;  
            takeProfit = TP2Level;  
            tradeResult = obj_Trade.Buy(LotSize, _Symbol, entryPriceTrade, stopLoss, takeProfit, "Bat Signal");  
            if(tradeResult)  {
               Print("Buy order opened successfully.");  
               g_tradeTaken = true;
            } else  
               Print("Buy order failed: ", obj_Trade.ResultRetcodeDescription());  
         }  
         //--- For a Bearish pattern, execute a SELL obj_Trade  
         else if(patternType=="Bearish") {  //--- SELL signal  
            entryPriceTrade = SymbolInfoDouble(_Symbol, SYMBOL_BID);  
            double diffTrade = entryPriceTrade - TP2Level;  
            stopLoss = entryPriceTrade + diffTrade * 3;  
            takeProfit = TP2Level;  
            tradeResult = obj_Trade.Sell(LotSize, _Symbol, entryPriceTrade, stopLoss, takeProfit, "Bat Signal");  
            if(tradeResult)  {
               Print("Sell order opened successfully.");  
               g_tradeTaken = true;
            } else  
               Print("Sell order failed: ", obj_Trade.ResultRetcodeDescription());  
         }  
      }  
      else {  
         //--- If a position is already open, do not execute a new obj_Trade  
         Print("A position is already open for ", _Symbol, ". No new obj_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;  
      g_tradeTaken = false;  
      Print("Pattern has changed; updating lock on bar ", currentBarIndex, ". Waiting for confirmation.");  
      return;  
   }  
}  
else {  
   //--- If no valid Bat pattern is detected, reset the pattern lock variables  
   g_patternFormationBar = -1;  
   g_lockedPatternX = 0;  
   g_tradeTaken = false;  
}

ここでは、パターンの取引実行とパターン確認を管理することで、システムのティック実装を完了します。まず、「Bars(_Symbol, _Period) - 1」で現在のバーのインデックスを取得し、currentBarIndexに格納します。次に、パターンがロックされていない場合(g_patternFormationBar == -1)、g_patternFormationBarをcurrentBarIndexに設定し、g_lockedPatternXにX.timeを格納してXピボットの時間をロックします。パターン検出をログに記録し、確認待ちであることを示して処理を終了します。次に、まだフォーメーションバー上にある場合(currentBarIndex == g_patternFormationBar)、再描画をログに記録して終了し、早すぎる取引を防ぎます。

最後に、新しいバーが形成され(currentBarIndex > g_patternFormationBar)かつXピボットがg_lockedPatternXと一致する場合、パターンを確認してログに記録し、g_patternFormationBarを更新します。その上で、AllowTradingで取引が許可されているか、PositionSelectでポジションが存在しないか、g_tradeTakenがfalseであるかを確認します。強気パターンの場合、entryPriceTradeを売値に設定し、diffTradeをTP2Level−entryPriceTradeとして計算し、stopLossをこの距離の3倍に設定、takeProfitをTP2Levelに設定して、LotSizeとBat Signalを用いてobj_Trade.Buyで買いを実行し、成功または失敗をログに記録してg_tradeTakenをtrueに設定します。弱気パターンの場合はBid価格を使用し、stopLossを上方3倍に設定してobj_Trade.Sellで売りを実行します。取引が許可されていない場合、ポジションが存在する場合、または取引済みの場合は、取引はおこなわれずログに記録されます。パターンが変更された場合はロックを更新して待機し、パターンが見つからない場合はグローバル変数をリセットします。コンパイルすると、次の結果が得られます。

弱気シグナル

弱気シグナル

強気シグナル

強気シグナル

画像から、ハーモニックパターンを正しくプロットできており、パターンが確定した後にそれに応じてエントリーできていることが確認できます。これにより、パターンの識別、描画、取引という目的を達成できています。残っている作業は、このプログラムのバックテストをおこなうことです。バックテストについては次のセクションで扱います。


バックテスト

徹底的なバックテストの結果、次の結果が得られました。

バックテストグラフ

グラフ

バックテストレポート

レポート


結論

結論として、私たちはMQL5バットパターンシステムを開発しました。価格の動きを活用して強気と弱気のバットハーモニックパターンを、正確なフィボナッチ比率で検出し、計算されたエントリー、SL、複数レベルのTPポイントを使用したエントリーを自動化し、三角形やトレンドラインといったチャートオブジェクトでパターンを可視化しました。

免責条項:本記事は教育目的のみを意図したものです。取引には重大な財務リスクが伴い、市場の変動によって損失が生じる可能性があります。本プログラムを実際の市場で運用する前に、十分なバックテストと慎重なリスク管理が不可欠です。

提示された概念と実装を活用することで、このバットパターンシステムを自分の取引スタイルに適応させ、アルゴリズム戦略を強化できます。取引をお楽しみください。 

MetaQuotes Ltdにより英語から翻訳されました。
元の記事: https://www.mql5.com/en/articles/19105

添付されたファイル |
Bat_Pattern_EA.mq5 (50.85 KB)
MQL5でのデータベースの簡素化(第1回):データベースとSQL入門 MQL5でのデータベースの簡素化(第1回):データベースとSQL入門
MQL5言語のネイティブ関数を用いたデータベース操作について解説します。テーブルの作成、データの挿入、更新、削除から、データのインポートとエクスポートまで、すべてサンプルコード付きで紹介します。本記事は、データアクセスの内部メカニズムを理解するための確固たる基盤を提供し、MQL5でORMを構築する際の土台となります。
チャート同期でテクニカル分析を簡単にする チャート同期でテクニカル分析を簡単にする
「Chart Synchronization for Easier Technical Analysis」は、単一の銘柄に対してすべてのチャート時間足でトレンドライン、四角形、インジケーターなどの一貫したグラフィックオブジェクトが表示されるようにするツールです。パン、ズーム、銘柄変更などの操作はすべての同期したチャートに反映されるため、トレーダーは複数の時間足で同じプライスアクションの文脈をシームレスに確認し、比較できます。
取引システムの構築(第3回):現実的な利益目標のための最小リスクレベルの決定 取引システムの構築(第3回):現実的な利益目標のための最小リスクレベルの決定
すべてのトレーダーの究極の目標は収益を上げることです。そのため、多くのトレーダーは、定められた取引期間内に達成すべき具体的な利益目標を設定します。本記事では、モンテカルロシミュレーションを用いて、取引目標を達成するために必要な取引ごとの最適なリスク割合を算出します。この結果は、利益目標が現実的か、それとも過度に野心的かを判断する際に役立ちます。最後に、取引目標に見合った実用的なリスク割合を設定するために調整可能なパラメータについても解説します。
MQL5で自己最適化エキスパートアドバイザーを構築する(第13回):行列分解を用いた制御理論の簡単な入門 MQL5で自己最適化エキスパートアドバイザーを構築する(第13回):行列分解を用いた制御理論の簡単な入門
金融市場は本質的に予測が難しく、過去には利益が出ていたように見える取引戦略でも、実際の市場環境では破綻することが少なくありません。主な原因は、ほとんどの戦略が一度展開されると振る舞いが固定され、失敗から学習したり適応したりできないということです。そこで制御理論の考え方を取り入れることで、フィードバックコントローラを用いて戦略と市場の相互作用を観察し、その挙動を収益性に向けて調整することが可能になります。今回の結果では、単純な移動平均戦略にフィードバックコントローラを導入するだけで、利益の向上、リスクの低減、効率の改善が見られ、このアプローチが取引用途において大きな可能性を持つことが示されました。