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

JAFX Advanced SMC V4

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

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

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

О программе

JAFX Advanced SMC V4 — индикатор для MetaTrader 5, визуализирующий концепции Smart Money Concepts на графике цены. Программа определяет точки разворота (pivots), структурные пробои BOS и CHoCH, строит зоны Order Blocks и Fair Value Gaps, отображает уровни Equal High/Equal Low, зоны Premium/Discount и предыдущие дневные, недельные и месячные экстремумы. Индикатор работает в окне графика и создаёт графические объекты прямо на чарте.

Индикатор поддерживает два режима отображения структуры — Historical (все исторические данные) и Present (только актуальные), а также два стиля раскраски — цветной и монохромный. Пользователь может включать или отключать отображение внутренней и маяковной структуры, настраивать фильтры по типу пробоя, длину поиска пивотов и цвета для бычьих и медвежьих сигналов. Дополнительно реализована фильтрация конфлюэнса для внутренней структуры и метод митигации ордер-блоков по закрытию или диапазону High/Low.

Индикатор включает дашборд с информацией о текущем и межрыночном тренде, отображает сигналы более высоких таймфреймов (HTF) и промежуточных таймфреймов (ITF), включая CHoCH и BOS. Система уведомлений поддерживает всплывающие алерты, звуковые сигналы, push-уведомления и email-рассылки при обнаружении структурных событий. Все настройки доступны через вводные параметры индикатора.

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

НастройкаОписание
Mode (InpMode) Режим отображения — Определяет, показывать ли все исторические данные или только актуальные структурные уровни
Style (InpStyle) Стиль отображения — Выбирает цветной или монохромный режим визуализации элементов индикатора
Color Candles by Trend (InpColorCandles) Цвет свечей по тренду — Включает раскраску свечей в соответствии с текущим направлением внутреннего импульса
History Bars to Calculate (0 = All) (InpHistoryBars) Баров для расчёта — Ограничивает количество баров, участвующих в расчёте (0 — все доступные)
Show Internal Structure (InpShowInternal) Показывать внутреннюю структуру — Включает отображение внутренней рыночной структуры (BOS/CHoCH)
Bullish Filter (InpInternalBullFilt) Фильтр бычьей внутренней структуры — Фильтр для отображения бычьих структурных сигналов внутреннего уровня
Bearish Filter (InpInternalBearFilt) Фильтр медвежьей внутренней структуры — Фильтр для отображения медвежьих структурных сигналов внутреннего уровня
Pivot Length (InpInternalLen) Длина пивота внутреннего — Период поиска точек разворота для внутренней структуры
Confluence Filter (InpInternalConflu) Фильтр конфлюэнса внутреннего — Включает дополнительную фильтрацию по соотношению тела и теней свечи
Bullish Color (InpInternalBullClr) Цвет бычьей внутренней структуры — Цвет линий и меток бычьих сигналов внутренней структуры
Bearish Color (InpInternalBearClr) Цвет медвежьей внутренней структуры — Цвет линий и меток медвежьих сигналов внутренней структуры
Show Swing Structure (InpShowSwing) Показывать маяковную структуру — Включает отображение структуры на более высоком уровне (BOS/CHoCH)
Bullish Filter (InpSwingBullFilt) Фильтр бычьей маяковой структуры — Фильтр для отображения бычьих структурных сигналов маякового уровня
Bearish Filter (InpSwingBearFilt) Фильтр медвежьей маяковой структуры — Фильтр для отображения медвежьих структурных сигналов маякового уровня
Pivot Length (InpSwingLen) Длина пивота маякового — Период поиска точек разворота для маяковой структуры
Show Swing Points (HH/HL/LH/LL) (InpShowSwingPts) Показывать точки разворота — Отображает метки HH, HL, LH, LL на уровнях маяковых пивотов
Show Strong/Weak High/Low (InpShowStrongWeak) Показывать сильные/слабые экстремумы — Включает отображение Strong/Weak High и Low с учётом импульса
Bullish Color (InpSwingBullClr) Цвет бычьей маяковой структуры — Цвет линий и меток бычьих сигналов маяковой структуры
Bearish Color (InpSwingBearClr) Цвет медвежьей маяковой структуры — Цвет линий и меток медвежьих сигналов маяковой структуры
Internal Order Blocks (InpShowInternalOB) Показывать внутренние ордер-блоки — Включает отображение зон ордер-блоков внутренней структуры
Max Internal OB Count (InpInternalOBCount) Максимум внутренних ордер-блоков — Ограничивает количество отображаемых внутренних ордер-блоков
Swing Order Blocks (InpShowSwingOB) Показывать маяковые ордер-блоки — Включает отображение зон ордер-блоков маяковой структуры
Max Swing OB Count (InpSwingOBCount) Максимум маяковых ордер-блоков — Ограничивает количество отображаемых маяковых ордер-блоков
Mitigation Method (InpOBMitigation) Метод митигации ордер-блоков — Определяет критерий деактивации ордер-блока (по закрытию или High/Low)
Internal Bullish OB (InpIntBullOBClr) Цвет бычьего внутреннего ордер-блока — Цвет заливки бычьих внутренних ордер-блоков
Internal Bearish OB (InpIntBearOBClr) Цвет медвежьего внутреннего ордер-блока — Цвет заливки медвежьих внутренних ордер-блоков
Swing Bullish OB (InpSwgBullOBClr) Цвет бычьего маякового ордер-блока — Цвет заливки бычьих маяковых ордер-блоков
Swing Bearish OB (InpSwgBearOBClr) Цвет медвежьего маякового ордер-блока — Цвет заливки медвежьих маяковых ордер-блоков
Show Equal H/L (InpShowEQHL) Показывать Equal High/Low — Включает отображение зон равных высот и равных низок
Threshold (0-0.5) (InpEQHLThreshold) Порог EQH/EQL — Пороговое значение для определения равенства уровней в долях от ATR
Получить полный код

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

#property version     "4.00"
#property description "JAFX Smart Money Concepts V4.0"
#property description "BOS · CHoCH · Order Blocks · Fair Value Gaps"
#property description "EQH/EQL · Premium/Discount · Strong/Weak H/L"
#property description "Dashboard · Multi-channel alerts"
#property description "Precision before profit."
#property indicator_chart_window
#property indicator_buffers 5
#property indicator_plots   1
#property strict

#property indicator_label1  "SMC Open;SMC High;SMC Low;SMC Close"
#property indicator_type1   DRAW_COLOR_CANDLES
#property indicator_color1  clrLime,clrRed,clrGray
#property indicator_width1  1

enum ENUM_SMC_MODE
{
   SMC_MODE_HISTORICAL = 0,  // Historical (show all)
   SMC_MODE_PRESENT    = 1   // Present (recent only)
};

enum ENUM_SMC_STYLE
{
   SMC_STYLE_COLORED    = 0, // Colored
   SMC_STYLE_MONO       = 1  // Monochrome
};

enum ENUM_STRUCTURE_FILTER
{
   SMC_STRUCT_ALL   = 0,     // All
   SMC_STRUCT_BOS   = 1,     // BOS only
   SMC_STRUCT_CHOCH = 2      // CHoCH only
};

enum ENUM_OB_MITIGATION
{
   OB_MIT_CLOSE   = 0,       // Close
   OB_MIT_HIGHLOW = 1        // High/Low
};

input group                      "══════ General ══════"
input ENUM_SMC_MODE              InpMode             = SMC_MODE_HISTORICAL;  // Mode
input ENUM_SMC_STYLE             InpStyle            = SMC_STYLE_COLORED;    // Style
input bool                       InpColorCandles     = false;                // Color Candles by Trend
input int                        InpHistoryBars      = 2000;                 // History Bars to Calculate (0 = All)

input group                      "══════ Internal Structure ══════"
input bool                       InpShowInternal     = true;                 // Show Internal Structure
input ENUM_STRUCTURE_FILTER      InpInternalBullFilt = SMC_STRUCT_ALL;       // Bullish Filter
input ENUM_STRUCTURE_FILTER      InpInternalBearFilt = SMC_STRUCT_ALL;       // Bearish Filter
input int                        InpInternalLen      = 5;                    // Pivot Length
input bool                       InpInternalConflu   = true;                // Confluence Filter
input color                      InpInternalBullClr  = C'0,185,140';        // Bullish Color
input color                      InpInternalBearClr  = C'220,50,80';        // Bearish Color

input group                      "══════ Swing Structure ══════"
input bool                       InpShowSwing        = true;                 // Show Swing Structure
input ENUM_STRUCTURE_FILTER      InpSwingBullFilt    = SMC_STRUCT_ALL;       // Bullish Filter
input ENUM_STRUCTURE_FILTER      InpSwingBearFilt    = SMC_STRUCT_ALL;       // Bearish Filter
input int                        InpSwingLen         = 50;                   // Pivot Length
input bool                       InpShowSwingPts     = true;                // Show Swing Points (HH/HL/LH/LL)
input bool                       InpShowStrongWeak   = true;                 // Show Strong/Weak High/Low
input color                      InpSwingBullClr     = C'0,185,140';        // Bullish Color
input color                      InpSwingBearClr     = C'220,50,80';        // Bearish Color

input group                      "══════ Order Blocks ══════"
input bool                       InpShowInternalOB   = true;                 // Internal Order Blocks
input int                        InpInternalOBCount  = 5;                    // Max Internal OB Count
input bool                       InpShowSwingOB      = true;                // Swing Order Blocks
input int                        InpSwingOBCount     = 5;                    // Max Swing OB Count
input ENUM_OB_MITIGATION         InpOBMitigation     = OB_MIT_HIGHLOW;       // Mitigation Method
input color                      InpIntBullOBClr     = C'91,156,246';        // Internal Bullish OB
input color                      InpIntBearOBClr     = C'247,124,128';       // Internal Bearish OB
input color                      InpSwgBullOBClr     = C'255,255,0';         // Swing Bullish OB
input color                      InpSwgBearOBClr     = C'255,255,0';         // Swing Bearish OB

input group                      "══════ Equal Highs/Lows ══════"
input bool                       InpShowEQHL         = true;                 // Show Equal H/L
input double                     InpEQHLThreshold    = 0.1;                  // Threshold (0-0.5)

input group                      "══════ Fair Value Gaps ══════"
input bool                       InpShowFVG          = true;                // Show Fair Value Gaps
input ENUM_TIMEFRAMES            InpFVGTimeframe     = PERIOD_CURRENT;       // FVG Timeframe
input bool                       InpFVGAutoThresh    = true;                 // Auto Threshold
input int                        InpFVGExtend        = 5;                    // Extend Bars
input int                        InpFVGBullCount     = 3;                    // Max Bullish FVGs to Show (0 = All)
input int                        InpFVGBearCount     = 3;                    // Max Bearish FVGs to Show (0 = All)
input color                      InpFVGBullClr       = C'0,100,0';        // Bullish FVG
input color                      InpFVGBearClr       = C'255,0,8';          // Bearish FVG

input group                      "══════ Premium/Discount ══════"
input bool                       InpShowPDZones      = true;                // Show Premium/Discount Zones

input group                      "══════ Previous D/W/M High/Low ══════"
input bool                       InpShowPrevDay       = true;               // Show Previous Day High/Low
input bool                       InpShowPrevWeek      = true;               // Show Previous Week High/Low
input bool                       InpShowPrevMonth     = true;               // Show Previous Month High/Low
input color                      InpPrevHighClr       = clrDeepSkyBlue;      // Previous High Color
input color                      InpPrevLowClr        = clrOrange;          // Previous Low Color
input ENUM_LINE_STYLE            InpPrevLineStyle     = STYLE_DASH;          // Line Style

input group                      "══════ Alerts ══════"
input bool                       InpAlertPopup       = false;                 // Popup Alert
input bool                       InpAlertSound       = false;                 // Sound Alert
input bool                       InpAlertPush        = false;                // Push Notification
input bool                       InpAlertEmail       = false;                // Email Alert

input group                      "══════ Dashboard ══════"
input bool                       InpShowDash         = true;                 // Show Dashboard
input int                        InpDashX            = 5;                   // X Position
input int                        InpDashY            = 400;                   // Y Position
input int                        InpDashFS           = 9;                    // Font Size

input group                      "══════ HTF Dashboard ══════"
input bool                       InpShowHTF          = true;                 // Show HTF Section
input ENUM_TIMEFRAMES            InpHTFTimeframe     = PERIOD_H4;            // Higher Timeframe

input group                      "══════ ITF Dashboard ══════"
input bool                       InpShowITF          = true;                 // Show ITF Section
input ENUM_TIMEFRAMES            InpITFTimeframe     = PERIOD_H1;            // Intermediate Timeframe

#define PREFIX        "JAFX"
#define FONT          "Consolas"
#define BULLISH       1
#define BEARISH       -1
#define NEUTRAL       0
#define MAX_OB        100
#define MAX_FVG       50

struct SPivot
{
   double   level;
   double   lastLevel;
   bool     crossed;
   datetime barTime;
   int      barIndex;
};

struct SOrderBlock
{
   double   high;
   double   low;
   datetime barTime;
   int      bias;
   bool     active;
   string   boxName;
};

struct SFairValueGap
{
   double   top;
   double   bottom;
   int      bias;
   datetime barTime;
   bool     active;
   string   boxTopName;
   string   boxBotName;
};

struct STrailing
{
   double   top;
   double   bottom;
   datetime topTime;
   datetime bottomTime;
   datetime anchorTime;
   int      anchorIndex;
};

double g_bufOpen[];       // 0 - candle OHLC
double g_bufHigh[];       // 1
double g_bufLow[];        // 2
double g_bufClose[];      // 3
double g_bufCandleClr[];  // 4 - color index

SPivot         g_swingHigh, g_swingLow;
SPivot         g_intHigh, g_intLow;
SPivot         g_eqHigh, g_eqLow;
STrailing      g_trailing;

SOrderBlock    g_intOB[];
SOrderBlock    g_swgOB[];
SFairValueGap  g_fvg[];

int            g_swingBias    = 0;
int            g_internalBias = 0;
int            g_objCount     = 0;
datetime       g_lastAlertTime = 0;

int            g_htfSwingBias    = 0;
int            g_htfInternalBias = 0;
string         g_htfLastSignal   = "None";
color          g_htfLastSignalClr = C'90,95,110';
datetime       g_htfLastCalc     = 0;

int            g_itfSwingBias     = 0;
int            g_itfInternalBias  = 0;
string         g_itfLastSignal    = "—";
color          g_itfLastSignalClr = C'90,95,110';
string         g_itfChochSignal   = "Calculating...";
color          g_itfChochClr      = C'90,95,110';
string         g_itfBosSignal     = "Calculating...";
color          g_itfBosClr        = C'90,95,110';
string         g_itfSwingSignal   = "Calculating...";
color          g_itfSwingClr      = C'90,95,110';
datetime       g_itfLastCalc      = 0;
double         g_atr[];
int            g_atrHandle    = INVALID_HANDLE;
int            g_fvgHigh      = INVALID_HANDLE;
int            g_fvgLow       = INVALID_HANDLE;
int            g_fvgOpen      = INVALID_HANDLE;
int            g_fvgClose     = INVALID_HANDLE;
double         g_pointVal     = 0;

int OnInit()
{
      // код доступен только после оплаты
   }

void OnDeinit(const int reason)
{
   ObjectsDeleteAll(0, PREFIX);
   if(g_atrHandle != INVALID_HANDLE) IndicatorRelease(g_atrHandle);
   ChartRedraw(0);
}

int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
      // код доступен только после оплаты
   }

void InitPivot(SPivot &p)
{
   p.level = 0; p.lastLevel = 0; p.crossed = false;
   p.barTime = 0; p.barIndex = 0;
}

void SetPivotHigh(SPivot &p, const double val, const datetime t, const int idx)
{
   p.lastLevel = p.level;
   p.level = val; p.crossed = false;
   p.barTime = t; p.barIndex = idx;
}

void SetPivotLow(SPivot &p, const double val, const datetime t, const int idx)
{
   p.lastLevel = p.level;
   p.level = val; p.crossed = false;
   p.barTime = t; p.barIndex = idx;
}

void DetectPivots(const int i, const int len,
                  const double &high[], const double &low[],
                  const datetime &time[], const bool internal)
{
   if(i < len * 2)
      return;

   int lb = i - len; // lookback bar

   bool isHigh = true;
   for(int j = 1; j <= len; j++)
   {
      if(high[lb - j] > high[lb] || high[lb + j] > high[lb])
      { isHigh = false; break; }
   }

   bool isLow = true;
   for(int j = 1; j <= len; j++)
   {
      if(low[lb - j] < low[lb] || low[lb + j] < low[lb])
      { isLow = false; break; }
   }

   if(isHigh)
   {

      if(!internal && InpShowEQHL && g_eqHigh.level > 0)
      {
         double atr = (g_atr[lb] > 0) ? g_atr[lb] : g_pointVal * 100;
         if(MathAbs(g_eqHigh.level - high[lb]) < InpEQHLThreshold * atr)
            DrawEqualHL(g_eqHigh, high[lb], time[lb], lb, true);
      }

      if(!internal)
      {
         g_eqHigh.lastLevel = g_eqHigh.level;
         g_eqHigh.level = high[lb]; g_eqHigh.barTime = time[lb]; g_eqHigh.barIndex = lb;
      }

      if(internal)
         SetPivotHigh(g_intHigh, high[lb], time[lb], lb);
      else
      {
         SetPivotHigh(g_swingHigh, high[lb], time[lb], lb);
         g_trailing.top = high[lb]; g_trailing.topTime = time[lb];
         g_trailing.anchorTime = time[lb]; g_trailing.anchorIndex = lb;
      }

      if(!internal && InpShowSwingPts)
      {
         double prev = g_swingHigh.lastLevel;
         string tag = (high[lb] > prev && prev > 0) ? "HH" : "LH";
         DrawSmcLabel(time[lb], high[lb], tag, GetBearColor(false), true);
      }
   }

   if(isLow)
   {

      if(!internal && InpShowEQHL && g_eqLow.level > 0)
      {
         double atr = (g_atr[lb] > 0) ? g_atr[lb] : g_pointVal * 100;
         if(MathAbs(g_eqLow.level - low[lb]) < InpEQHLThreshold * atr)
            DrawEqualHL(g_eqLow, low[lb], time[lb], lb, false);
      }

      if(!internal)
      {
         g_eqLow.lastLevel = g_eqLow.level;
         g_eqLow.level = low[lb]; g_eqLow.barTime = time[lb]; g_eqLow.barIndex = lb;
      }

      if(internal)
         SetPivotLow(g_intLow, low[lb], time[lb], lb);
      else
      {
         SetPivotLow(g_swingLow, low[lb], time[lb], lb);
         g_trailing.bottom = low[lb]; g_trailing.bottomTime = time[lb];
         g_trailing.anchorTime = time[lb]; g_trailing.anchorIndex = lb;
      }

      if(!internal && InpShowSwingPts)
      {
         double prev = g_swingLow.lastLevel;
         string tag = (low[lb] < prev && prev > 0) ? "LL" : "HL";
         DrawSmcLabel(time[lb], low[lb], tag, GetBullColor(false), false);
      }
   }
}

void DetectStructure(const int i,
                     const double &close[], const double &open[],
                     const double &high[], const double &low[],
                     const datetime &time[], const bool internal)
{

   bool bullBar = true, bearBar = true;
   if(internal && InpInternalConflu)
   {
      double bodyTop = MathMax(close[i], open[i]);
      double bodyBot = MathMin(close[i], open[i]);
      bullBar = (high[i] - bodyTop) > (bodyBot - low[i]);
      bearBar = (high[i] - bodyTop) < (bodyBot - low[i]);
   }

   double highLevel, lowLevel;
   bool   highCrossed, lowCrossed;
   datetime highTime, lowTime;
   int    highIdx, lowIdx, curBias;

   if(internal)
   {
      highLevel = g_intHigh.level;  highCrossed = g_intHigh.crossed;
      highTime  = g_intHigh.barTime; highIdx    = g_intHigh.barIndex;
      lowLevel  = g_intLow.level;   lowCrossed  = g_intLow.crossed;
      lowTime   = g_intLow.barTime;  lowIdx     = g_intLow.barIndex;
      curBias   = g_internalBias;
   }
   else
   {
      highLevel = g_swingHigh.level;  highCrossed = g_swingHigh.crossed;
      highTime  = g_swingHigh.barTime; highIdx    = g_swingHigh.barIndex;
      lowLevel  = g_swingLow.level;   lowCrossed  = g_swingLow.crossed;
      lowTime   = g_swingLow.barTime;  lowIdx     = g_swingLow.barIndex;
      curBias   = g_swingBias;
   }

   bool extraBull = internal ? (g_intHigh.level != g_swingHigh.level && bullBar) : true;
   bool extraBear = internal ? (g_intLow.level  != g_swingLow.level  && bearBar) : true;

   if(highLevel > 0 && close[i] > highLevel && !highCrossed && extraBull)
   {
      string tag = (curBias == BEARISH) ? "CHoCH" : "BOS";

      if(internal) g_intHigh.crossed = true;
      else         g_swingHigh.crossed = true;

      if(internal) g_internalBias = BULLISH;
      else         g_swingBias = BULLISH;

      ENUM_STRUCTURE_FILTER filt = internal ? InpInternalBullFilt : InpSwingBullFilt;
      bool show = internal ? InpShowInternal : InpShowSwing;
      bool pass = (filt == SMC_STRUCT_ALL) ||
                  (filt == SMC_STRUCT_BOS   && tag == "BOS") ||
                  (filt == SMC_STRUCT_CHOCH  && tag == "CHoCH");

      if(show && pass)
      {
         SPivot tmpPivot;
         tmpPivot.level = highLevel; tmpPivot.barTime = highTime; tmpPivot.barIndex = highIdx;
         DrawStructureLine(tmpPivot, tag, GetBullColor(internal), internal, time[i]);
      }

      if((internal && InpShowInternalOB) || (!internal && InpShowSwingOB))
      {
         SPivot tmpPivot;
         tmpPivot.level = highLevel; tmpPivot.barTime = highTime; tmpPivot.barIndex = highIdx;
         StoreOrderBlock(tmpPivot, internal, BULLISH, high, low, time);
      }

      FireAlert(tag, "Bullish", internal, time[i]);
   }

   if(lowLevel > 0 && close[i] < lowLevel && !lowCrossed && extraBear)
   {
      string tag = (curBias == BULLISH) ? "CHoCH" : "BOS";

      if(internal) g_intLow.crossed = true;
      else         g_swingLow.crossed = true;

      if(internal) g_internalBias = BEARISH;
      else         g_swingBias = BEARISH;

      ENUM_STRUCTURE_FILTER filt = internal ? InpInternalBearFilt : InpSwingBearFilt;
      bool show = internal ? InpShowInternal : InpShowSwing;
      bool pass = (filt == SMC_STRUCT_ALL) ||
                  (filt == SMC_STRUCT_BOS   && tag == "BOS") ||
                  (filt == SMC_STRUCT_CHOCH  && tag == "CHoCH");

      if(show && pass)
      {
         SPivot tmpPivot;
         tmpPivot.level = lowLevel; tmpPivot.barTime = lowTime; tmpPivot.barIndex = lowIdx;
         DrawStructureLine(tmpPivot, tag, GetBearColor(internal), internal, time[i]);
      }

      if((internal && InpShowInternalOB) || (!internal && InpShowSwingOB))
      {
         SPivot tmpPivot;
         tmpPivot.level = lowLevel; tmpPivot.barTime = lowTime; tmpPivot.barIndex = lowIdx;
         StoreOrderBlock(tmpPivot, internal, BEARISH, high, low, time);
      }

      FireAlert(tag, "Bearish", internal, time[i]);
   }
}

void StoreOrderBlock(const SPivot &pivot, const bool internal,
                     const int bias,
                     const double &high[], const double &low[],
                     const datetime &time[])
{
   if(pivot.barIndex <= 0) return;

   int startIdx = pivot.barIndex;
   int endIdx   = MathMin(ArraySize(high) - 1, startIdx + 50);
   int bestIdx  = startIdx;

   if(bias == BEARISH)
   {
      double maxH = high[startIdx];
      for(int j = startIdx + 1; j <= endIdx; j++)
         if(high[j] > maxH) { maxH = high[j]; bestIdx = j; }
   }
   else
   {
      double minL = low[startIdx];
      for(int j = startIdx + 1; j <= endIdx; j++)
         if(low[j] < minL) { minL = low[j]; bestIdx = j; }
   }

   SOrderBlock ob;
   ob.high    = high[bestIdx];
   ob.low     = low[bestIdx];
   ob.barTime = time[bestIdx];
   ob.bias    = bias;
   ob.active  = true;
   ob.boxName = PREFIX + "OB_" + (internal ? "I" : "S") + "_" +
                IntegerToString((long)time[bestIdx]);

   if(internal)
   {
      int sz = ArraySize(g_intOB);
      ArrayResize(g_intOB, sz + 1);
      g_intOB[sz] = ob;
      if(ArraySize(g_intOB) > MAX_OB) ArrayRemove(g_intOB, 0, 1);
   }
   else
   {
      int sz = ArraySize(g_swgOB);
      ArrayResize(g_swgOB, sz + 1);
      g_swgOB[sz] = ob;
      if(ArraySize(g_swgOB) > MAX_OB) ArrayRemove(g_swgOB, 0, 1);
   }
}

void MitigateOB(SOrderBlock &arr[],
                const double closeP, const double highP, const double lowP)
{
   double bullSrc = (InpOBMitigation == OB_MIT_CLOSE) ? closeP : lowP;
   double bearSrc = (InpOBMitigation == OB_MIT_CLOSE) ? closeP : highP;

   for(int j = ArraySize(arr) - 1; j >= 0; j--)
   {
      if(!arr[j].active) continue;

      if(arr[j].bias == BEARISH && bearSrc > arr[j].high)
      { arr[j].active = false; ObjectDelete(0, arr[j].boxName); }
      else if(arr[j].bias == BULLISH && bullSrc < arr[j].low)
      { arr[j].active = false; ObjectDelete(0, arr[j].boxName); }
   }
}

void DetectFVG(const int i,
               const double &high[], const double &low[],
               const double &close[], const double &open[],
               const datetime &time[], const int rates_total)
{

   ENUM_TIMEFRAMES fvgTF = InpFVGTimeframe;
   double fH0, fH2, fL0, fL2, fO1, fC1;
   datetime fT1;
   if(fvgTF == PERIOD_CURRENT || fvgTF == _Period)
   {
      fH0 = high[i];   fH2 = high[i-2];
      fL0 = low[i];    fL2 = low[i-2];
      fO1 = open[i-1]; fC1 = close[i-1];
      fT1 = time[i-1];
   }
   else
   {

      int s0 = iBarShift(_Symbol, fvgTF, time[i],   false);
      int s1 = iBarShift(_Symbol, fvgTF, time[i-1], false);
      int s2 = iBarShift(_Symbol, fvgTF, time[i-2], false);
      if(s0 < 0 || s1 < 0 || s2 < 0) return;

      if(s0 == s1) return;
      fH0 = iHigh(_Symbol,  fvgTF, s0);
      fH2 = iHigh(_Symbol,  fvgTF, s2);
      fL0 = iLow(_Symbol,   fvgTF, s0);
      fL2 = iLow(_Symbol,   fvgTF, s2);
      fO1 = iOpen(_Symbol,  fvgTF, s1);
      fC1 = iClose(_Symbol, fvgTF, s1);
      fT1 = (datetime)iTime(_Symbol, fvgTF, s1);
   }

   if(fL0 > fH2)
   {
      double bodyPct = MathAbs(fC1 - fO1) /
                       (fO1 != 0 ? MathAbs(fO1) : 1.0) * 100.0;
      if(!InpFVGAutoThresh || bodyPct > 0.05)
      {

         bool dup = false;
         for(int k = ArraySize(g_fvg)-1; k >= 0; k--)
            if(g_fvg[k].barTime == fT1 && g_fvg[k].bias == BULLISH) { dup = true; break; }
         if(!dup)
         {
            SFairValueGap fvg;
            fvg.top = fL0; fvg.bottom = fH2;
            fvg.bias = BULLISH; fvg.barTime = fT1; fvg.active = true;
            fvg.boxTopName = PREFIX + "FVG_BT_" + IntegerToString((long)fT1);
            fvg.boxBotName = PREFIX + "FVG_BB_" + IntegerToString((long)fT1);
            int sz = ArraySize(g_fvg);
            ArrayResize(g_fvg, sz + 1);
            g_fvg[sz] = fvg;
            if(ArraySize(g_fvg) > MAX_FVG) ArrayRemove(g_fvg, 0, 1);
         }
      }
   }

   if(fH0 < fL2)
   {
      double bodyPct = MathAbs(fC1 - fO1) /
                       (fO1 != 0 ? MathAbs(fO1) : 1.0) * 100.0;
      if(!InpFVGAutoThresh || bodyPct > 0.05)
      {
         bool dup = false;
         for(int k = ArraySize(g_fvg)-1; k >= 0; k--)
            if(g_fvg[k].barTime == fT1 && g_fvg[k].bias == BEARISH) { dup = true; break; }
         if(!dup)
         {
            SFairValueGap fvg;
            fvg.top = fL2; fvg.bottom = fH0;
            fvg.bias = BEARISH; fvg.barTime = fT1; fvg.active = true;
            fvg.boxTopName = PREFIX + "FVG_ST_" + IntegerToString((long)fT1);
            fvg.boxBotName = PREFIX + "FVG_SB_" + IntegerToString((long)fT1);
            int sz = ArraySize(g_fvg);
            ArrayResize(g_fvg, sz + 1);
            g_fvg[sz] = fvg;
            if(ArraySize(g_fvg) > MAX_FVG) ArrayRemove(g_fvg, 0, 1);
         }
      }
   }

   for(int j = ArraySize(g_fvg) - 1; j >= 0; j--)
   {
      if(!g_fvg[j].active) continue;
      if(g_fvg[j].bias == BULLISH && low[i] < g_fvg[j].bottom)
      { g_fvg[j].active = false; ObjectDelete(0, g_fvg[j].boxTopName); ObjectDelete(0, g_fvg[j].boxBotName); }
      else if(g_fvg[j].bias == BEARISH && high[i] > g_fvg[j].top)
      { g_fvg[j].active = false; ObjectDelete(0, g_fvg[j].boxTopName); ObjectDelete(0, g_fvg[j].boxBotName); }
   }
}

void UpdateTrailing(const double h, const double l, const datetime t)
{
   if(h > g_trailing.top || g_trailing.top == 0)
   { g_trailing.top = h; g_trailing.topTime = t; }
   if(l < g_trailing.bottom || g_trailing.bottom == DBL_MAX)
   { g_trailing.bottom = l; g_trailing.bottomTime = t; }
}

void DrawStructureLine(const SPivot &pivot, const string tag,
                       const color clr, const bool internal,
                       const datetime currentTime)
{
   if(InpMode == SMC_MODE_PRESENT)
      CleanOldObjects("STR_");

   string sfx       = IntegerToString(g_objCount++);
   string lineName  = PREFIX + "STR_L_" + sfx;
   string labelName = PREFIX + "STR_T_" + sfx;

   ObjectCreate(0, lineName, OBJ_TREND, 0,
                pivot.barTime, pivot.level, currentTime, pivot.level);
   ObjectSetInteger(0, lineName, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, lineName, OBJPROP_WIDTH, 1);
   ObjectSetInteger(0, lineName, OBJPROP_RAY_RIGHT, false);
   ObjectSetInteger(0, lineName, OBJPROP_STYLE, internal ? STYLE_DASH : STYLE_SOLID);
   ObjectSetInteger(0, lineName, OBJPROP_BACK, true);
   ObjectSetInteger(0, lineName, OBJPROP_SELECTABLE, false);

   datetime midTime = (datetime)(((long)pivot.barTime + (long)currentTime) / 2);
   ObjectCreate(0, labelName, OBJ_TEXT, 0, midTime, pivot.level);
   string displayTag = tag;
   if(!internal) StringToUpper(displayTag);
   else StringToLower(displayTag);
   ObjectSetString(0,  labelName, OBJPROP_TEXT, displayTag);
   ObjectSetInteger(0, labelName, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, labelName, OBJPROP_FONTSIZE, 10);
   ObjectSetString(0,  labelName, OBJPROP_FONT, FONT);
   ObjectSetInteger(0, labelName, OBJPROP_ANCHOR, ANCHOR_LOWER);
   ObjectSetInteger(0, labelName, OBJPROP_SELECTABLE, false);
}

void DrawSmcLabel(const datetime t, const double price,
                  const string tag, const color clr, const bool above)
{
   string name = PREFIX + "LBL_" + IntegerToString(g_objCount++);
   ObjectCreate(0, name, OBJ_TEXT, 0, t, price);
   ObjectSetString(0,  name, OBJPROP_TEXT, tag);
   ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 10);
   ObjectSetString(0,  name, OBJPROP_FONT, FONT);
   ObjectSetInteger(0, name, OBJPROP_ANCHOR, above ? ANCHOR_LOWER : ANCHOR_UPPER);
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
}

void DrawEqualHL(const SPivot &pivot, const double level,
                 const datetime t, const int idx, const bool isHigh)
{
   string sf

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

Открыть по тарифу

Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.

Разовая покупка файла

На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.

Чтобы оформить заказ, введите email и перейдите к оплате.

Стоимость полного кода
4 151,60₽ ≈ $50.74