← К каталогу
Исходный код · ID 4777

SMC Fusion Pro v2

smc_fusion_pro_v2.mq5

Похожие материалы по тегам

indicator crt with smc levels for tradingview.pineTradingView · 1 общих теговgold_session_liquidity_free_mt5 (1).mq5MQL5 / MetaTrader 5 · 1 общих теговconfluenceforge_pro.mq5TradingView · 1 общих теговidentical candles.mq5MQL5 / MetaTrader 5 · 1 общих теговbattleplan_ciclo_3_tempi.mq4MQL4 / MetaTrader 4 · 1 общих теговvolatility_gold_master.mq5MQL5 / MetaTrader 5 · 1 общих тегов
Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Краткий обзор

О программе

SMC Fusion Pro v2 — индикатор MetaTrader 5, рассчитывающий 17 паттернов смарт-денежных концепций (Order Block, FVG, BOS, CRT Retest, Mitigation Block, Propulsion Block, Vacuum Block и др.) и объединяющий их в конfluence-сигналы с настраиваемыми весами. Отображает зоны входа с проекциями TP/SL на графике, включает фильтр VWAP, детекцию структурных пробоев, сессионный фильтр и систему анти-перекрытия зон. Встроенная панель с кнопками позволяет переключать отображение, таймфрейм и фильтры, а также отслеживать статистику закрытых сигналов (TP1/TP2, SL-хиты, ожидание). Индикатор работает на закрытых свечах с причинно-корректным расчётом ATR и не перерисовывает исторические сигналы.

Настройки программы

НастройкаОписание
Notice Текстовое уведомление-предупреждение, отображаемое пользователю.
SimpleForexTeam__ Текстовый параметр с информацией о команде и каналах разработчика.
InpMinQuality Минимальная оценка качества сигнала (количество совпадающих паттернов): LOW 3, MEDIUM 4, HIGH 5, ULTRA 6.
InpMinCategories Минимальное количество различных структурных семейств (от 1 до 4), необходимых для формирования конfluence-сигнала.
InpShowScore Отображение оценки конfluence на метке зоны.
InpConfluenceWindow Количество баров, в пределах которых объединяются сигналы для расчёта конfluence-оценки.
InpWeightIFVG Вес паттерна Inverse FVG в конfluence-оценке.
InpWeightCRT Вес паттерна CRT Retest в конfluence-оценке.
InpWeightOB Вес паттерна Order Block в конfluence-оценке.
InpWeightMIT Вес паттерна Mitigation Block в конfluence-оценке.
InpWeightPROP Вес паттерна Propulsion Block в конfluence-оценке.
InpWeightVAC Вес паттерна Vacuum Block (True Gap) в конfluence-оценке.
InpWeightUNI Вес паттерна Unicorn Block в конfluence-оценке.
InpWeightBRK Вес паттерна Breaker Block в конfluence-оценке.
InpWeightFVG Вес паттерна FVG Re-Entry в конfluence-оценке.
InpWeightBPR Вес паттерна Balanced Price Range в конfluence-оценке.
InpWeightKZ Вес паттерна Killzone OB в конfluence-оценке.
InpWeightCE Вес паттерна CE 50% Raid в конfluence-оценке.
InpWeightSFP Вес паттерна Swing Failure Pattern в конfluence-оценке.
InpWeightREJ Вес паттерна Rejection Block в конfluence-оценке.
InpWeightSD Вес паттерна Supply/Demand Flip в конfluence-оценке.
InpWeightWY Вес паттерна Wyckoff Spring/UT в конfluence-оценке.
InpWeightMSS Вес паттерна MSS Entry в конfluence-оценке.
InpRequireFVGConfirm Обязательное подтверждение FVG-смещением перед принятием конfluence-сигнала.
InpFVGConfirmBars Максимальное количество баров ожидания подтверждения FVG-смещения перед принятием сигнала.
InpFilterMode Основной фильтр тренда: выключен или VWAP.
InpShowFilter Отображение линии VWAP при активном фильтре.
InpVWAPCol Цвет линии VWAP.
InpVWAPWidth Толщина линии VWAP.
InpBOSMode Режим отображения структурных пробоев: выключен, отображение или фильтр.
InpBosSwingLen Длина свинга для обнаружения структурных пробоев (количество баров).
InpBosBreakMode Тип разрыва структуры: по закрытию свечи или по фитилям.
InpBosShowLevels Отображение активных уровней свинг-хай/лоу на графике.
InpBosBullCol Цвет линий и подписей бычьих структурных пробоев.
InpBosBearCol Цвет линий и подписей медвежьих структурных пробоев.
InpBOSLineWidth Толщина линий структурных пробоев, отрисовываемых на графике.
InpBOSLabelSize Размер шрифта подписей структурных пробоев (BOS/ChoCH) на графике.
InpSourceTFEnum Таймфрейм-источник для анализа: текущий или один из стандартных (M1, M5, M15, M30, H1, H4, D1, W1, MN1).
InpBuyZoneColor Цвет заливки бычьих зон.
InpSellZoneColor Цвет заливки медвежьих зон.
InpBuyBorderCol Цвет границы бычьих зон.
InpSellBorderCol Цвет границы медвежьих зон.
InpBtnFont Шрифт текста на кнопках интерактивной панели.
InpBtnFontSize Размер шрифта текста на кнопках интерактивной панели.
InpBtnOnColor Цвет активной кнопки панели.
InpBtnOffColor Цвет неактивной кнопки панели.
InpBtnBgColor Цвет фона кнопок интерактивной панели.
InpBtnBorderColor Цвет рамки кнопок интерактивной панели.
InpBtnX Горизонтальная позиция панели кнопок на графике (в пикселях от левого верхнего угла).
InpBtnY Вертикальная позиция панели кнопок на графике (в пикселях от левого верхнего угла).
InpBtnWidth Ширина кнопок интерактивной панели в пикселях.
InpBtnHeight Высота кнопок интерактивной панели в пикселях.
InpBtnSound Включение звукового сигнала при нажатии кнопок панели.
InpBtnSoundFile Путь к звуковому файлу, воспроизводимому при нажатии кнопок.
InpMaxBars Количество исторических баров для сканирования при расчёте.
InpPivotLen Длина фрактального пивота для обнаружения свинг-экстремумов.
InpSwingLookback Количество баров назад для поиска свинг-экстремумов (отскоков).
InpOBSearchDepth Глубина поиска Order Block в истории (количество баров назад).
InpMinBodyRatio Минимальное соотношение тела свечи к её диапазону для распознавания Order Block.
InpRetestBars Максимальный возраст (в барах) CRT Retest-зон, которые ещё могут дать сигнал.
InpUseBody Использование тела свечи (а не полного диапазона) для определения границ зон.
InpUseSession Включение сессионного фильтра (ограничение анализа по торговой сессии).
InpSessionStart Время начала сессионного фильтра в формате ЧЧ:ММ.
InpSessionEnd Время окончания сессионного фильтра в формате ЧЧ:ММ.
InpHideMitigated Скрытие зон, которые уже были пробиты (митигированы).
InpHideOverlap Скрытие новых зон при перекрытии существующими противоположными.
InpShowLabels Отображение текстовых подписей зон на графике.
InpShowMidline Отображение средней линии внутри зон.
InpExtendBars Количество баров для расширения отображения зон при перерисовке.
InpLiveExtendBars Количество баров для расширения активных зон в реальном времени.
InpMaxZonesPerSide Максимальное количество одновременно отображаемых зон на одну сторону (бычью или медвежью).
InpBuyArrowCol Цвет стрелок для бычьих зон.
InpSellArrowCol Цвет стрелок для медвежьих зон.
InpArrowSize Размер стрелок-меток, отображаемых на графике для обозначения зон.
InpChartLabelSize Размер шрифта подписей зон и уровней на графике.
InpATRLength Период расчёта индикатора ATR (средний истинный диапазон), используемый для определения зон и фильтров.
InpSLMultiplier Множитель ATR для расчёта расстояния стоп-лосса от цены входа.
InpTPMultiplier1 Множитель ATR для расчёта первого тейк-профита.
InpTPMultiplier2 Множитель ATR для расчёта второго тейк-профита.
InpMoveToBEAtTP1 Перемещение стоп-лосса в безубыток после достижения первого тейк-профита.
InpShowTPSL Отображение линий и зон TP/SL на графике.
InpProjectionBars Максимальное количество баров удержания/проекции для активных зон до автоматического истечения.
InpTPZoneCol Цвет зоны тейк-профита на графике.
InpSLZoneCol Цвет зоны стоп-лосса на графике.
InpEntryLineCol Цвет линии входа в зону на графике.
InpTPLineCol Цвет линий тейк-профита на графике.
InpSLLineCol Цвет линии стоп-лосса на графике.
InpCooldownBuy Минимальное количество баров между последовательными бычьими сигналами.
InpCooldownSell Минимальное количество баров между последовательными медвежьими сигналами.
InpEnableAlerts Включение всплывающих уведомлений-оповещений о новых зонах.
InpEnablePush Включение отправки push-уведомлений на мобильные устройства.
InpEnableEmail Включение отправки электронной почты при появлении новых зон.

Поиск по коду файла

#property version   "2.00"

#property strict
#property indicator_chart_window
#property indicator_buffers 0
#property indicator_plots   0

enum SignalQuality   { LOW_3=0, MEDIUM_4=1, HIGH_5=2, ULTRA_6=3 };
enum FilterMode      { FILTER_OFF=0, FILTER_VWAP=1 };
enum BOSMode         { BOS_OFF=0, BOS_DISPLAY=1, BOS_FILTER=2 };
enum BreakMode       { BREAK_CLOSE=0, BREAK_WICK=1 };
enum SourceTimeframe { TF_CURRENT=0, TF_M1=1, TF_M5=2, TF_M15=3, TF_M30=4, TF_H1=5, TF_H4=6, TF_D1=7, TF_W1=8, TF_MN1=9 };

input string Notice = "Trading are risky! Trade only if you can loss your money";
input string SimpleForexTeam__ = "free tools for forex! Join our channel for more free eas";
input string The_our_telegram = "";
input string VIP_group = "";
input group "═══ FUSION ENGINE SETTINGS ═══"
input SignalQuality InpMinQuality         = LOW_3;  // Minimum Signal Quality (Count)
input int           InpMinCategories      = 2;      // Min Distinct Structural Families (1-4)
input bool          InpShowScore          = true;   // Show Confluence Score on Label
input int           InpConfluenceWindow   = 3;      // Confluence Window (Bars)

input group "═══ STRATEGY WEIGHTS ═══"
input double InpWeightIFVG = 1.0; // Weight: Inverse FVG
input double InpWeightCRT  = 1.2; // Weight: CRT Retest
input double InpWeightOB   = 1.5; // Weight: Order Block
input double InpWeightMIT  = 1.0; // Weight: Mitigation Block
input double InpWeightPROP = 1.3; // Weight: Propulsion Block
input double InpWeightVAC  = 0.8; // Weight: Vacuum Block (True Gap)
input double InpWeightUNI  = 1.5; // Weight: Unicorn Block
input double InpWeightBRK  = 1.4; // Weight: Breaker Block
input double InpWeightFVG  = 1.0; // Weight: FVG Re-Entry
input double InpWeightBPR  = 1.2; // Weight: Balanced Price Range
input double InpWeightKZ   = 1.3; // Weight: Killzone OB
input double InpWeightCE   = 1.0; // Weight: CE 50% Raid
input double InpWeightSFP  = 1.4; // Weight: Swing Failure Pattern
input double InpWeightREJ  = 1.1; // Weight: Rejection Block
input double InpWeightSD   = 1.2; // Weight: Supply/Demand Flip
input double InpWeightWY   = 1.3; // Weight: Wyckoff Spring/UT
input double InpWeightMSS  = 1.5; // Weight: MSS Entry

input group "═══ FVG CONFIRMATION ═══"
input bool InpRequireFVGConfirm = true; // Require FVG Displacement Confirmation
input int  InpFVGConfirmBars    = 3;    // Max Bars to Wait for FVG Confirm

input group "═══ FILTER SELECTION ═══"
input FilterMode InpFilterMode = FILTER_OFF; // Primary Trend Filter
input bool       InpShowFilter = true;       // Show VWAP Line When Active

input group "═══ VWAP FILTER ═══"
input color InpVWAPCol   = (color)55295; // VWAP Color
input int   InpVWAPWidth = 2;            // VWAP Line Width

input group "═══ BOS / CHOCH ═══"
input BOSMode   InpBOSMode       = BOS_FILTER;       // Structure Break Mode
input int       InpBosSwingLen   = 15;               // Structure Swing Length
input BreakMode InpBosBreakMode  = BREAK_CLOSE;      // Structure Break Type
input bool      InpBosShowLevels = true;             // Show Active Swing Levels
input color     InpBosBullCol    = (color)7451452;   // Bullish Structure Color
input color     InpBosBearCol    = (color)4678655;   // Bearish Structure Color
input int       InpBOSLineWidth  = 2;                // Structure Line Width
input int       InpBOSLabelSize  = 8;                // Structure Label Size

input group "═══ SOURCE TIMEFRAME ═══"
input SourceTimeframe InpSourceTFEnum = TF_CURRENT;

input group "═══ ZONE COLORS ═══"
input color InpBuyZoneColor  = (color)15128749;
input color InpSellZoneColor = (color)11788021;
input color InpBuyBorderCol  = (color)16760576;
input color InpSellBorderCol = (color)17919;

input group "═══ SMC UI PANEL & BUTTONS ═══"
input string InpBtnFont        = "Arial Bold";
input int    InpBtnFontSize    = 9;
input color  InpBtnOnColor     = (color)65280;
input color  InpBtnOffColor    = (color)255;
input color  InpBtnBgColor     = (color)2629150;
input color  InpBtnBorderColor = (color)16748574;
input int    InpBtnX           = 200;
input int    InpBtnY           = 10;
input int    InpBtnWidth       = 62;
input int    InpBtnHeight      = 22;
input bool   InpBtnSound       = true;
input string InpBtnSoundFile   = "tick.wav";

input group "═══ CANDLE LIMIT & STRATEGY PARAMS ═══"
input int    InpMaxBars       = 2000;    // History Bars to Scan
input int    InpPivotLen      = 3;       // Fractal Pivot Length
input int    InpSwingLookback = 20;      // Swing Lookback Bars
input int    InpOBSearchDepth = 15;      // Order Block Search Depth
input double InpMinBodyRatio  = 0.30;    // Min OB Body-to-Range Ratio
input int    InpRetestBars    = 20;      // Max Retest Age (Bars)
input bool   InpUseBody       = false;   // Use Candle Body for Zones
input bool   InpUseSession    = false;   // Enable Session Time Filter
input string InpSessionStart  = "08:00"; // Session Start (HH:MM)
input string InpSessionEnd    = "17:00"; // Session End (HH:MM)

input group "═══ VISUAL DISPLAY ═══"
input bool  InpHideMitigated   = true;
input bool  InpHideOverlap     = true;
input bool  InpShowLabels      = true;
input bool  InpShowMidline     = false;
input int   InpExtendBars      = 5;
input int   InpLiveExtendBars  = 25;
input int   InpMaxZonesPerSide = 5;
input color InpBuyArrowCol     = (color)16711680;
input color InpSellArrowCol    = (color)9639167;
input int   InpArrowSize       = 3;
input int   InpChartLabelSize  = 9;

input group "═══ TP/SL PROJECTION SETTINGS ═══"
input int    InpATRLength      = 14;
input double InpSLMultiplier   = 1.5;
input double InpTPMultiplier1  = 1.5;
input double InpTPMultiplier2  = 3.0;
input bool   InpMoveToBEAtTP1  = true;   // Move SL to Breakeven after TP1 Hit
input bool   InpShowTPSL       = true;
input int    InpProjectionBars = 24;     // Max Holding / Projection Bars
input color  InpTPZoneCol      = (color)10025880;
input color  InpSLZoneCol      = (color)4678655;
input color  InpEntryLineCol   = (color)8421504;
input color  InpTPLineCol      = (color)32768;
input color  InpSLLineCol      = (color)255;

input group "═══ ANTI-OVERLAP & ALERTS ═══"
input int  InpCooldownBuy  = 8;
input int  InpCooldownSell = 8;
input bool InpEnableAlerts = true;
input bool InpEnablePush   = true;
input bool InpEnableEmail  = false;

struct Signal
{
   bool     valid, buy;
   double   top, bottom, entry, high, low;
   datetime start, end;
   int      strategy, bar;
   double   weight;
};

struct Block
{
   double   top, bottom;
   bool     buy, flipped, used;
   int      bar;
   datetime time;
};

struct Fusion
{
   bool     valid, buy, mitigated, active, tp1hit, tp2hit, slhit, behit;
   double   top, bottom, entry, high, low, score, sl, tp1, tp2, atr, realizedR;
   datetime start, end, finish;
   int      count, categories, bar, entryBar;
   string   names;
};

struct StructureBreak
{
   bool     buy, change;
   double   price;
   datetime start, end;
};

MqlRates       R[];
double         VW[], ATRBuf[];
Signal         Pool[];
Block          InverseBuy[], InverseSell[], CrtBlocks[], MitBlocks[], BreakBlocks[], GapBlocks[], BprBlocks[], SdBlocks[];
Fusion         Zones[], Pending[];
StructureBreak Breaks[];

bool            Enabled=true, ShowTargets=true, ForceRefresh=true, Initialized=false;
int             FilterSetting=0, BosSetting=0, QualitySetting=0, TimeframeSetting=0;
int             LastBuy=-9999, LastSell=-9999, Trend=0, HighBar=-1, LowBar=-1;
double          SwingHigh=0, SwingLow=0;
bool            HighReady=false, LowReady=false;
string          Prefix;
datetime        LastSourceBar=0, LastAlert=0;
ENUM_TIMEFRAMES SourceTF=PERIOD_CURRENT;

int    g_TotalClosed = 0;
int    g_TP1Wins     = 0;
int    g_TP2Wins     = 0;
int    g_SLHits      = 0;
double g_TotalR      = 0.0;

double Weight(const int id)
{
   double w[17]={InpWeightIFVG,InpWeightCRT,InpWeightOB,InpWeightMIT,InpWeightPROP,InpWeightVAC,InpWeightUNI,
                 InpWeightBRK,InpWeightFVG,InpWeightBPR,InpWeightKZ,InpWeightCE,InpWeightSFP,InpWeightREJ,
                 InpWeightSD,InpWeightWY,InpWeightMSS};
   return (id>=0 && id<17) ? w[id] : 1.0;
}

string StrategyName(const int id)
{
   string n[17]={"IF","CRT","OB","MIT","PROP","VAC","UNI","BRK","FVG","BPR","KZ","CE","SFP","REJ","SD","WY","MSS"};
   return (id>=0 && id<17) ? n[id] : "";
}

int StrategyCategory(const int id)
{
   switch(id)
   {
      case 2: case 4: case 5: case 10:         return 0; // Family 0: Impulse / Displacement (OB, PROP, VAC, KZ)
      case 0: case 8: case 9: case 11:         return 1; // Family 1: Fair Value Gap / Imbalance (IFVG, FVG, BPR, CE)
      case 1: case 3: case 7: case 14:         return 2; // Family 2: Block Retest / Flip (CRT, MIT, BRK, SD)
      default:                                 return 3; // Family 3: Liquidity Sweep / Structure (UNI, SFP, REJ, WY, MSS)
   }
}

double Body(const int i)      { return MathAbs(R[i].close - R[i].open); }
double Range(const int i)     { return R[i].high - R[i].low; }
bool   Bull(const int i)      { return R[i].close > R[i].open; }
bool   Bear(const int i)      { return R[i].close < R[i].open; }
double ZoneHigh(const int i)  { return InpUseBody ? MathMax(R[i].open, R[i].close) : R[i].high; }
double ZoneLow(const int i)   { return InpUseBody ? MathMin(R[i].open, R[i].close) : R[i].low; }
double UpperWick(const int i) { return R[i].high - MathMax(R[i].open, R[i].close); }
double LowerWick(const int i) { return MathMin(R[i].open, R[i].close) - R[i].low; }

void CalculateATR()
{
   int n = ArraySize(R);
   ArrayResize(ATRBuf, n);
   ArrayInitialize(ATRBuf, 0.0);
   if(n <= InpATRLength) return;

   double sum = 0.0;
   for(int i = 1; i < n; i++)
   {
      double tr = MathMax(R[i].high - R[i].low,
                  MathMax(MathAbs(R[i].high - R[i-1].close),
                          MathAbs(R[i].low  - R[i-1].close)));
      if(i <= InpATRLength)
      {
         sum += tr;
         if(i == InpATRLength) ATRBuf[i] = sum / InpATRLength;
      }
      else
      {
         ATRBuf[i] = (ATRBuf[i-1] * (InpATRLength - 1) + tr) / InpATRLength;
      }
   }
}

double PivotHigh(const int p, const int span, const int maxBar)
{
   if(p < span || p + span > maxBar || p + span >= ArraySize(R)) return 0.0;
   for(int j = p - span; j <= p + span; j++)
      if(j != p && R[j].high >= R[p].high) return 0.0;
   return R[p].high;
}

double PivotLow(const int p, const int span, const int maxBar)
{
   if(p < span || p + span > maxBar || p + span >= ArraySize(R)) return 0.0;
   for(int j = p - span; j <= p + span; j++)
      if(j != p && R[j].low <= R[p].low) return 0.0;
   return R[p].low;
}

bool Killzone(const int i)
{
   MqlDateTime t; TimeToStruct(R[i].time, t);
   return (t.hour >= 2 && t.hour <= 5) || (t.hour >= 7 && t.hour <= 10) || t.hour >= 20 || t.hour == 0;
}

int MinuteOfDay(const string s)
{
   string a[];
   if(StringSplit(s, ':', a) != 2) return -1;
   int h = (int)StringToInteger(a[0]), m = (int)StringToInteger(a[1]);
   if(h < 0 || h > 23 || m < 0 || m > 59) return -1;
   return h * 60 + m;
}

bool SessionAllowed(const int i)
{
   if(!InpUseSession) return true;
   MqlDateTime t; TimeToStruct(R[i].time, t);
   int m = t.hour * 60 + t.min;
   int a = MinuteOfDay(InpSessionStart), b = MinuteOfDay(InpSessionEnd);
   return (a <= b) ? (m >= a && m <= b) : (m >= a || m <= b);
}

void MakeSignal(Signal &s, const int id, const bool buy, const int i, const int start,
                const double top, const double bottom, const double multiplier=1.0)
{
   ZeroMemory(s);
   s.valid    = true;
   s.buy      = buy;
   s.strategy = id;
   s.bar      = i;
   s.top      = MathMax(top, bottom);
   s.bottom   = MathMin(top, bottom);
   s.entry    = R[i].close;
   s.high     = R[i].high;
   s.low      = R[i].low;
   s.start    = R[MathMax(0, start)].time;
   s.end      = R[i].time;
   s.weight   = Weight(id) * multiplier;
}

void PushBlock(Block &a[], const double top, const double bottom, const bool buy, const int bar, const datetime time)
{
   int n = ArraySize(a);
   ArrayResize(a, n + 1);
   ZeroMemory(a[n]);
   a[n].top    = MathMax(top, bottom);
   a[n].bottom = MathMin(top, bottom);
   a[n].buy    = buy;
   a[n].bar    = bar;
   a[n].time   = time;
}

void TrimBlocks(Block &a[], const int count)
{
   int n = ArraySize(a);
   if(n > count) ArrayRemove(a, 0, n - count);
}

void FromBlock(Signal &s, const Block &b, const int id, const bool buy, const int i)
{
   MakeSignal(s, id, buy, i, b.bar, b.top, b.bottom);
   s.start = b.time;
}

void DetectIFVG(const int i, const double atr, Signal &s)
{
   if(i < 4) return;
   if(R[i].low - R[i-2].high > atr * 0.1 && ArraySize(InverseBuy) < 40)
      PushBlock(InverseBuy, R[i].low, R[i-2].high, true, i-1, R[i-1].time);
   if(R[i-2].low - R[i].high > atr * 0.1 && ArraySize(InverseSell) < 40)
      PushBlock(InverseSell, R[i-2].low, R[i].high, false, i-1, R[i-1].time);

   for(int k = ArraySize(InverseBuy) - 1; k >= 0; k--)
   {
      if(InverseBuy[k].used) continue;
      if(i - InverseBuy[k].bar > 80) { InverseBuy[k].used = true; continue; }
      if(i - InverseBuy[k].bar > 1 && R[i].close < InverseBuy[k].bottom)
      { FromBlock(s, InverseBuy[k], 0, false, i); InverseBuy[k].used = true; break; }
   }
   if(!s.valid)
   {
      for(int k = ArraySize(InverseSell) - 1; k >= 0; k--)
      {
         if(InverseSell[k].used) continue;
         if(i - InverseSell[k].bar > 80) { InverseSell[k].used = true; continue; }
         if(i - InverseSell[k].bar > 1 && R[i].close > InverseSell[k].top)
         { FromBlock(s, InverseSell[k], 0, true, i); InverseSell[k].used = true; break; }
      }
   }
   TrimBlocks(InverseBuy, 30);
   TrimBlocks(InverseSell, 30);
}

void DetectCRT(const int i, const double atr, const bool breakUp, const bool breakDown, Signal &s)
{
   if(i < 3) return;
   for(int side = 0; side < 2; side++)
   {
      bool buy = (side == 0);
      int pivot = buy ? HighBar : LowBar;
      if(!(buy ? breakUp : breakDown) || pivot <= 0 || pivot >= ArraySize(R) || ArraySize(CrtBlocks) >= 25) continue;
      int start = pivot;
      for(int j = pivot; j >= MathMax(0, pivot - 8); j--)
         if(buy ? Bear(j) : Bull(j)) { start = j; break; }
      PushBlock(CrtBlocks, R[start].high, R[start].low, buy, i, R[MathMax(0, i-3)].time);
   }
   for(int k = ArraySize(CrtBlocks) - 1; k >= 0; k--)
   {
      if(CrtBlocks[k].used) continue;
      int age = i - CrtBlocks[k].bar;
      if(age > InpRetestBars) { CrtBlocks[k].used = true; continue; }
      if(age <= 1) continue;
      double hi = CrtBlocks[k].top, lo = CrtBlocks[k].bottom;
      bool ok = CrtBlocks[k].buy ? (R[i].low <= hi + atr * 0.3 && R[i].low >= lo - atr * 0.3 && R[i].close > lo)
                                 : (R[i].high >= lo - atr * 0.3 && R[i].high <= hi + atr * 0.3 && R[i].close < hi);
      if(ok) { FromBlock(s, CrtBlocks[k], 1, CrtBlocks[k].buy, i); CrtBlocks[k].used = true; break; }
   }
   TrimBlocks(CrtBlocks, 20);
}

void DetectOB(const int i, const double atr, Signal &s, const int id=2)
{
   if(i < InpOBSearchDepth + (id == 10 ? 3 : 2)) return;
   if(id == 10 && !Killzone(i)) return;
   double threshold = (id == 10) ? 0.8 : 1.0;
   if(Body(i) < atr * threshold || (!Bull(i) && !Bear(i))) return;
   bool buy = Bull(i);
   for(int j = i - 1; j >= MathMax(0, i - InpOBSearchDepth); j--)
   {
      if(id == 10 && !Killzone(j)) continue;
      if(!(buy ? Bear(j) : Bull(j)) || Body(j) <= _Point) continue;
      if(Body(j) / MathMax(_Point, Range(j)) < InpMinBodyRatio) continue;
      MakeSignal(s, id, buy, i, j, ZoneHigh(j), ZoneLow(j), (id == 2 && Body(i) >= 1.5 * atr) ? 1.3 : 1.0);
      return;
   }
}

void DetectFlip(const int i, const double atr, Signal &s, Block &blocks[], const int id)
{
   if(i < InpOBSearchDepth + (id == 7 ? 3 : 2)) return;
   if(Body(i) >= atr * 0.8 && (Bull(i) || Bear(i)))
   {
      bool buy = Bull(i);
      for(int j = i - 1; j >= MathMax(0, i - InpOBSearchDepth); j--)
      {
         if(!(buy ? Bear(j) : Bull(j))) continue;
         if(id == 7 && Body(j) / MathMax(_Point, Range(j)) < InpMinBodyRatio * 0.7) continue;
         PushBlock(blocks, ZoneHigh(j), ZoneLow(j), buy, j, R[j].time);
         break;
      }
   }
   for(int k = ArraySize(blocks) - 1; k >= 0; k--)
   {
      if(blocks[k].used) continue;
      if(i - blocks[k].bar > 500) { blocks[k].used = true; continue; }
      if(!blocks[k].flipped)
      {
         if(blocks[k].buy ? (R[i].close < blocks[k].bottom) : (R[i].close > blocks[k].top))
            blocks[k].flipped = true;
         continue;
      }
      bool buy = !blocks[k].buy;
      bool ok = buy ? (R[i].low <= blocks[k].top && (id == 3 ? R[i].close >= blocks[k].bottom : R[i].close > blocks[k].bottom))
                    : (R[i].high >= blocks[k].bottom && (id == 3 ? R[i].close <= blocks[k].top : R[i].close < blocks[k].top));
      if(ok) { FromBlock(s, blocks[k], id, buy, i); blocks[k].used = true; break; }
   }
   TrimBlocks(blocks, 60);
}

void DetectPropulsion(const int i, const double atr, Signal &s)
{
   if(i < InpOBSearchDepth + 3) return;
   bool buy = R[i].low > R[i-2].high, sell = R[i].high < R[i-2].low;
   if((!buy && !sell) || Body(i) < atr || !(buy ? Bull(i) : Bear(i))) return;
   double hi = buy ? R[i].low : R[i-2].low, lo = buy ? R[i-2].high : R[i].high;
   for(int j = i - 1; j >= MathMax(0, i - InpOBSearchDepth); j--)
   {
      if(!(buy ? Bear(j) : Bull(j))) continue;
      double top = MathMax(hi, ZoneHigh(j)), bottom = MathMin(lo, ZoneLow(j));
      if(bottom < top) { MakeSignal(s, 4, buy, i, j, top, bottom); return; }
   }
}

void DetectVacuum(const int i, const double atr, Signal &s)
{
   if(i < 3) return;
   if(R[i].low - R[i-1].high >= atr * 0.25)
      MakeSignal(s, 5, true, i, i-1, R[i].low, R[i-1].high);
   else if(R[i-1].low - R[i].high >= atr * 0.25)
      MakeSignal(s, 5, false, i, i-1, R[i-1].low, R[i].high);
}

void DetectUnicorn(const int i, const double atr, const bool up, const bool down, Signal &s)
{
   if(i < 4) return;
   for(int side = 0; side < 2; side++)
   {
      bool buy = (side == 0);
      double pivot = buy ? SwingHigh : SwingLow;
      if(!(buy ? up : down) || pivot <= 0) continue;
      for(int j = i; j >= MathMax(2, i - 4); j--)
      {
         double hi = buy ? R[j].low : R[j-2].low, lo = buy ? R[j-2].high : R[j].high;
         if(hi > lo && MathAbs((hi + lo) * 0.5 - pivot) <= atr * 1.5)
         { MakeSignal(s, 6, buy, i, j-2, hi, lo); return; }
      }
   }
}

void DetectFVG(const int i, const double atr, Signal &s)
{
   if(i < 5) return;
   if(R[i-1].low - R[i-3].high > atr * 0.2) PushBlock(GapBlocks, R[i-1].low, R[i-3].high, true, i-2, R[i-2].time);
   if(R[i-3].low - R[i-1].high > atr * 0.2) PushBlock(GapBlocks, R[i-3].low, R[i-1].high, false, i-2, R[i-2].time);
   for(int k = ArraySize(GapBlocks) - 1; k >= 0; k--)
   {
      if(GapBlocks[k].used) continue;
      int age = i - GapBlocks[k].bar;
      if(age > 40) { GapBlocks[k].used = true; continue; }
      if(age <= 1) continue;
      bool buy = GapBlocks[k].buy;
      bool ok = buy ? (R[i].low <= GapBlocks[k].top && R[i].close > GapBlocks[k].bottom && Bull(i))
                    : (R[i].high >= GapBlocks[k].bottom && R[i].close < GapBlocks[k].top && Bear(i));
      if(ok) { FromBlock(s, GapBlocks[k], 8, buy, i); GapBlocks[k].used = true; break; }
   }
   TrimBlocks(GapBlocks, 70);
}

void DetectBPR(const int i, const double atr, Signal &s)
{
   if(i < 5) return;
   if(R[i-1].low > R[i-3].high) PushBlock(BprBlocks, R[i-1].low, R[i-3].high, true, i-2, R[i-2].time);
   if(R[i-1].high < R[i-3].low) PushBlock(BprBlocks, R[i-3].low, R[i-1].high, false, i-2, R[i-2].time);
   int n = ArraySize(BprBlocks);
   for(int k = n - 1; k >= MathMax(0, n - 20) && !s.valid; k--)
   {
      if(BprBlocks[k].used) continue;
      if(i - BprBlocks[k].bar > 25) { BprBlocks[k].used = true; continue; }
      for(int j = k - 2; j >= MathMax(0, k - 16); j--)
      {
         if(BprBlocks[j].used || BprBlocks[j].buy == BprBlocks[k].buy) continue;
         double top = MathMin(BprBlocks[k].top, BprBlocks[j].top);
         double bottom = MathMax(BprBlocks[k].bottom, BprBlocks[j].bottom);
         if(top <= bottom) continue;
         bool buy = BprBlocks[k].buy;
         bool ok = buy ? (R[i].low <= top + atr * 0.3 && R[i].close > bottom)
                       : (R[i].high >= bottom - atr * 0.3 && R[i].close < top);
         if(ok)
         {
            MakeSignal(s, 9, buy, i, BprBlocks[j].bar, top, bottom);
            BprBlocks[j].used = true; BprBlocks[k].used = true;
            break;
         }
      }
   }
   TrimBlocks(BprBlocks, 100);
}

void DetectCE(const int i, const double atr, Signal &s)
{
   if(i < 6) return;
   for(int j = i - 3; j >= MathMax(2, i - 20); j--)
   {
      double hi = R[j].low, lo = R[j-2].high, mid = (hi + lo) * 0.5;
      if(hi > lo && hi - lo >= atr * 0.2 && R[i].low <= mid + atr * 0.15 && R[i].low >= lo - atr * 0.15 && R[i].close > mid && Bull(i))
      { MakeSignal(s, 11, true, i, j, hi, mid - atr * 0.1); return; }

      hi = R[j-2].low; lo = R[j].high; mid = (hi + lo) * 0.5;
      if(hi > lo && hi - lo >= atr * 0.2 && R[i].high >= mid - atr * 0.15 && R[i].high <= hi + atr * 0.15 && R[i].close < mid && Bear(i))
      { MakeSignal(s, 11, false, i, j, mid + atr * 0.1, lo); return; }
   }
}

void SwingExtremes(const int i, double &hi, double &lo, int &ih, int &il)
{
   hi = 0.0; lo = DBL_MAX; ih = -1; il = -1;
   int startJ = i - InpPivotLen;
   int minJ   = MathMax(InpPivotLen, i - InpSwingLookback);
   for(int j = startJ; j >= minJ; j--)
   {
      double h = PivotHigh(j, InpPivotLen, i);
      double l = PivotLow(j, InpPivotLen, i);
      if(h > 0 && h > hi) { hi = h; ih = j; }
      if(l > 0 && l < lo) { lo = l; il = j; }
   }
}

void DetectSFP(const int i, const double atr, Signal &s)
{
   if(i < InpSwingLookback + InpPivotLen + 2) return;
   double hi, lo; int ih, il;
   SwingExtremes(i, hi, lo, ih, il);
   double uw = UpperWick(i), lw = LowerWick(i), body = Body(i);
   if(hi > 0 && R[i].high > hi && R[i].close < hi && R[i].open < hi && uw > body * 0.5 && uw > atr * 0.2)
      MakeSignal(s, 12, false, i, i, R[i].high, MathMax(R[i].open, R[i].close), uw > atr * 0.5 ? 1.3 : 1.0);
   else if(il >= 0 && R[i].low < lo && R[i].close > lo && R[i].open > lo && lw > body * 0.5 && lw > atr * 0.2)
      MakeSignal(s, 12, true, i, i, MathMin(R[i].open, R[i].close), R[i].low, lw > atr * 0.5 ? 1.3 : 1.0);
}

void DetectRejection(const int i, const double atr, Signal &s)
{
   if(i < InpSwingLookback + 2 || Range(i) < atr * 0.5) return;
   double hi = 0.0, lo = DBL_MAX;
   for(int j = i - 1; j >= MathMax(0, i - InpSwingLookback); j--)
   { hi = MathMax(hi, R[j].high); lo = MathMin(lo, R[j].low); }

   double uw = UpperWick(i), lw = LowerWick(i), body = Body(i), range = Range(i);
   if(uw > range * 0.5 && uw > body * 1.5 && R[i].high >= hi - atr * 0.3)
      MakeSignal(s, 13, false, i, i, R[i].high, MathMax(R[i].open, R[i].close), uw > range * 0.65 ? 1.2 : 1.0);
   else if(lw > range * 0.5 && lw > body * 1.5 && R[i].low <= lo + atr * 0.3)
      MakeSignal(s, 13, true, i, i, MathMin(R[i].open, R[i].close), R[i].low, lw > range * 0.65 ? 1.2 : 1.0);
}

void DetectSupplyDemand(const int i, const double atr, Signal &s)
{
   if(i < 6) return;
   if(Body(i) >= atr * 0.8 && (Bull(i) || Bear(i)))
   {
      for(int j = i - 1; j >= MathMax(0, i - 5); j--)
         if(Body(j) < atr * 0.3)
         {

            PushBlock(SdBlocks, R[j].high, R[j].low, Bull(i), j, R[j].time);
            break;
         }
   }
   for(int k = ArraySize(SdBlocks) - 1; k >= 0; k--)
   {
      if(SdBlocks[k].used) continue;
      if(i - SdBlocks[k].bar > 200) { SdBlocks[k].used = true; continue; }
      if(!SdBlocks[k].flipped)
      {
         if(SdBlocks[k].buy  && R[i].close < SdBlocks[k].bottom) SdBlocks[k].flipped = true;
         if(!SdBlocks[k].buy && R[i].close > SdBlocks[k].top)    SdBlocks[k].flipped = true;
         continue;
      }

      bool buy = !SdBlocks[k].buy;
      bool ok = buy ? (R[i].low <= SdBlocks[k].top && R[i].close > SdBlocks[k].bottom)
                    : (R[i].high >= SdBlocks[k].bottom && R[i].close < SdBlocks[k].top);
      if(ok) { FromBlock(s, SdBlocks[k], 14, buy, i); SdBlocks[k].used = true; break; }
   }
   TrimBlocks(SdBlocks, 80);
}

void DetectWyckoff(const int i, const double atr, Signal &s)
{
   if(i < 25) return;
   int start = MathMax(0, i - 20);
   double hi = 0.0, lo = DBL_MAX;
   for(int j = start; j < i - 2; j++) { hi = MathMax(hi, R[j].high); lo = MathMin(lo, R[j].low); }
   double range = hi - lo;
   if(range < atr * 2.0 || range > atr * 8.0) return;

   double depth = lo - R[i].low;
   if(R[i].low < lo && R[i].close > lo && R[i].close < hi && depth > atr * 0.1 && depth < atr * 1.5)
      MakeSignal(s, 15, true, i, start, lo + range * 0.15, R[i].low, (depth > atr * 0.3 && Bull(i)) ? 1.3 : 1.0);
   else
   {
      depth = R[i].high - hi;
      if(R[i].high > hi && R[i].close < hi && R[i].close > lo && depth > atr * 0.1 && depth < atr * 1.5)
         MakeSignal(s, 15, false, i, start, R[i].high, hi - range * 0.15, (depth > atr * 0.3 && Bear(i)) ? 1.3 : 1.0);
   }
}

void DetectMSS(const int i, const double atr, Signal &s)
{
   if(i < InpSwingLookback + InpPivotLen + 5) return;
   double hi, lo; int ih, il;
   SwingExtremes(i, hi, lo, ih, il);
   if(il > 0 && Bull(i) && Body(i) > atr && R[i].close > lo)
      for(int j = i - 1; j >= MathMax(il + 1, i - 8); j--)
         if(R[j].low < lo) { MakeSignal(s, 16, true, i, il, lo + atr * 0.3, lo - atr * 0.3, Body(i) > atr * 1.5 ? 1.3 : 1.0); return; }

   if(ih > 0 && Bear(i) && Body(i) > atr && R[i].close < hi)
      for(int j = i - 1; j >= MathMax(ih + 1, i - 8); j--)
         if(R[j].high > hi) { MakeSignal(s, 16, false, i, ih, hi + atr * 0.3, hi - atr * 0.3, Body(i) > atr * 1.5 ? 1.3 : 1.0); return; }
}

ENUM_TIMEFRAMES SelectedTimeframe()
{
   ENUM_TIMEFRAMES tf[10]={

Показано первые 50% кода (символов: 39093)