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

Fibonacci Pullback and Reversal Zones

fibpullbackreversal.mq5
Вы автор или правообладатель?

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

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

О программе

Fibonacci Pullback and Reversal Zones — это пользовательский индикатор для MetaTrader 5, портированный с Pine Script v6 (оригинал BullByte). Индикатор рассчитывает аналитические уровни Фибоначчи на основе импульсных движений цены, определяемых через пороги ATR.

Основная логика строится на обнаружении свинговых точек A и B: при достижении импульсом минимальной длины и эффективности строится карта Фибоначчи, включающая зону откатов, две зоны разворота и целевые уровни. Все расчёты выполняются на закрытых свечах.

Индикатор реализует машины состояний для подтверждения сигналов, моделирует сделки с расчётом стоп-лосса и тейк-профитов от открытия следующей свечи, управляет позицией (переход в безубыток, фиксация прибыли) и поддерживает оповещения. На графике отображаются зоны, маркеры сигналов, уровни сделок и информационная панель.

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

НастройкаОписание
Notice Текстовое предупреждение о рисках торговли.
SimpleForexTeam__ Текстовая ссылка на канал автора.
InpSwingMode Режим обнаружения свингов: отзывчивый (1.5 ATR), сбалансированный (2.0 ATR), структурный (3.5 ATR) или пользовательский.
InpCustomRevAtr Множитель ATR для пользовательского режима разворота свинга (Custom Swing Reversal).
InpAtrLength Период расчёта индикатора ATR (ATR Length).
InpMinImpulseAtr Минимальная длина импульса A–B в долях ATR (Minimum A-B Impulse).
InpMinEfficiency Минимальная направленная эффективность свинга (Minimum Swing Directional Efficiency).
InpRequireBreak Требовать новый свинговый пробой для обновления карты (Require New Swing Break).
InpMaxSwingBars Максимальное количество баров между точками A и B (20–1500).
InpPbLower Нижнее соотношение зоны отката (Pullback Lower Ratio).
InpPbUpper Верхнее соотношение зоны отката (Pullback Upper Ratio).
InpR1Lower Нижнее соотношение зоны разворота 1 (Reversal 1 Lower Ratio).
InpR1Upper Верхнее соотношение зоны разворота 1 (Reversal 1 Upper Ratio).
InpR2Lower Нижнее соотношение зоны разворота 2 (Reversal 2 Lower Ratio).
InpR2Upper Верхнее соотношение зоны разворота 2 (Reversal 2 Upper Ratio).
InpPbT1Ratio Целевой уровень 1 для отката (Pullback Target 1 Ratio).
InpPbT2Ratio Целевой уровень 2 для отката (Pullback Target 2 Ratio).
InpR1T1Ratio Целевой уровень 1 для разворота 1 (Reversal 1 Target 1 Ratio).
InpR1T2Ratio Целевой уровень 2 для разворота 1 (Reversal 1 Target 2 Ratio).
InpR2T1Ratio Целевой уровень 1 для разворота 2 (Reversal 2 Target 1 Ratio).
InpR2T2Ratio Целевой уровень 2 для разворота 2 (Reversal 2 Target 2 Ratio).
InpBoT1Ratio Целевой уровень 1 для прорыва (Breakout Target 1 Ratio).
InpBoT2Ratio Целевой уровень 2 для прорыва (Breakout Target 2 Ratio).
InpEnablePullback Включить сигналы отката (Pullback).
InpEnableRev1 Включить сигналы разворота 1 (Reversal 1).
InpEnableRev2 Включить сигналы разворота 2 (Reversal 2).
InpEnableBreakout Включить сигналы прорыва (Extension Breakout).
InpPbConfirm Метод подтверждения отката: восстановление зоны или восстановление + микропрорыв.
InpRvConfirm Метод подтверждения разворота: отклонение зоны, микропрорыв или ликвидность + отклонение + микропрорыв.
InpMicroLookback Количество баров для поиска микроструктуры (Micro Structure Lookback, 2–50).
InpLiqLookback Количество баров для поиска ликвидности (Liquidity Sweep Lookback, 2–50).
InpBoRetestExpiry Срок действия ретеста прорыва в баров (Breakout Retest Expiry).
InpBoRetestTolAtr Допустимое отклонение для ретеста прорыва в долях ATR (Breakout Retest Tolerance).
InpAcceptCloses Количество закрытий свечей за пределами зоны для принятия сигнала (1–5).
InpPbExpiry Срок действия настройки отката в баров (Pullback Setup Expiry).
InpRvExpiry Срок действия настройки разворота в баров (Reversal Setup Expiry).
InpReqSignalCandle Требовать направленную сигнальную свечу (бычью или медвежью) для подтверждения.
InpReqStrongClose Требовать сильное закрытие свечи в направлении сигнала.
InpMinCloseStrength Минимальная сила закрытия сигнальной свечи (0.50–0.95).
InpMinPbRR Минимальное соотношение риск/прибыль для отката (Minimum Pullback R:R).
InpMinRvRR Минимальное соотношение риск/прибыль для разворота (Minimum Reversal R:R).
InpMinBoRR Минимальное соотношение риск/прибыль для прорыва (Minimum Breakout R:R).
InpSlMode Основа для расчёта стоп-лосса: структурный уровень или ATR.
InpStructBufAtr Буфер структуры в долях ATR (Structure Buffer).
InpInvalidAtr Расстояние стоп-лосса в долях ATR (Stop-Loss Distance).
InpTpMode Основа для расчёта тейк-профита: уровни Фибоначчи или ATR.
InpT1Atr Расстояние целевого уровня 1 в долях ATR (Target 1 Distance).
InpT2Atr Расстояние целевого уровня 2 в долях ATR (Target 2 Distance).
InpMoveToBE Перевести стоп-лосс в безубыток после достижения целевого уровня 1.
InpAtrFallback Использовать целевые уровни ATR, если уровни Фибоначчи не подходят.
InpHistTrades Количество сохраняемых исторических сделок (0–40).
InpContPolicy Политика при подтверждении продолжения во время разворота (Continue Reversal / Close Reversal & Take Continuation).
InpShowMap Отображать активную карту Фибоначчи.
InpShowZoneLabels Отображать полные подписи зон.
InpShowSwingMarks Отображать маркеры свинговых точек A и B.
InpShowSignals Отображать маркеры принятых сигналов.
InpShowTradeLevels Отображать уровни текущей сделки на графике.
InpShowTradeLabels Отображать подписи входа, стоп-лосса и тейк-профита.
InpShowHistLevels Отображать линии исторических уровней входа, стоп-лосса и тейк-профита.
InpShowHistBoxes Отображать фоновые прямоугольники риска/прибыли для исторических сделок.
InpShowPanel Отображать информационную панель (дашборд) на графике.
InpPanelPos Положение информационной панели на графике (верхний левый, верхний правый, нижний левый, нижний правый угол).
InpZoneLabelOffset Сдвиг подписей Фибоначчи вправо от текущего бара в баров.
InpTradeLabelGap Отступ подписей сделки от подписей Фибоначчи в баров.
InpZoneTransp Прозрачность заливки зон.
InpHistTransp Прозрачность прошлых сделок (70–99).
InpMajorColor Цвет основных свинговых маркеров.
InpPullbackColor Цвет зоны отката.
InpRev1Color Цвет зоны разворота 1.
InpRev2Color Цвет зоны разворота 2.
InpLongColor Цвет сигналов на покупку.
InpShortColor Цвет сигналов на продажу.
InpEntryColor Цвет уровня входа в сделку.
InpTargetColor Цвет целевых уровней.
InpInvalidColor Цвет уровня инвалидации (стоп-лосса).
InpAlertSetups Включить оповещение при подтверждении сигнала (откат / разворот / прорыв).
InpAlertEntry Включить оповещение при открытии смоделированной сделки.
InpAlertRejected Включить оповещение при отклонении входа на следующей свече (недопустимый стоп, таргет или R:R).
InpAlertTargets Включить оповещение при достижении целевых уровней 1 и 2.
InpAlertInvalid Включить оповещение при достижении уровня стоп-лосса.
InpAlertReplaced Включить оповещение при замене текущей сделки новым сигналом.
InpAlertPopup Включить всплывающее оповещение на графике.
InpAlertPush Включить отправку push-уведомлений.
InpAlertEmail Включить отправку уведомлений по электронной почте.
InpFont Шрифт для отображения графических элементов (требуются треугольные символы).
InpMaxBars Максимальное количество баров для расчёта (0 — все бары).

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

#property version     "1.02"
#property description "Fibonacci Pullback and Reversal Zones: ATR-reversal swings, A-B Fibonacci map, pullback /"
#property description "reversal / breakout setups, next-bar-open trade model with targets. Closed-bar logic, EA buffers."
#property indicator_chart_window
#property indicator_buffers 25
#property indicator_plots   23

enum ENUM_FB_MODE
{
   SM_RESPONSIVE = 0, // Responsive
   SM_BALANCED   = 1, // Balanced
   SM_STRUCTURAL = 2, // Structural
   SM_CUSTOM     = 3  // Custom
};

enum ENUM_FB_PBCONF
{
   PC_RECLAIM = 0, // Zone Reclaim
   PC_MICRO   = 1  // Reclaim + Micro Break
};

enum ENUM_FB_RVCONF
{
   RC_REJECT = 0, // Zone Rejection
   RC_MICRO  = 1, // Rejection + Micro Break
   RC_SWEEP  = 2  // Sweep + Reclaim + Micro Break
};

enum ENUM_FB_SL
{
   SLB_STRUCTURE = 0, // Structure
   SLB_ATR       = 1  // ATR
};

enum ENUM_FB_TP
{
   TPB_FIB = 0, // Fibonacci
   TPB_ATR = 1  // ATR
};

enum ENUM_FB_POLICY
{
   PL_CONTINUE = 0, // Continue Reversal Until Exit
   PL_REPLACE  = 1  // Close Reversal & Take Continuation
};

enum ENUM_FB_POS
{
   PP_TL = 0, // Top Left
   PP_TR = 1, // Top Right
   PP_BL = 2, // Bottom Left
   PP_BR = 3  // Bottom Right
};
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 "1. Swing Selection"
input ENUM_FB_MODE   InpSwingMode       = SM_BALANCED;   // Mode (Responsive 1.5 / Balanced 2.0 / Structural 3.5 ATR)
input double         InpCustomRevAtr    = 2.5;           // Custom Swing Reversal (x ATR)
input int            InpAtrLength       = 14;            // ATR Length
input double         InpMinImpulseAtr   = 1.0;           // Minimum A-B Impulse (x ATR)
input double         InpMinEfficiency   = 0.15;          // Minimum Swing Directional Efficiency
input bool           InpRequireBreak    = true;          // Require New Swing Break To Refresh Map
input int            InpMaxSwingBars    = 800;           // Maximum Bars Between A and B (20-1500)

input group "2. Original Fibonacci Zones"
input double         InpPbLower         = 0.500;         // Pullback Lower Ratio
input double         InpPbUpper         = 0.618;         // Pullback Upper Ratio
input double         InpR1Lower         = 1.414;         // Reversal 1 Lower Ratio
input double         InpR1Upper         = 1.618;         // Reversal 1 Upper Ratio
input double         InpR2Lower         = 2.000;         // Reversal 2 Lower Ratio
input double         InpR2Upper         = 2.272;         // Reversal 2 Upper Ratio
input double         InpPbT1Ratio       = 1.000;         // Pullback Target 1 Ratio
input double         InpPbT2Ratio       = 1.272;         // Pullback Target 2 Ratio
input double         InpR1T1Ratio       = 1.000;         // Reversal 1 Target 1 Ratio
input double         InpR1T2Ratio       = 0.618;         // Reversal 1 Target 2 Ratio
input double         InpR2T1Ratio       = 1.618;         // Reversal 2 Target 1 Ratio
input double         InpR2T2Ratio       = 1.000;         // Reversal 2 Target 2 Ratio
input double         InpBoT1Ratio       = 2.000;         // Breakout Target 1 Ratio
input double         InpBoT2Ratio       = 2.618;         // Breakout Target 2 Ratio

input group "3. Independent Signal Toggles"
input bool           InpEnablePullback  = true;          // Enable Pullback Signals
input bool           InpEnableRev1      = true;          // Enable Reversal 1 Signals
input bool           InpEnableRev2      = true;          // Enable Reversal 2 Signals
input bool           InpEnableBreakout  = false;         // Enable Extension Breakout Signals

input group "4. Entry Confirmation"
input ENUM_FB_PBCONF InpPbConfirm       = PC_RECLAIM;    // Pullback Confirmation
input ENUM_FB_RVCONF InpRvConfirm       = RC_REJECT;     // Reversal Confirmation
input int            InpMicroLookback   = 3;             // Micro Structure Lookback (2-50)
input int            InpLiqLookback     = 8;             // Liquidity Sweep Lookback (2-50)
input int            InpBoRetestExpiry  = 20;            // Breakout Retest Expiry (bars)
input double         InpBoRetestTolAtr  = 0.25;          // Breakout Retest Tolerance (x ATR)
input int            InpAcceptCloses    = 2;             // Closes To Accept Beyond Zone (1-5)
input int            InpPbExpiry        = 30;            // Pullback Setup Expiry (bars)
input int            InpRvExpiry        = 100;           // Reversal Setup Expiry (bars)
input bool           InpReqSignalCandle = true;          // Require Directional Signal Candle
input bool           InpReqStrongClose  = false;         // Require Strong Close In Signal Direction
input double         InpMinCloseStrength = 0.60;         // Minimum Signal-Close Strength (0.50-0.95)
input double         InpMinPbRR         = 1.0;           // Minimum Pullback Setup R:R
input double         InpMinRvRR         = 1.0;           // Minimum Reversal Setup R:R
input double         InpMinBoRR         = 1.2;           // Minimum Breakout Setup R:R

input group "5. Trade Management"
input ENUM_FB_SL     InpSlMode          = SLB_STRUCTURE; // Stop-Loss Basis
input double         InpStructBufAtr    = 0.25;          // Structure Buffer (x ATR)
input double         InpInvalidAtr      = 1.5;           // Stop-Loss Distance (x ATR)
input ENUM_FB_TP     InpTpMode          = TPB_FIB;       // Target Basis
input double         InpT1Atr           = 1.5;           // Target 1 Distance (x ATR)
input double         InpT2Atr           = 3.0;           // Target 2 Distance (x ATR)
input bool           InpMoveToBE        = true;          // Move Invalidation To Breakeven After Target 1
input bool           InpAtrFallback     = true;          // Use ATR Targets If Fibonacci Targets Are Passed
input int            InpHistTrades      = 30;            // Historical Trades To Keep (0-40)
input ENUM_FB_POLICY InpContPolicy      = PL_CONTINUE;   // When Continuation Confirms During Reversal

input group "6. Display"
input bool           InpShowMap         = true;          // Show Active Fibonacci Map
input bool           InpShowZoneLabels  = true;          // Show Full Zone Labels
input bool           InpShowSwingMarks  = true;          // Show A/B Swing Markers
input bool           InpShowSignals     = true;          // Show Signal Markers
input bool           InpShowTradeLevels = true;          // Show Trade Levels
input bool           InpShowTradeLabels = true;          // Show Entry / SL / TP Labels
input bool           InpShowHistLevels  = true;          // Show Historical Entry / SL / TP Lines
input bool           InpShowHistBoxes   = true;          // Show Historical Risk / Reward Background
input bool           InpShowPanel       = true;          // Display Dashboard
input ENUM_FB_POS    InpPanelPos        = PP_TR;         // Panel Position
input int            InpZoneLabelOffset = 12;            // Fib Labels Start (bars right)
input int            InpTradeLabelGap   = 14;            // Trade Labels After Fib Labels (bars)
input int            InpZoneTransp      = 88;            // Zone Fill Transparency
input int            InpHistTransp      = 82;            // Past Trade Transparency (70-99)

input group "7. Colors"
input color          InpMajorColor      = C'120,123,134'; // Major Swing
input color          InpPullbackColor   = C'41,98,255';   // Pullback Zone
input color          InpRev1Color       = C'245,124,0';   // Reversal 1 Zone
input color          InpRev2Color       = C'142,36,170';  // Reversal 2 Zone
input color          InpLongColor       = C'8,153,129';   // Long Signals
input color          InpShortColor      = C'242,54,69';   // Short Signals
input color          InpEntryColor      = C'120,123,134'; // Entry Level
input color          InpTargetColor     = C'8,153,129';   // Target Levels
input color          InpInvalidColor    = C'242,54,69';   // Invalidation Level

input group "Alerts"
input bool           InpAlertSetups     = true;          // Alert: setup confirmed (pullback / reversal / breakout)
input bool           InpAlertEntry      = false;         // Alert: modeled entry opened
input bool           InpAlertRejected   = true;          // Alert: next-bar entry rejected
input bool           InpAlertTargets    = true;          // Alert: Target 1 / Target 2 reached
input bool           InpAlertInvalid    = true;          // Alert: invalidation reached
input bool           InpAlertReplaced   = false;         // Alert: trade replaced by a new setup
input bool           InpAlertPopup      = true;          // Popup alert
input bool           InpAlertPush       = false;         // Push notification
input bool           InpAlertEmail      = false;         // E-mail

input group "Calculation"
input string         InpFont            = "Segoe UI Symbol"; // Font (needs the triangle glyphs)
input int            InpMaxBars         = 0;             // Max bars to calculate (0 = all)

#define NA_BAR       LONG_MIN
#define MAX_MARKERS  150
#define SCAN_MAX     1999
#define TBL_PAD      6
#define C_PANEL_BG   C'30,34,45'      // #1E222D
#define C_PANEL_KEY  C'149,152,161'   // #9598A1
#define C_PANEL_TXT  C'209,212,220'   // #D1D4DC
#define C_PANEL_HDR  C'41,98,255'     // #2962FF

#define ST_PULLBACK  1
#define ST_REV1      2
#define ST_REV2      3
#define ST_BREAKOUT  4

struct ATrade
{
   bool   on;
   int    uid;
   int    dir;
   double entry;
   double inval;
   double boxSl;       // stop at entry (the risk box keeps it after break-even)
   double t1;
   double t2;
   string tag;
   bool   t1Hit;
   long   entryBar;
   bool   live;        // Show Trade Levels
   bool   hasLines;
   bool   hasBoxes;
   bool   hasLabels;
   double rr1;
   double rr2;
};

struct HTrade
{
   int    uid;
   long   x1;
   long   x2;
   double entry;
   double inval;
   double boxSl;
   double t1;
   double t2;
   bool   lines;
   bool   boxes;
   bool   created;
};

struct Marker
{
   int      uid;
   datetime t;
   double   y;
   string   txt;
   color    clr;
   bool     above;
   bool     created;
};

double b0[], b1[], b2[], b3[], b4[], b5[], b6[], b7[], b8[], b9[], b10[], b11[];
double b12[], b13[], b14[], b15[], b16[], b17[], b18[], b19[], b20[], b21[], b22[];
double g_cAtr[], g_cPath[];

string   g_prefix = "FIBPR_";
string   G_UP, G_DN, G_DOT, G_NDASH;
double   g_mult = 2.0;
double   g_tick = 0.01;
int      g_maxSwingBars = 800, g_microLb = 3, g_liqLb = 8, g_acceptCloses = 2, g_histKeep = 30, g_histTransp = 82;
int      g_periodSec = 60;
int      g_ratesTotal = 0;
bool     g_fullPass = true;
int      g_lastIdx = -1;
datetime g_lastTime = 0;
long     g_bi = -1;
long     g_baseIdx = 0;
int      g_uid = 0;
datetime g_time[];
int      g_timeN = 0;
bool     g_ratiosValid = true;

int      g_trackDir;
double   g_trackExt, g_trackExtAtr, g_trackExtPath;
long     g_trackExtBar;
double   g_lastSwingPrice, g_lastSwingAtr, g_lastSwingPath;
long     g_lastSwingBar;
double   g_lastStructHigh, g_lastStructLow;
bool     g_parentEverBuilt;
int      g_boState, g_boAcceptance;
long     g_boAcceptedBar;
double   g_boRetestExt;

double   g_pA, g_pB;
long     g_pBarA, g_pBarB, g_mapBar;
int      g_pDir;
bool     g_pActive;
double   g_pImpulseAtr, g_pEfficiency;
int      g_pInvalidCloses;

double   g_pbBot, g_pbTop;
int      g_pbState;
long     g_pbTouchBar, g_pbReclaimBar;
double   g_pbExt, g_pbMicro;
bool     g_pbUsed;

double   g_r1Bot, g_r1Top;
int      g_r1State;
long     g_r1TouchBar, g_r1ReclaimBar, g_r1RejBar;
double   g_r1Ext, g_r1Sweep, g_r1Micro;
bool     g_r1SweepSeen, g_r1ReclaimSeen, g_r1RejSeen;
int      g_r1Accept;

double   g_r2Bot, g_r2Top;
int      g_r2State;
long     g_r2TouchBar, g_r2ReclaimBar, g_r2RejBar;
double   g_r2Ext, g_r2Sweep, g_r2Micro;
bool     g_r2SweepSeen, g_r2ReclaimSeen, g_r2RejSeen;
int      g_r2Accept;

ATrade   g_tr;
bool     g_pendEntry;
long     g_pendSignalBar;
int      g_pendDir;
double   g_pendInval, g_pendMinRR, g_pendT1, g_pendT2, g_pendAtr;
string   g_pendTag;
string   g_coordStatus;

bool     g_mapDrawn = false;      // map objects exist (Show Active Fibonacci Map at build time)
bool     g_swingDrawn = false;
HTrade   g_hist[];
Marker   g_markers[];
string   g_panelSig = "";
double   g_lastPpp = 0.0;

template<typename T>
void PushBack(T &arr[], const T &value)
{
   const int n = ArraySize(arr);
   ArrayResize(arr, n + 1, 64);
   arr[n] = value;
}

template<typename T>
void RemoveAt(T &arr[], const int index)
{
   const int n = ArraySize(arr);
   if(index < 0 || index >= n)
      return;
   for(int k = index; k < n - 1; k++)
      arr[k] = arr[k + 1];
   ArrayResize(arr, n - 1);
}

bool   IsNa(const double v) { return (v == EMPTY_VALUE); }
long   LMax(const long a, const long b) { return (a > b) ? a : b; }
long   LMin(const long a, const long b) { return (a < b) ? a : b; }
double Fib(const double a, const double b, const double r) { return a + r * (b - a); }

color Blend(const color c, const color bg, const double a)
{
   const double aa = MathMax(0.0, MathMin(1.0, a));
   const int ci = (int)c;
   const int bi = (int)bg;
   const int r = (int)MathRound((ci & 0xFF) * aa + (bi & 0xFF) * (1.0 - aa));
   const int g = (int)MathRound(((ci >> 8) & 0xFF) * aa + ((bi >> 8) & 0xFF) * (1.0 - aa));
   const int b = (int)MathRound(((ci >> 16) & 0xFF) * aa + ((bi >> 16) & 0xFF) * (1.0 - aa));
   return (color)(r | (g << 8) | (b << 16));
}

color ChartBg() { return (color)ChartGetInteger(0, CHART_COLOR_BACKGROUND); }
color ChartFg() { return (color)ChartGetInteger(0, CHART_COLOR_FOREGROUND); }

color Tr(const color c, const double transp) { return Blend(c, ChartBg(), 1.0 - transp / 100.0); }

string Px(const double v) { return IsNa(v) ? "na" : DoubleToString(v, _Digits); }

string TfName() { return StringSubstr(EnumToString((ENUM_TIMEFRAMES)_Period), 7); }

void FireAlert(const string text)
{
   if(InpAlertPopup)
      Alert(text);
   if(InpAlertPush)
      SendNotification(StringSubstr(text, 0, 255));
   if(InpAlertEmail)
      SendMail("Fibonacci Pullback and Reversal Zones " + _Symbol, text);
}

double HighestPrev(const double &arr[], const int i, const int n)
{
   if(i - n < 0)
      return EMPTY_VALUE;
   double m = arr[i - 1];
   for(int k = 2; k <= n; k++)
      m = MathMax(m, arr[i - k]);
   return m;
}

double LowestPrev(const double &arr[], const int i, const int n)
{
   if(i - n < 0)
      return EMPTY_VALUE;
   double m = arr[i - 1];
   for(int k = 2; k <= n; k++)
      m = MathMin(m, arr[i - k]);
   return m;
}

string PbStateText(const int s)
{
   switch(s)
   {
      case 0: return "Armed";
      case 1: return "Touched";
      case 2: return "Confirming";
      case 3: return "Signalled";
      case 4: return "Expired";
      case 5: return "Filtered";
      default: break;
   }
   return "Inactive";
}

string RvStateText(const int s)
{
   switch(s)
   {
      case 0: return "Armed";
      case 1: return "Touched";
      case 2: return "Signalled";
      case 3: return "Invalidated";
      case 4: return "Expired";
      case 5: return "Filtered";
      default: break;
   }
   return "Inactive";
}

string BoStateText(const int s)
{
   switch(s)
   {
      case 0: return "Waiting";
      case 1: return "Accepted";
      case 2: return "Signalled";
      case 3: return "Failed";
      case 4: return "Expired";
      case 5: return "Filtered";
      default: break;
   }
   return "Inactive";
}

string ModeName()
{
   switch(InpSwingMode)
   {
      case SM_RESPONSIVE: return "Responsive";
      case SM_STRUCTURAL: return "Structural";
      case SM_CUSTOM:     return "Custom";
      default:            break;
   }
   return "Balanced";
}

string TradePrefix(const int uid) { return g_prefix + "AT" + IntegerToString(uid) + "_"; }
string HistPrefix(const int uid)  { return g_prefix + "H" + IntegerToString(uid) + "_"; }

void OpenTrade(const int dir, const double entry, const double inval, const double t1, const double t2, const string tag,
               const long bi)
{
   g_tr.on        = true;
   g_tr.uid       = ++g_uid;
   g_tr.dir       = dir;
   g_tr.entry     = entry;
   g_tr.inval     = inval;
   g_tr.boxSl     = inval;
   g_tr.t1        = t1;
   g_tr.t2        = t2;
   g_tr.tag       = tag;
   g_tr.t1Hit     = false;
   g_tr.entryBar  = bi;
   g_tr.live      = InpShowTradeLevels;
   g_tr.hasLines  = InpShowTradeLevels || InpShowHistLevels;
   g_tr.hasBoxes  = InpShowTradeLevels || InpShowHistBoxes;
   g_tr.hasLabels = InpShowTradeLevels && InpShowTradeLabels;
   const double risk = MathAbs(entry - inval);
   g_tr.rr1 = (risk > 0) ? MathAbs(t1 - entry) / risk : 0.0;
   g_tr.rr2 = (risk > 0) ? MathAbs(t2 - entry) / risk : 0.0;
}

void CloseTrade(const long closeBar)
{
   if(!g_tr.on)
      return;
   ObjectsDeleteAll(0, TradePrefix(g_tr.uid));
   const bool kl = InpShowHistLevels && g_tr.hasLines;
   const bool kb = InpShowHistBoxes && g_tr.hasBoxes;
   if(kl || kb)
   {
      HTrade h;
      h.uid     = g_tr.uid;
      h.x1      = g_tr.entryBar;
      h.x2      = LMax(closeBar, g_tr.entryBar + 1);
      h.entry   = g_tr.entry;
      h.inval   = g_tr.inval;
      h.boxSl   = g_tr.boxSl;
      h.t1      = g_tr.t1;
      h.t2      = g_tr.t2;
      h.lines   = kl;
      h.boxes   = kb;
      h.created = false;
      PushBack(g_hist, h);
   }
   while(ArraySize(g_hist) > g_histKeep)
   {
      ObjectsDeleteAll(0, HistPrefix(g_hist[0].uid));
      RemoveAt(g_hist, 0);
   }
   g_tr.on = false;
}

void ResetState()
{
   g_trackDir = 1;
   g_trackExt = EMPTY_VALUE;
   g_trackExtBar = NA_BAR;
   g_trackExtAtr = EMPTY_VALUE;
   g_trackExtPath = EMPTY_VALUE;
   g_lastSwingPrice = EMPTY_VALUE;
   g_lastSwingBar = NA_BAR;
   g_lastSwingAtr = EMPTY_VALUE;
   g_lastSwingPath = EMPTY_VALUE;
   g_lastStructHigh = EMPTY_VALUE;
   g_lastStructLow = EMPTY_VALUE;
   g_parentEverBuilt = false;
   g_boState = 0;
   g_boAcceptance = 0;
   g_boAcceptedBar = NA_BAR;
   g_boRetestExt = EMPTY_VALUE;

   g_pA = EMPTY_VALUE;
   g_pB = EMPTY_VALUE;
   g_pBarA = NA_BAR;
   g_pBarB = NA_BAR;
   g_mapBar = NA_BAR;
   g_pDir = 0;
   g_pActive = false;
   g_pImpulseAtr = EMPTY_VALUE;
   g_pEfficiency = EMPTY_VALUE;
   g_pInvalidCloses = 0;

   g_pbBot = EMPTY_VALUE;
   g_pbTop = EMPTY_VALUE;
   g_pbState = 6;
   g_pbTouchBar = NA_BAR;
   g_pbExt = EMPTY_VALUE;
   g_pbReclaimBar = NA_BAR;
   g_pbMicro = EMPTY_VALUE;
   g_pbUsed = false;

   g_r1Bot = EMPTY_VALUE;
   g_r1Top = EMPTY_VALUE;
   g_r1State = 6;
   g_r1TouchBar = NA_BAR;
   g_r1Ext = EMPTY_VALUE;
   g_r1Sweep = EMPTY_VALUE;
   g_r1SweepSeen = false;
   g_r1ReclaimSeen = false;
   g_r1ReclaimBar = NA_BAR;
   g_r1RejSeen = false;
   g_r1RejBar = NA_BAR;
   g_r1Micro = EMPTY_VALUE;
   g_r1Accept = 0;

   g_r2Bot = EMPTY_VALUE;
   g_r2Top = EMPTY_VALUE;
   g_r2State = 6;
   g_r2TouchBar = NA_BAR;
   g_r2Ext = EMPTY_VALUE;
   g_r2Sweep = EMPTY_VALUE;
   g_r2SweepSeen = false;
   g_r2ReclaimSeen = false;
   g_r2ReclaimBar = NA_BAR;
   g_r2RejSeen = false;
   g_r2RejBar = NA_BAR;
   g_r2Micro = EMPTY_VALUE;
   g_r2Accept = 0;

   g_tr.on = false;
   g_pendEntry = false;
   g_pendSignalBar = NA_BAR;
   g_pendDir = 0;
   g_pendInval = EMPTY_VALUE;
   g_pendMinRR = EMPTY_VALUE;
   g_pendT1 = EMPTY_VALUE;
   g_pendT2 = EMPTY_VALUE;
   g_pendAtr = EMPTY_VALUE;
   g_pendTag = "";
   g_coordStatus = "Waiting for setup";

   g_mapDrawn = false;
   g_swingDrawn = false;
   ArrayResize(g_hist, 0);
   ArrayResize(g_markers, 0);
   g_panelSig = "";
   g_lastPpp = 0.0;
   g_lastIdx = -1;
   g_lastTime = 0;
}

void ClearBarBuffers(const int i)
{
   b0[i] = EMPTY_VALUE;  b1[i] = EMPTY_VALUE;  b2[i] = EMPTY_VALUE;  b3[i] = EMPTY_VALUE;
   b4[i] = EMPTY_VALUE;  b5[i] = EMPTY_VALUE;  b6[i] = EMPTY_VALUE;  b7[i] = EMPTY_VALUE;
   b8[i] = EMPTY_VALUE;  b9[i] = EMPTY_VALUE;  b10[i] = EMPTY_VALUE; b11[i] = EMPTY_VALUE;
   b12[i] = EMPTY_VALUE; b13[i] = EMPTY_VALUE; b14[i] = EMPTY_VALUE; b15[i] = EMPTY_VALUE;
   b16[i] = EMPTY_VALUE; b17[i] = EMPTY_VALUE; b18[i] = EMPTY_VALUE; b19[i] = EMPTY_VALUE;
   b20[i] = EMPTY_VALUE; b21[i] = EMPTY_VALUE; b22[i] = EMPTY_VALUE;
}

void AddMarker(const datetime t, const double y, const string txt, const color clr, const bool above)
{
   Marker m;
   m.uid     = ++g_uid;
   m.t       = t;
   m.y       = y;
   m.txt     = txt;
   m.clr     = clr;
   m.above   = above;
   m.created = false;
   PushBack(g_markers, m);
   while(ArraySize(g_markers) > MAX_MARKERS)
   {
      ObjectDelete(0, g_prefix + "K" + IntegerToString(g_markers[0].uid) + "_");
      RemoveAt(g_markers, 0);
   }
}

double AtrStop(const int dir, const double base, const double atr) { return (dir == 1) ? base - InpInvalidAtr * atr : base + InpInvalidAtr * atr; }
double AtrT1(const int dir, const double base, const double atr)   { return (dir == 1) ? base + InpT1Atr * atr : base - InpT1Atr * atr; }
double AtrT2(const int dir, const double base, const double atr)   { return (dir == 1) ? base + InpT2Atr * atr : base - InpT2Atr * atr; }

bool TargetsAhead(const int dir, const double c, const double t1, const double t2)
{
   return (dir == 1) ? (t1 > c && t2 > t1) : (t1 < c && t2 < t1);
}

void ProcessBar(const int i, const datetime &time[], const double &open[], const double &high[], const double &low[],
                const double &close[])
{
   g_bi++;
   const long     bi   = g_bi;
   g_baseIdx = i - bi;
   const datetime t    = time[i];
   const double   o    = open[i];
   const double   h    = high[i];
   const double   l    = low[i];
   const double   c    = close[i];
   const bool     live = (!g_fullPass && i == g_ratesTotal - 2);
   ClearBarBuffers(i);

   const double atrValue    = g_cAtr[i];
   const double cumPath     = g_cPath[i];
   const double candleRange = h - l;
   const bool   strongBullClose = candleRange > 0 && (c - l) / candleRange >= InpMinCloseStrength;
   const bool   strongBearClose = candleRange > 0 && (h - c) / candleRange >= InpMinCloseStrength;
   const bool   bullCandleOk = !InpReqSignalCandle || c > o;
   const bool   bearCandleOk = !InpReqSignalCandle || c < o;
   const bool   bullCloseOk  = !InpReqStrongClose || strongBullClose;
   const bool   bearCloseOk  = !InpReqStrongClose || strongBearClose;
   const double priorLiqHigh = HighestPrev(high, i, g_liqLb);
   const double priorLiqLow  = LowestPrev(low, i, g_liqLb);
   const double microHigh    = HighestPrev(high, i, g_microLb);
   const double microLow     = LowestPrev(low, i, g_microLb);

   bool   pbLong = false, pbShort = false, r1Long = false, r1Short = false, r2Long = false, r2Short = false, boLong = false, boShort = false;
   bool   entryRejected = false, entryAccepted = false, tradeReplaced = false, t1Event = false, t2Event = false, invalidEvent = false;
   bool   accPbLong = false, accPbShort = false, accBoLong = false, accBoShort = false;
   bool   accR1Long = false, accR1Short = false, accR2Long = false, accR2Short = false;
   double pullInv = EMPTY_VALUE, pullT1 = EMPTY_VALUE, pullT2 = EMPTY_VALUE;
   double r1Inv = EMPTY_VALUE, r1T1 = EMPTY_VALUE, r1T2 = EMPTY_VALUE;
   double r2Inv = EMPTY_VALUE, r2T1 = EMPTY_VALUE, r2T2 = EMPTY_VALUE;
   double boInv = EMPTY_VALUE, boT1 = EMPTY_VALUE, boT2 = EMPTY_VALUE;
   string openedTag = "", exitMsg = "";

   if(g_pendEntry && g_pendSignalBar != NA_BAR && bi > g_pendSignalBar)
   {
      const int    pd   = g_pendDir;
      const double mEnt = o;
      const double mInv = (InpSlMode == SLB_ATR) ? AtrStop(pd, mEnt, g_pendAtr) : g_pendInval;
      const double mT1  = (InpTpMode == TPB_ATR) ? AtrT1(pd, mEnt, g_pendAtr) : g_pendT1;
      const double mT2  = (InpTpMode == TPB_ATR) ? AtrT2(pd, mEnt, g_pendAtr) : g_pendT2;
      const bool   stopValid    = !IsNa(mInv) && ((pd == 1) ? mInv < mEnt : mInv > mEnt);
      const bool   targetsValid = !IsNa(mT1) && !IsNa(mT2) && TargetsAhead(pd, mEnt, mT1, mT2);
      const double riskAtFill   = IsNa(mInv) ? 0.0 : MathAbs(mEnt - mInv);
      const bool   rrValid      = !IsNa(g_pendMinRR) && riskAtFill > 0 && !IsNa(mT2) && MathAbs(mT2 - mEnt) >= g_pendMinRR * riskAtFill;
      if(stopValid && targetsValid && rrValid && !g_tr.on)
      {
         OpenTrade(pd, mEnt, mInv, mT1, mT2, g_pendTag, bi);
         entryAccepted = true;
         openedTag     = g_pendTag;
         g_coordStatus = "Active: " + g_pendTag;
      }
      else
      {
         entryRejected = true;
         g_coordStatus = !stopValid ? "Entry skipped " + G_DOT + " stop beyond entry" :
                         (!targetsValid ? "Entry skipped " + G_DOT + " target passed at open" :
                         (!rrValid ? "Entry skipped " + G_DOT + " gap reduced R:R" : "Entry skipped " + G_DOT + " position occupied"));
      }
      g_pendEntry     = false;
      g_pendSignalBar = NA_BAR;
      g_pendDir       = 0;
      g_pendInval     = EMPTY_VALUE;
      g_pendMinRR     = EMPTY_VALUE;
      g_pendT1        = EMPTY_VALUE;
      g_pendT2        = EMPTY_VALUE;
      g_pendAtr       = EMPTY_VALUE;
      g_pendTag       = "";
   }

   bool     newSwing = false;
   int      cSwingDir = 0;
   double   cSwingPrice = EMPTY_VALUE, cSwingAtr = EMPTY_VALUE, cSwingPath = EMPTY_VALUE;
   long     cSwingBar = NA_BAR;
   if(IsNa(g_trackExt) && !IsNa(atrValue))
   {
      g_trackExt     = h;
      g_trackExtBar  = bi;
      g_trackExtAtr  = atrValue;
      g_trackExtPath = cumPath;
   }
   if(!IsNa(g_trackExt) && !IsNa(g_trackExtAtr))
   {
      if(g_trackDir == 1)
      {
         if(h > g_trackExt)
         {
            g_trackExt     = h;
            g_trackExtBar  = bi;
            g_trackExtAtr  = atrValue;
            g_trackExtPath = cumPath;
         }
         else if(g_trackExt - c >= g_mult * g_trackExtAtr)
         {
            newSwing    = true;
            cSwingDir   = 1;
            cSwingPrice = g_trackExt;
            cSwingBar   = g_trackExtBar;
            cSwingAtr   = g_trackExtAtr;
            cSwingPath  = g_trackExtPath;
            const int scanBound = (int)LMin(LMax(bi - g_trackExtBar - 1, 0), SCAN_MAX);
            double nExt = l, nAtr = atrValue, nPath = cumPath;
            long   nBar = bi;
            for(int k = 1; k <= scanBound && i - k >= 0; k++)
               if(low[i - k] < nExt)
               {
                  nExt  = low[i - k];
                  nBar  = bi - k;
                  nAtr  = IsNa(g_cAtr[i - k]) ? atrValue : g_cAtr[i - k];
                  nPath = g_cPath[i - k];
               }
            g_trackExt     = nExt;
            g_trackExtBar  = nBar;
            g_trackExtAtr  = nAtr;
            g_trackExtPath = nPath;
            g_trackDir     = -1;
         }
      }
      else
      {
         if(l < g_trackExt)
         {
            g_trackExt     = l;
            g_trackExtBar  = bi;
            g_trackExtAtr  = atrValue;
            g_trackExtPath = cumPath;
         }
         else if(c - g_trackExt >= g_mult * g_trackExtAtr)
         {
            newSwing    = true;
            cSwingDir   = -1;
            cSwingPrice = g_trackExt;
            cSwingBar   = g_trackExtBar;
            cSwingAtr   = g_trackExtAtr;
            cSwingPath  = g_trackExtPath;
            const int scanBound = (int)LMin(LMax(bi - g_trackExtBar - 1, 0), SCAN_MAX);
            double nExt = h, nAtr = atrValue, nPath = cumPath;
            long   nBar = bi;
            for(int k = 1; k <= scanBound && i - k >= 0; k++)
               if(high[i - k] > nExt)
               {
                  nExt  = high[i - k];
                  nBar  = bi - k;
                  nAtr  = IsNa(g_cAtr[i - k]) ? atrValue : g_cAtr[i - k];
                  nPath = g_cPath[i - k];
               }
            g_trackExt     = nExt;
            g_trackExtBar  = nBar;
            g_trackExtAtr  = nAtr;
            g_trackExtPath = nPath;
            g_trackDir     = 1;
         }
      }
   }

   if(newSwing)
   {
      if(!IsNa(g_lastSwingPrice))
      {
         const double cA      = g_lastSwingPrice;
         const double cB      = cSwingPrice;
         const int    cDir    = cSwingDir;
         const long   cBarA   = g_lastSwingBar;
         const long   cBarB   = cSwingBar;
         const double cLeg    = MathAbs(cB - cA);
         const double cAvgAtr = MathMax((g_lastSwingAtr + cSwingAtr) * 0.5, g_tick);
         const double cPath   = MathMax(MathAbs(cSwingPath - g_lastSwingPath), g_tick);
         const double cScore  = cLeg / cAvgAtr;
         const double cEff    = MathMin(1.0, cLeg / cPath);
         const bool   withinBarLimit = (cBarB - cBarA) <= g_maxSwingBars;
         bool breaksPrev = false;
         if(g_parentEverBuilt && InpRequireBreak)
         {
            const long scanFrom = LMax(bi - cBarB, 0);
            const long scanTo   = LMin(bi - cBarA, SCAN_MAX);
            for(long off = scanFrom; off <= scanTo && i - off >= 0; off++)
            {
               const double cl = close[i - (int)off];
               breaksPrev = breaksPrev || ((cDir == 1) ? (!IsNa(g_lastStructHigh) && cl > g_lastStructHigh)
                                                       : (!IsNa(g_lastStructLow) && cl < g_lastStructLow));
            }
         }
         const bool refreshAllowed = !g_parentEverBuilt || !InpRequireBreak || breaksPrev;
         const bool qualified      = g_ratiosValid && cScore >= InpMinImpulseAtr && cEff >= InpMinEfficiency && withinBarLimit && refreshAllowed;
         if(qualified)
         {
            g_pA = cA;
            g_pB = cB;
            g_pBarA = cBarA;
            g_pBarB = cBarB;
            g_mapBar = bi;
            g_pDir = cDir;
            g_pImpulseAtr = cScore;
            g_pEfficiency = cEff;
            g_parentEverBuilt = true;
            g_pActive = true;
            g_pInvalidCloses = 0;
            if(cDir == 1)
            {
               g_lastStructLow  = cA;
               g_lastStructHigh = cB;
            }
            else
            {
               g_lastStructHigh = cA;
               g_lastStructLow  = cB;
            }

            g_pbBot = MathMin(Fib(g_pA, g_pB, InpPbLower), Fib(g_pA, g_pB, InpPbUpper));
            g_pbTop = MathMax(Fib(g_pA, g_pB, InpPbLower), Fib(g_pA, g_pB, InpPbUpper));
            g_r1Bot = MathMin(Fib(g_pA, g_pB, InpR1Lower), Fib(g_pA, g_pB, InpR1Upper));
            g_r1Top = MathMax(Fib(g_pA, g_pB, InpR1Lower), Fib(g_pA, g_pB, InpR1Upper));
            g_r2Bot = MathMin(Fib(g_pA, g_pB, InpR2Lower), Fib(g_pA, g_pB, InpR2Upper));
            g_r2Top = MathMax(Fib(g_pA, g_pB, InpR2Lower), Fib(g_pA, g_pB, InpR2Upper));

            g_pbState = 0;
            g_pbTouchBar = NA_BAR;
            g_pbExt = EMPTY_VALUE;
            g_pbReclaimBar = NA_BAR;
            g_pbMicro = EMPTY_VALUE;
            g_pbUsed = false;
            g_r1State = 0;
            g_r1TouchBar = NA_BAR;
            g_r1Ext = EMPTY_VALUE;
            g_r1Sweep = EMPTY_VALUE;
            g_r1SweepSeen = false;
            g_r1ReclaimSeen = false;
            g_r1ReclaimBar = NA_BAR;
            g_r1RejSeen = false;
            g_r1RejBar = NA_BAR;
            g_r1Micro = EMPTY_VALUE;
            g_r1Accept = 0;
            g_r2State = 0;
            g_r2TouchBar = NA_BAR;
            g_r2Ext = EMPTY_VALUE;
            g_r2Sweep = EMPTY_VALUE;
            g_r2SweepSeen = false;
            g_r2ReclaimSeen = false;
            g_r2ReclaimBar = NA_BAR;
            g_r2RejSeen = false;
            g_r2RejBar = NA_BAR;
            g_r2Micro = EMPTY_VALUE;
            g_r2Accept = 0;
            g_boState = 0;
            g_boAcceptance = 0;
            g_boAcceptedBar = NA_BAR;
            g_boRetestExt = EMPTY_VALUE;

            const int barsAfter = (int)LMin(LMax(bi - g_pBarB, 0), SCAN_MAX);
            int recentScan = -1;
            for(int s = 0; s <= barsAfter && i - s >= 0; s++)
               if(recentScan < 0 && high[i - s] >= g_pbBot && low[i - s] <= g_pbTop)
                  recentScan = s;
            if(recentScan >= 0)
            {
               double rExt = (g_pDir == 1) ? 10e10 : -10e10;
               for(int s = 0; s <= recentScan; s++)
                  rExt = (g_pDir == 1) ? MathMin(rExt, low[i - s]) : MathMax(rExt, high[i - s]);
               g_pbState    = 1;
               g_pbTouchBar = bi - recentScan;
               g_pbExt      = rExt;
            }

            ObjectsDeleteAll(0, g_prefix + "MAP_");
            ObjectsDeleteAll(0, g_prefix + "SW_");
            g_mapDrawn   = InpShowMap;
            g_swingDrawn = InpShowSwingMarks;
         }
      }
      g_lastSwingPrice = cSwingPrice;
      g_lastSwingBar   = cSwingBar;
      g_lastSwingAtr   = cSwingAtr;
      g_lastSwingPath  = cSwingPath;
   }

   if(g_pActive)
   {
      const double stopBuffer = InpStructBufAtr * atrValue;
      const bool   pbOverlap  = h >= g_pbBot && l <= g_pbTop;
      const bool   r1Overlap  = h >= g_r1Bot && l <= g_r1Top;
      const bool   r2Overlap  = h >= g_r2Bot && l <= g_r2Top;

      if(g_pbState == 0 && pbOverlap)
      {
         g_pbState      = 1;
         g_pbTouchBar   = bi;
         g_pbExt        = (g_pDir == 1) ? l : h;
         g_pbReclaimBar = NA_BAR;
      }
      if(g_pbState == 1 || g_pbState == 2)
      {
         g_pbExt = (g_pDir == 1) ? MathMin(g_pbExt, l) : MathMax(g_pbExt, h);
         const bool pbExpired   = g_pbTouchBar != NA_BAR && bi - g_pbTouchBar > InpPbExpiry;
         const bool pbFailed    = (g_pDir == 1) ? c < g_pbBot : c > g_pbTop;
         const bool pbReclaimed = (g_pDir == 1) ? c > g_pbTop : c < g_pbBot;
         const bool pbMicroBrk  = !IsNa(g_pbMicro) && ((g_pDir == 1) ? c > g_pbMicro : c < g_pbMicro);
         const bool pbCandle    = (g_pDir == 1) ? (bullCandleOk && bullCloseOk) : (bearCandleOk && bearCloseOk);
         bool pbConfirmedNow = false;
         if(pbExpired)
            g_pbState = 4;
         else if(pbFailed)
            g_pbState = 5;
         else
         {
            if(g_pbState == 1 && pbReclaimed)
            {
               if(InpPbConfirm == PC_RECLAIM)
                  pbConfirmedNow = pbCandle;
               else
               {
                  g_pbState      = 2;
                  g_pbReclaimBar = bi;
                  g_pbMicro      = (g_pDir == 1) ? microHigh : microLow;
               }
            }
            else if(g_pbState == 2 && g_pbReclaimBar != NA_BAR && bi > g_pbReclaimBar)
               pbConfirmedNow = pbMicroBrk && pbCandle;
         }
         if(pbConfirmedNow && InpEnablePullback && !g_pbUsed)
         {
            const double structInv = (g_pDir == 1) ? MathMin(g_pbBot, g_pbExt) - stopBuffer : MathMax(g_pbTop, g_pbExt) + stopBuffer;
            const double inv  = (InpSlMode == SLB_ATR) ? AtrStop(g_pDir, c, atrValue) : structInv;
            const double tp1  = (InpTpMode == TPB_ATR) ? AtrT1(g_pDir, c, atrValue) : Fib(g_pA, g_pB, InpPbT1Ratio);
            const double tp2  = (InpTpMode == TPB_ATR) ? AtrT2(g_pDir, c, atrValue) : Fib(g_pA, g_pB, InpPbT2Ratio);
            const double risk = MathAbs(c - inv);
            const bool   orderValid = TargetsAhead(g_pDir, c, tp1, tp2);
            const bool   riskValid  = risk > 0 && MathAbs(tp2 - c) >= InpMinPbRR * risk;
            if(orderValid && riskValid)
            {
               pbLong   = (g_pDir == 1);
               pbShort  = (g_pDir == -1);
               pullInv  = inv;
               pullT1   = tp1;
               pullT2   = tp2;
               g_pbUsed = true;
               g_pbState = 3;
            }
            else
               g_pbState = 5;
         }
      }

      if(g_r1State == 0 && r1Overlap)
      {
         g_r1State       = 1;
         g_r1TouchBar    = bi;
         g_r1Ext         = (g_pDir == 1) ? h : l;
         g_r1Sweep       = (g_pDir == 1) ? priorLiqHigh : priorLiqLow;
         g_r1SweepSeen   = false;
         g_r1ReclaimSeen = false;
         g_r1ReclaimBar  = NA_BAR;
         g_r1RejSeen     = false;
         g_r1RejBar      = NA_BAR;
      }
      if(g_r1State == 1)
      {
         g_r1Ext = (g_pDir == 1) ? MathMax(g_r1Ext, h) : MathMin(g_r1Ext, l);
         const bool expired  = g_r1TouchBar != NA_BAR && bi - g_r1TouchBar > InpRvExpiry;
         const bool accepted = (g_pDir == 1) ? c > g_r1Top : c < g_r1Bot;
         g_r1Accept = accepted ? g_r1Accept + 1 : 0;
         const bool swept = !IsNa(g_r1Sweep) && ((g_pDir == 1) ? h > g_r1Sweep : l < g_r1Sweep);
         if(swept && !g_r1SweepSeen)
            g_r1SweepSeen = true;
         const bool reclaim = g_r1SweepSeen && !IsNa(g_r1Sweep) && ((g_pDir == 1) ? c < g_r1Sweep : c > g_r1Sweep);
         if(reclaim && !g_r1ReclaimSeen)
         {
            g_r1ReclaimSeen = true;
            g_r1ReclaimBar  = bi;
            g_r1Micro       = (g_pDir == 1) ? microLow : microHigh;
         }
         const bool rejected = (g_pDir == 1) ? c < g_r1Bot : c > g_r1Top;
         if(rejected && !g_r1RejSeen)
         {
            g_r1RejSeen = true;
            g_r1RejBar  = bi;
            if(InpRvConfirm == RC_MICRO)
               g_r1Micro = (g_pDir == 1) ? microLow : microHigh;
         }
         const bool microBrk   = !IsNa(g_r1Micro) && ((g_pDir == 1) ? c < g_r1Micro : c > g_r1Micro);
         const bool microReady = (InpRvConfirm == RC_MICRO) ? (g_r1RejSeen && g_r1RejBar != NA_BAR && bi > g_r1RejBar)
                                 : (g_r1SweepSeen && g_r1ReclaimSeen && g_r1RejSeen && g_r1ReclaimBar != NA_BAR && bi > g_r1ReclaimBar);
         const bool confirmed  = (InpRvConfirm == RC_REJECT) ? rejected : (microReady && microBrk);
         const bool candle     = (g_pDir == 1) ? (bearCandleOk && bearCloseOk) : (bullCandleOk && bullCloseOk);
         if(expired)
            g_r1State = 4;
         else if(g_r1Accept >= g_acceptCloses)
            g_r1State = 3;
         else if(confirmed && candle && InpEnableRev1)
         {
            const int    rd        = -g_pDir;
            const double structInv = (g_pDir == 1) ? g_r1Ext + stopBuffer : g_r1Ext - stopBuffer;
            const double inv       = (InpSlMode == SLB_ATR) ? AtrStop(rd, c, atrValue) : structInv;
            double tp1 = (InpTpMode == TPB_ATR) ? AtrT1(rd, c, atrValue) : Fib(g_pA, g_pB, InpR1T1Ratio);
            double tp2 = (InpTpMode == TPB_ATR) ? AtrT2(rd, c, atrValue) : Fib(g_pA, g_pB, InpR1T2Ratio);
            bool   ahead = TargetsAhead(rd, c, tp1, tp2);
            if(InpTpMode == TPB_FIB && !ahead)
            {
               tp1   = Fib(g_pA, g_pB, 0.618);
               tp2   = Fib(g_pA, g_pB, 0.0);
               ahead = TargetsAhead(rd, c, tp1, tp2);
               if(!ahead && InpAtrFallback)
               {
                  tp1 = AtrT1(rd, c, atrValue);
                  tp2 = AtrT2(rd, c, atrValue);
               }
            }
            const double risk = MathAbs(c - inv);
            const bool   orderValid = TargetsAhead(rd, c, tp1, tp2);
            const bool   riskValid  = risk > 0 && MathAbs(tp2 - c) >= InpMinRvRR * risk;
            if(orderValid && riskValid)
            {
               r1Long    = (rd == 1);
               r1Short   = (rd == -1);
               r1Inv     = inv;
               r1T1      = tp1;
               r1

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