Flag and Pennant continuation pattern EA
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «flagpennantea.mq5» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Flag and Pennant EA — торговый советник для MetaTrader 5, который выявляет паттерны продолжения тренда (флаг и папоротник) на основе анализа свинг-структур. Советник сканирует импульсные полюса на заданном таймфрейме, затем воспроизводит последующие бары текущего графика для обнаружения консолидации и пробоя. При подтверждённом пробое рассчитывается объём позиции на основе процента риска от депозита и расстояния стоп-лосса, после чего открываются сделки с уровнями входа, стоп-лосса и тейк-профита.
Система работает в трёх состояниях: поиск новых полюсов, отслеживание активного флага и управление открытой позицией. Для измерений используется индикатор ATR, рассчитываемый на свинг-ТФ. Записи об использованных полюсах сохраняются через глобальные переменные терминала, чтобы не входить в один и тот же паттерн повторно. Доступна визуализация на графике через горизонтальные линии и текстовые метки.
Настройки программы
| Настройка | Описание |
|---|---|
| InpSwingStrength | Количество баров по каждую сторону от свинга |
| InpSwingLookback | Максимальное количество баров H4 для сканирования свингов |
| InpSwingTF | Таймфрейм для анализа свинг-структуры |
| InpMinPoleATR | Минимальная высота полюса в единицах ATR свинг-ТФ |
| InpMaxPoleBars | Максимальное количество баров свинг-ТФ для формирования полюса |
| InpMinFlagBars | Минимальное количество баров текущего графика консолидации, чтобы пробой засчитывался |
| InpMaxFlagBars | Максимальное количество баров текущего графика консолидации до истечения паттерна |
| InpMaxRetracePct | Максимальный откат флага как доля высоты полюса |
| InpATRPeriod | Период индикатора ATR, рассчитываемого на свинг-ТФ |
| InpRiskPercent | Процент риска депозита на одну сделку |
| InpSLBufferATR | Буфер стоп-лосса за границей флага в единицах ATR свинг-ТФ |
| InpUseMeasuredMove | Использовать целевой уровень измеренного движения; при false — расчёт как 2R |
| InpMaxSlipATR | Пропустить вход, если цена ушла от уровня пробоя на указанное количество ATR |
| InpMagicNumber | Магический номер для идентификации позиций советника |
| InpSlippage | Допустимое проскальзывание в пунктах |
| InpShowLabels | Отображать метки паттерна на графике |
| InpDebugLog | Вести лог причин отклонения каждой неудачной проверки паттерна |
Поиск по коду файла
#property version "1.00"
#property description "Flag and Pennant continuation pattern EA"
#property description "Swing structure reads InpSwingTF (default H4) internally"
#property description "Requires SwingEngine.mqh from Part 1"
#include <Trade\Trade.mqh>
#include <ChartPatterns\SwingEngine.mqh>
input group "=== Swing Engine ==="
input int InpSwingStrength = 3; // H4 bars on each side of a swing
input int InpSwingLookback = 200; // Maximum H4 bars to scan
input ENUM_TIMEFRAMES InpSwingTF = PERIOD_H4; // Timeframe for swing structure
input group "=== Pattern Settings ==="
input double InpMinPoleATR = 2.0; // Minimum pole height, in swing-TF ATR
input int InpMaxPoleBars = 15; // Maximum swing-TF bars for the pole to form
input int InpMinFlagBars = 5; // Minimum CHART bars of consolidation before a breakout counts
input int InpMaxFlagBars = 30; // Maximum CHART bars of consolidation before the setup expires
input double InpMaxRetracePct = 0.5; // Maximum flag retracement, as a fraction of pole height
input int InpATRPeriod = 14; // ATR period, computed on InpSwingTF
input group "=== Entry and Risk ==="
input double InpRiskPercent = 1.0; // Account risk per trade, percent
input double InpSLBufferATR = 0.5; // Stop loss buffer beyond the flag boundary, swing-TF ATR
input bool InpUseMeasuredMove = true; // Use measured move target (false = 2R fallback)
input double InpMaxSlipATR = 0.5; // Skip entry if price is already this many ATR past the breakout level
input group "=== General ==="
input int InpMagicNumber = 444004; // Magic number
input int InpSlippage = 10; // Slippage in points
input bool InpShowLabels = true; // Draw pattern labels on chart
input bool InpDebugLog = false; // Log the reason every rejected pattern check fails
enum ENUM_FL_STATE
{
FL_STATE_SCANNING, // No pole locked, evaluating every bar
FL_STATE_TRACKING, // Pole locked, replaying the flag each bar
FL_STATE_IN_TRADE // Position open from this pattern
};
enum ENUM_FLAG_STATUS
{
FLAG_PENDING, // Consolidating inside every limit
FLAG_BREAKOUT, // Valid breakout on the bar that just closed
FLAG_EARLY_BREAK, // Closed beyond the boundary before InpMinFlagBars
FLAG_MISSED_BREAK, // Valid breakout happened on an earlier bar
FLAG_RETRACED, // Gave back more than InpMaxRetracePct of the pole
FLAG_EXPIRED, // More than InpMaxFlagBars bars without a breakout
FLAG_NO_DATA // Chart history not available yet, retry next bar
};
struct SPatternResult
{
bool valid;
bool is_bullish; // true = bullish pole (long breakout), false = bearish pole (short breakout)
double pole_start; // Price where the pole began
double pole_end; // Price where the pole ended, the flag's starting boundary
double break_level; // Flag boundary in the pole's direction (the level to break)
double stop_ref; // Opposite flag extreme, the reference for the stop
int flag_bars; // Chart bars in the flag before the current bar
double target; // Filled in at breakout
double stop; // Filled in at breakout
datetime pole_start_time; // H4 bar time of the pole's first swing
datetime pole_end_time; // H4 bar time of the pole's last swing, also the pattern identity
};
CSwingEngine g_engine; // Swing engine from Part 1, reads InpSwingTF internally
CTrade g_trade; // Trade execution object
int g_atr_handle = INVALID_HANDLE; // ATR handle on InpSwingTF
datetime g_last_bar = 0; // Last processed CHART bar time
string g_obj_prefix = ""; // Unique per symbol + magic number, set in OnInit()
ENUM_FL_STATE g_state = FL_STATE_SCANNING; // Current pattern lifecycle state
SPatternResult g_active; // The one pole currently locked in
datetime g_spent_bull_pole = 0; // pole_end_time of the last bullish pole used up
datetime g_spent_bear_pole = 0; // pole_end_time of the last bearish pole used up
string g_gv_bull_name = ""; // Global variable names that persist the two values
string g_gv_bear_name = "";
void DebugLog(string msg)
{
if(InpDebugLog)
Print("FlagPennantEA[debug]: ", msg);
}
bool HasOpenPosition(const string symbol, const long magic)
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(!PositionSelectByTicket(ticket))
continue;
if(PositionGetString(POSITION_SYMBOL) != symbol)
continue;
if(PositionGetInteger(POSITION_MAGIC) != magic)
continue;
return true;
}
return false;
}
double CalcLots(double sl_points)
{
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
double risk_amt = balance * InpRiskPercent / 100.0;
double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
if(tick_size <= 0 || tick_value <= 0 || sl_points <= 0)
return 0;
double point_value = (_Point / tick_size) * tick_value; // Money value of one point, 1.0 lot
double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
if(step <= 0)
return 0;
double raw_lots = risk_amt / (sl_points * point_value);
double steps = MathFloor(raw_lots / step + 0.0000001); // Epsilon guards float rounding
double lots = NormalizeDouble(steps * step, 8);
if(lots < min_lot)
return 0; // Skip rather than over-risk
return MathMin(max_lot, lots);
}
bool HasSufficientMargin(ENUM_ORDER_TYPE order_type, double lots, double price)
{
double margin_required = 0;
if(!OrderCalcMargin(order_type, _Symbol, lots, price, margin_required))
return false;
return (margin_required <= AccountInfoDouble(ACCOUNT_MARGIN_FREE));
}
void ResetPattern(SPatternResult &p)
{
p.valid = false;
p.is_bullish = true;
p.pole_start = 0;
p.pole_end = 0;
p.break_level = 0;
p.stop_ref = 0;
p.flag_bars = 0;
p.target = 0;
p.stop = 0;
p.pole_start_time = 0;
p.pole_end_time = 0;
}
void ClosePole(const SPatternResult &pat)
{
if(pat.is_bullish)
{
g_spent_bull_pole = pat.pole_end_time;
GlobalVariableSet(g_gv_bull_name, (double)pat.pole_end_time);
}
else
{
g_spent_bear_pole = pat.pole_end_time;
GlobalVariableSet(g_gv_bear_name, (double)pat.pole_end_time);
}
}
void RefreshSpentRecords()
{
if(g_spent_bull_pole > 0)
GlobalVariableSet(g_gv_bull_name, (double)g_spent_bull_pole);
if(g_spent_bear_pole > 0)
GlobalVariableSet(g_gv_bear_name, (double)g_spent_bear_pole);
}
string FlagStatusText(ENUM_FLAG_STATUS st)
{
switch(st)
{
case FLAG_PENDING:
return "still consolidating";
case FLAG_BREAKOUT:
return "breakout";
case FLAG_EARLY_BREAK:
return "closed beyond the boundary before the minimum consolidation";
case FLAG_MISSED_BREAK:
return "breakout already happened on an earlier bar";
case FLAG_RETRACED:
return "retraced beyond the maximum fraction of the pole";
case FLAG_EXPIRED:
return "maximum consolidation length exceeded";
case FLAG_NO_DATA:
return "chart history not available";
}
return "unknown";
}
void DrawHLine(string name, double price, color clr, ENUM_LINE_STYLE style)
{
if(!InpShowLabels)
return;
string obj = g_obj_prefix + name;
if(ObjectFind(0, obj) < 0)
{
if(!ObjectCreate(0, obj, OBJ_HLINE, 0, 0, price))
{ DebugLog("ObjectCreate failed for " + obj); return; }
}
ObjectSetDouble(0, obj, OBJPROP_PRICE, price);
ObjectSetInteger(0, obj, OBJPROP_COLOR, clr);
ObjectSetInteger(0, obj, OBJPROP_STYLE, style);
ObjectSetInteger(0, obj, OBJPROP_WIDTH, 1);
}
void DrawLabel(string name, datetime t, double price, string text, color clr)
{
if(!InpShowLabels)
return;
string obj = g_obj_prefix + name;
if(ObjectFind(0, obj) < 0)
{
if(!ObjectCreate(0, obj, OBJ_TEXT, 0, t, price))
{ DebugLog("ObjectCreate failed for " + obj); return; }
}
ObjectMove(0, obj, 0, t, price);
ObjectSetString(0, obj, OBJPROP_TEXT, text);
ObjectSetInteger(0, obj, OBJPROP_COLOR, clr);
ObjectSetInteger(0, obj, OBJPROP_FONTSIZE, 9);
}
void DeleteObject(string name)
{
string obj = g_obj_prefix + name;
if(ObjectFind(0, obj) >= 0)
ObjectDelete(0, obj);
}
void ClearLabels()
{
int total = ObjectsTotal(0);
for(int i = total - 1; i >= 0; i--)
{
string name = ObjectName(0, i);
if(StringFind(name, g_obj_prefix) == 0)
ObjectDelete(0, name);
}
}
bool FindPole(bool bullish, SSwingPoint &pole_start, SSwingPoint &pole_end)
{
int count = g_engine.GetSwingCount();
for(int i = 0; i < count - 1; i++)
{
SSwingPoint sp = g_engine.GetSwing(i); // Index 0 is the newest swing
if(sp.is_high != bullish)
continue; // Wrong type to end this pole
SSwingPoint prev = g_engine.GetSwing(i + 1); // Its older neighbour
if(prev.is_high == bullish)
return false; // Two same-type neighbours: not a single leg
if(prev.time <= 0 || sp.time <= prev.time)
return false;
pole_end = sp;
pole_start = prev;
return true;
}
return false;
}
bool CheckPole(bool bullish, double atr, SPatternResult &out)
{
ResetPattern(out);
out.is_bullish = bullish;
string side = bullish ? "Bull" : "Bear";
SSwingPoint s_start, s_end;
if(!FindPole(bullish, s_start, s_end))
{ DebugLog(side + " pole reject: no single-leg pole in the latest swings."); return false; }
double pole_height = bullish ? s_end.price - s_start.price
: s_start.price - s_end.price;
if(pole_height < atr * InpMinPoleATR)
{ DebugLog(StringFormat("%s pole reject: height %.5f below minimum.", side, pole_height)); return false; }
int start_shift = iBarShift(_Symbol, InpSwingTF, s_start.time, true);
int end_shift = iBarShift(_Symbol, InpSwingTF, s_end.time, true);
if(start_shift < 0 || end_shift < 0)
{ DebugLog(side + " pole reject: swing bar not found on the swing timeframe."); return false; }
int pole_bars = start_shift - end_shift;
if(pole_bars <= 0 || pole_bars > InpMaxPoleBars)
{ DebugLog(StringFormat("%s pole reject: duration=%d bars outside (0, %d].", side, pole_bars, InpMaxPoleBars)); return false; }
out.valid = true;
out.pole_start = s_start.price;
out.pole_end = s_end.price;
out.pole_start_time = s_start.time;
out.pole_end_time = s_end.time;
return true;
}
ENUM_FLAG_STATUS EvaluateFlag(SPatternResult &pat)
{
datetime flag_start = pat.pole_end_time + PeriodSeconds(InpSwingTF);
int s = iBarShift(_Symbol, PERIOD_CURRENT, flag_start, false);
if(s < 0)
return FLAG_NO_DATA;
if(iTime(_Symbol, PERIOD_CURRENT, s) < flag_start)
s--; // Start fell in a gap: use the first bar after it
pat.break_level = pat.pole_end;
pat.stop_ref = pat.pole_end;
pat.flag_bars = 0;
if(s < 1)
return FLAG_PENDING; // No closed chart bar in the flag yet
double pole_height = MathAbs(pat.pole_end - pat.pole_start);
double max_retrace = pole_height * InpMaxRetracePct;
double level = pat.pole_end; // RunniПоказано первые 50% кода (символов: 17748)