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

Order Block Zones Indicator

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

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

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

О программе

Индикатор Order Block Zones Indicator предназначен для поиска и отслеживания зон ордер-блоков на таймфрейме графика или на более высоком таймфрейме. Каждая зона отслеживается бар за баром и может находиться в состоянии свежей, проверенной или пробитой.

Размеры блоков измеряются в средних диапазонах, что позволяет использовать одинаковые настройки для любого символа и таймфрейма. Зоны не накапливаются: новая зона объединяется с живыми зонами той же стороны, разделяющими одну цену, а зоны противоположной стороны закрываются.

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

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

НастройкаОписание
InpTimeframe Таймфрейм, на котором определяются блоки. Если ниже таймфрейма графика, используется таймфрейм графика.
InpLength Количество свечей в движении после свечи блока. Значение от 1 до 20.
InpMove Минимальное движение всего движения, выраженное в средних диапазонах.
InpFirst Минимальное тело свечи блока, выраженное в средних диапазонах.
InpOther Свечи движения с телом меньше этого значения учитываются в обоих направлениях, выражены в средних диапазонах.
InpZones Количество живых зон на одну сторону. Значение от 0 до 20.
InpPrice Метод определения цены зоны: по верхней и нижней границе свечи, от тела до фитиля или по глубинному фитилю.
InpShift Свеча, от которой берётся цена зоны, где 0 соответствует свече блока.
InpSearch Количество свечей, просматриваемых в поисках глубинного фитиля.
InpDistance Скрывает зоны, удалённые от текущей цены, выражено в средних диапазонах. 0 — отключено.
InpBullColor Цвет отображения зон спроса.
InpBearColor Цвет отображения зон предложения.
InpAlert Включает уведомления при появлении новых зон и первых возвратах цены в зону.

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

#property version   "1.04"
#property description "Order blocks from the chart timeframe or a higher one, followed bar by bar as"
#property description "fresh, tested or broken zones that never pile up, sized in average ranges."
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_plots   4
#property indicator_type1   DRAW_NONE
#property indicator_label1  "Demand top"
#property indicator_type2   DRAW_NONE
#property indicator_label2  "Demand bottom"
#property indicator_type3   DRAW_NONE
#property indicator_label3  "Supply top"
#property indicator_type4   DRAW_NONE
#property indicator_label4  "Supply bottom"

enum ENUM_ZONE_PRICE
  {
   ZONE_PRICE_HIGH_LOW=0,  // high to low of the candle
   ZONE_PRICE_BODY=1,      // wick to the body of the candle
   ZONE_PRICE_DEEPEST=2    // deepest wick near the block candle
  };

input group "Blocks"
input ENUM_TIMEFRAMES InpTimeframe = PERIOD_CURRENT;     // block timeframe (lower than chart = chart)
input int             InpLength    = 5;                  // candles in the run, 1 to 20
input double          InpMove      = 0.85;               // least move of the run, average ranges
input double          InpFirst     = 0.15;               // least body of the block candle, average ranges
input double          InpOther     = 0.03;               // run candle under this body counts, average ranges
input group "Zones"
input int             InpZones     = 4;                  // live zones per side, 0 to 20
input ENUM_ZONE_PRICE InpPrice     = ZONE_PRICE_BODY;    // zone price
input int             InpShift     = 1;                  // candle that sets the price, 0 = block candle
input int             InpSearch    = 2;                  // candles searched for the deepest wick
input double          InpDistance  = 0;                  // hide zones farther, average ranges (0 = off)
input group "Colors"
input color           InpBullColor = C'0,137,180';       // demand zones
input color           InpBearColor = C'230,120,20';      // supply zones
input group "Alerts"
input bool            InpAlert     = false;              // alert on new blocks and first returns

#define SIDE_NONE    0              // no block on this bar
#define SIDE_BULL    1              // demand: down candle before up candles
#define SIDE_BEAR    -1             // supply: up candle before down candles
#define RANGE_SPAN   14             // bars of the average range
#define ZONE_FRESH   0              // price has not come back into the zone
#define ZONE_TESTED  1              // price came back, no close through it
#define ZONE_BROKEN  2              // a close went through the far edge
#define DEAD_KEEP    5              // broken zones kept per side
#define EVENT_NEW    1              // a zone became live on the bar
#define EVENT_RETURN 2              // price came back into a fresh zone
#define EVENT_BREAK  4              // a close went through a zone

struct BlockRules
  {
   int               length;        // candles in the run after the block candle
   double            move;          // least move of the run, average ranges
   double            first;         // least body of the block candle, average ranges
   double            other;         // run candle under this body counts both ways
   int               price;         // ENUM_ZONE_PRICE
   int               shift;         // candle that gives the price, 0 = block candle
   int               search;        // candles searched for the deepest wick
  };

struct BlockFound
  {
   int               side;          // SIDE_BULL, SIDE_BEAR or SIDE_NONE
   double            top;           // upper price of the zone
   double            bottom;        // lower price of the zone
   double            mid;           // middle of the zone
   int               origin;        // series index of the candle that gave the price
  };

struct ZoneRec
  {
   int               side;          // SIDE_BULL or SIDE_BEAR
   double            top;           // upper price
   double            bottom;        // lower price
   double            mid;           // middle price
   datetime          born;          // open time of the candle that gave the price
   datetime          start;         // open time of the bar after the run
   int               state;         // ZONE_FRESH, ZONE_TESTED or ZONE_BROKEN
   int               tests;         // times price came back into the zone
   bool              inside;        // the last bar touched the zone
   datetime          lastTest;      // bar of the latest return
   datetime          end;           // bar of the close through it
  };

void RulesClamp(BlockRules &r)
  {
   if(r.search>=r.length)
      r.search=r.length;
   if(r.shift>=r.length)
      r.shift=r.length;
  }

bool IsFlatCandle(const MqlRates &bar)
  {
   return(bar.open==bar.close && bar.open==bar.high && bar.open==bar.low);
  }

double BodyTop(const MqlRates &bar)
  {
   return(bar.close>bar.open ? bar.close : bar.open);
  }

double BodyBottom(const MqlRates &bar)
  {
   return(bar.close>bar.open ? bar.open : bar.close);
  }

double TrueRange(const MqlRates &s[],const int i)
  {
   return(MathMax(s[i].high,s[i-1].close)-MathMin(s[i].low,s[i-1].close));
  }

void RangeAverage(const MqlRates &s[],double &avg[],const int from)
  {
   int n=ArraySize(s);
   ArrayResize(avg,n,1024);
   for(int i=MathMax(from,0); i<n; i++)
     {
      if(i<RANGE_SPAN)
        {
         avg[i]=0.0;
         continue;
        }
      if(i==RANGE_SPAN)
        {
         double sum=0.0;
         for(int k=1; k<=RANGE_SPAN; k++)
            sum+=TrueRange(s,k);
         avg[i]=sum/RANGE_SPAN;
         continue;
        }
      avg[i]=(avg[i-1]*(RANGE_SPAN-1)+TrueRange(s,i))/RANGE_SPAN;
     }
  }

int DeepestLow(const MqlRates &s[],const int from,const int count)
  {
   int    best=0;
   double low=s[from].low;
   for(int i=1; i<=count; i++)
      if(s[from+i].low<=low)
        {
         low=s[from+i].low;
         best=i;
        }
   return(best);
  }

int DeepestHigh(const MqlRates &s[],const int from,const int count)
  {
   int    best=0;
   double high=s[from].high;
   for(int i=1; i<=count; i++)
      if(s[from+i].high>=high)
        {
         high=s[from+i].high;
         best=i;
        }
   return(best);
  }

bool FindBlock(const BlockRules &r,const MqlRates &s[],const double &avg[],const int t,BlockFound &f)
  {
   f.side=SIDE_NONE;
   int b=t-r.length-1;
   if(b<0 || avg[b]<=0.0)
      return(false);
   double unit=avg[b];
   double bo=s[b].open,bc=s[b].close;

   if(!(MathAbs(bc-s[t-1].close)>r.move*unit))
      return(false);
   if(!(MathAbs(bc-bo)>r.first*unit))
      return(false);
   int up=0,down=0;
   for(int k=t-1; k>b; k--)
     {
      if(IsFlatCandle(s[k]))
         continue;
      double o=s[k].open,c=s[k].close;
      if(MathAbs(c-o)<r.other*unit)
        {
         up++;
         down++;
         continue;
        }
      if(c>o)
         up++;
      else
         if(c<o)
            down++;
     }
   if(bc<bo && up==r.length)
      f.side=SIDE_BULL;
   if(bc>bo && down==r.length)
      f.side=SIDE_BEAR;
   if(f.side==SIDE_NONE)
      return(false);

   int step=r.shift;
   if(r.price==ZONE_PRICE_DEEPEST)
      step=(f.side==SIDE_BULL ? DeepestLow(s,b,r.search) : DeepestHigh(s,b,r.search));
   int k=b+step;
   f.origin=k;
   if(r.price==ZONE_PRICE_HIGH_LOW)
     {
      f.top=s[k].high;
      f.bottom=s[k].low;
     }
   else
      if(f.side==SIDE_BULL)
        {
         f.top=BodyTop(s[k]);
         f.bottom=s[k].low;
        }
      else
        {
         f.top=s[k].high;
         f.bottom=BodyBottom(s[k]);
        }
   f.mid=(f.top+f.bottom)/2;
   return(true);
  }

class ZoneTracker
  {
public:
   ZoneRec           live[];        // zones still in force, oldest first
   ZoneRec           dead[];        // broken zones, oldest first
   int               admitted;      // blocks of the found list already taken
   int               newFrom;       // first block taken by the last step
   int               events;        // EVENT_ flags of the last step

   void              Clear(void)
     {
      ArrayResize(live,0);
      ArrayResize(dead,0);
      admitted=0;
      newFrom=0;
      events=0;
     }

   void              CopyFrom(const ZoneTracker &other)
     {
      int n=ArraySize(other.live);
      ArrayResize(live,n,32);
      for(int i=0; i<n; i++)
         live[i]=other.live[i];
      n=ArraySize(other.dead);
      ArrayResize(dead,n,32);
      for(int i=0; i<n; i++)
         dead[i]=other.dead[i];
      admitted=other.admitted;
      newFrom=other.newFrom;
      events=other.events;
     }

   void              Step(const ZoneRec &found[],const int count,const int limit,const datetime t,
                          const double high,const double low,const double close)
     {
      events=0;
      newFrom=admitted;
      while(admitted<count && found[admitted].start<=t)
        {
         if(limit>0)
           {
            Admit(found[admitted],limit);
            events|=EVENT_NEW;
           }
         admitted++;
        }
      int i=0;
      while(i<ArraySize(live))
        {
         bool bull=(live[i].side==SIDE_BULL);
         if(bull ? close<live[i].bottom : close>live[i].top)
           {
            live[i].state=ZONE_BROKEN;
            live[i].end=t;
            Bury(live[i]);
            ArrayRemove(live,i,1);
            events|=EVENT_BREAK;
            continue;
           }
         bool touch=(bull ? low<=live[i].top : high>=live[i].bottom);
         if(touch && !live[i].inside)
           {
            live[i].tests++;
            live[i].lastTest=t;
            if(live[i].state==ZONE_FRESH)
              {
               live[i].state=ZONE_TESTED;
               events|=EVENT_RETURN;
              }
           }
         live[i].inside=touch;
         i++;
        }
     }

   bool              Nearest(const int side,double &top,double &bottom) const
     {
      int best=-1;
      for(int i=0; i<ArraySize(live); i++)
        {
         if(live[i].side!=side)
            continue;
         if(best<0 || (side==SIDE_BULL ? live[i].top>=live[best].top : live[i].bottom<=live[best].bottom))
            best=i;
        }
      if(best<0)
         return(false);
      top=live[best].top;
      bottom=live[best].bottom;
      return(true);
     }

private:

   void              Admit(const ZoneRec &z,const int limit)
     {
      ZoneRec nz=z;
      nz.state=ZONE_FRESH;
      nz.tests=0;
      nz.inside=false;
      nz.lastTest=0;
      nz.end=0;
      Absorb(nz);
      int same=0,oldest=-1;
      for(int i=0; i<ArraySize(live); i++)
         if(live[i].side==nz.side)
           {
            same++;
            if(oldest<0)
               oldest=i;
           }
      if(same>=limit && oldest>=0)
         ArrayRemove(live,oldest,1);
      int n=ArraySize(live);
      ArrayResize(live,n+1,32);
      live[n]=nz;
     }

   void              Absorb(ZoneRec &nz)
     {
      bool again=true;
      while(again)
        {
         again=false;
         for(int i=0; i<ArraySize(live); i++)
           {
            if(!(live[i].bottom<nz.top && live[i].top>nz.bottom))
               continue;
            if(live[i].side==nz.side)
              {
               nz.top=MathMax(nz.top,live[i].top);
               nz.bottom=MathMin(nz.bottom,live[i].bottom);
               nz.born=(datetime)MathMin((long)nz.born,(long)live[i].born);
               nz.mid=(nz.top+nz.bottom)/2;
              }
            ArrayRemove(live,i,1);
            again=true;
            break;
           }
        }
     }

   void              Bury(const ZoneRec &z)
     {
      int n=ArraySize(dead);
      ArrayResize(dead,n+1,32);
      dead[n]=z;
      int same=0,oldest=-1;
      for(int i=0; i<=n; i++)
         if(dead[i].side==z.side)
           {
            same++;
            if(oldest<0)
               oldest=i;
           }
      if(same>DEAD_KEEP)
         ArrayRemove(dead,oldest,1);
     }
  };

#define REACH_BARS   2              // bars a live zone reaches past the last bar
#define SHADE_FRESH  0.35           // fill of a fresh zone over the background
#define SHADE_TESTED 0.20           // fill of a tested zone over the background
#define SHADE_DEAD   0.10           // fill of the last broken zone of a side
#define TAG_FONT     "Arial"        // font of the zone tags
#define TAG_SIZE     8              // font size of the zone tags
#define TAG_SPACING  13             // least distance between two tags, pixels

BlockRules      g_rules;            // engine settings
ENUM_TIMEFRAMES g_tf;               // timeframe the blocks are read on
bool            g_chartTf;          // blocks come from the chart bars
string          g_tfName;           // timeframe name for the tags
string          g_tag;              // object prefix, unique per settings
MqlRates        g_src[];            // bars of the block timeframe, oldest first
double          g_avg[];            // average range of those bars
int             g_srcDone=-1;       // last anchor bar already looked at
datetime        g_srcDoneTime=0;    // its open time, to notice a history change
ZoneRec         g_found[];          // every block found, in anchor order
int             g_foundCount=0;     // blocks in g_found
ZoneTracker     g_done;             // zone state after the last closed chart bar
ZoneTracker     g_view;             // copy with the chart bar in progress applied
int             g_doneBar=-1;       // last chart bar applied to g_done
datetime        g_doneTime=0;       // its open time, to notice a history change
double          g_demTop[];         // buffer: top of the nearest demand zone
double          g_demBottom[];      // buffer: bottom of the nearest demand zon

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