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

WATL

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

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

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

О программе

WATL — это пользовательский индикатор для MetaTrader 5, портированный с открытого индикатора «Waves Auto Trend Indicator» автора idealfx. Индикатор рассчитывает волновые пивоты (семафоры) и автоматические трендовые линии на основе анализа скользящей средней (SMA) и линейно взвешенной скользящей средней (LWMA).

Индикатор отображает три типа пивотов: верхний (High pivot), нижний (Low pivot) и нижнейший (Lowest pivot), каждый отрисовывается стрелкой на графике. Для верхнего и нижнего пивотов строятся трендовые линии сопротивления и поддержки (HTL и LTL), а также прогнозная трендовая линия (FTL).

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

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

НастройкаОписание
High_period Период расчёта для верхней волны (основной период).
Low_period Период расчёта для нижней волны (основной период).
Trigger_Sens Чувствительность триггера определения волны (в пунктах).
ForecastHighTrendLine Включает или отключает отображение прогнозной трендовой линии для верхнего пивота.
StayLinesAfterDelete Если включено, трендовые линии остаются на графике после удаления индикатора.
ShowAuthorLabel Включает или отключает отображение метки автора на графике.
DrawHighPivotSemafor Включает или отключает отрисовку семафора верхнего пивота на графике.
DrawLowPivotSemafor Включает или отключает отрисовку семафора нижнего пивота на графике.
DrawLowestPivotSemafor Включает или отключает отрисовку семафора нижнейшего пивота на графике.
HTL_Draw Включает или отключает отрисовку трендовых линий верхнего пивота (сопротивление и поддержка).
HTL_ResColor Цвет линии сопротивления для верхнего пивота.
HTL_SupColor Цвет линии поддержки для верхнего пивота.
HTL_Style Стиль линий трендовых линий верхнего пивота.
HTL_Width Толщина линий трендовых линий верхнего пивота.
HTL_Ext Коэффициент продления трендовых линий верхнего пивота вправо.
HTL_InMemory Максимальное количество трендовых линий верхнего пивота, сохраняемых на графике.
HTL_MinPivotDifferentIgnore Минимальное количество баров между пивотами, при котором линии верхнего пивота всё ещё строятся.
LTL_Draw Включает или отключает отрисовку трендовых линий нижнего пивота (сопротивление и поддержка).
LTL_ResColor Цвет линии сопротивления для нижнего пивота.
LTL_SupColor Цвет линии поддержки для нижнего пивота.
LTL_Style Стиль линий трендовых линий нижнего пивота.
LTL_Width Толщина линий трендовых линий нижнего пивота.
LTL_Ext Коэффициент продления трендовых линий нижнего пивота вправо.
LTL_InMemory Максимальное количество трендовых линий нижнего пивота, сохраняемых на графике.
LTL_MinPivotDifferentIgnore Минимальное количество баров между пивотами, при котором линии нижнего пивота всё ещё строятся.
HighPivotTextAlarm Включает или отключает текстовое уведомление при появлении верхнего пивота.
HighPivotSoundAlarm Путь к звуковому файлу, воспроизводимому при появлении верхнего пивота.
HighPivotSemaforDrawOffset Смещение стрелки семафора верхнего пивота в пунктах от цены пивота.
HighSemaforSymbol Код стрелки для семафора верхнего пивота.
LowPivotTextAlarm Включает или отключает текстовое уведомление при появлении нижнего пивота.
LowPivotSoundAlarm Путь к звуковому файлу, воспроизводимому при появлении нижнего пивота.
LowPivotSemaforDrawOffset Смещение стрелки семафора нижнего пивота в пунктах от цены пивота.
LowSemaforSymbol Код стрелки для семафора нижнего пивота.
LowestSemaforSymbol Код стрелки для семафора нижнейшего пивота.
FTL_Color Цвет прогнозной трендовой линии.
FTL_Style Стиль линии прогнозной трендовой линии.
FTL_Width Толщина линии прогнозной трендовой линии.
FTL_Ext Коэффициент продления прогнозной трендовой линии вправо.

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

#property version   "1.00"
#property description "Waves Auto Trend Indicator: wave pivots (semafors) and automatic trend lines."
#property description "Open source. Original author: idealfx."

#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots   3

#property indicator_label1  "High pivot"
#property indicator_type1   DRAW_ARROW
#property indicator_color1  clrRed
#property indicator_width1  1

#property indicator_label2  "Low pivot"
#property indicator_type2   DRAW_ARROW
#property indicator_color2  clrDarkGoldenrod
#property indicator_width2  1

#property indicator_label3  "Lowest pivot"
#property indicator_type3   DRAW_ARROW
#property indicator_color3  clrBlueViolet
#property indicator_width3  1

input int  High_period           =70;     // High period
input int  Low_period            =21;     // Low period
input int  Trigger_Sens          =2;      // Trigger sensitivity (points)
input bool ForecastHighTrendLine =true;   // Forecast high trend line
input bool StayLinesAfterDelete  =false;  // Keep lines after indicator removal
input bool ShowAuthorLabel       =true;   // Show author label on chart

input group "***** Semafor Drawing Adjustment"
input bool DrawHighPivotSemafor   =true;  // Draw high pivot semafor
input bool DrawLowPivotSemafor    =true;  // Draw low pivot semafor
input bool DrawLowestPivotSemafor =true;  // Draw lowest pivot semafor

input group "***** High Trend Lines Adjustment"
input bool            HTL_Draw                   =true;         // HTL: draw lines
input color           HTL_ResColor               =clrRed;       // HTL: resistance color
input color           HTL_SupColor               =clrMaroon;    // HTL: support color
input ENUM_LINE_STYLE HTL_Style                  =STYLE_DASH;   // HTL: line style
input int             HTL_Width                  =2;            // HTL: line width
input double          HTL_Ext                    =1.5;          // HTL: extension factor
input int             HTL_InMemory               =10;           // HTL: lines kept on chart
input int             HTL_MinPivotDifferentIgnore=5;            // HTL: min bars between pivots

input group "***** Low Trend Lines Adjustment"
input bool            LTL_Draw                   =true;         // LTL: draw lines
input color           LTL_ResColor               =clrGold;      // LTL: resistance color
input color           LTL_SupColor               =clrGoldenrod; // LTL: support color
input ENUM_LINE_STYLE LTL_Style                  =STYLE_SOLID;  // LTL: line style
input int             LTL_Width                  =1;            // LTL: line width
input double          LTL_Ext                    =1.5;          // LTL: extension factor
input int             LTL_InMemory               =30;           // LTL: lines kept on chart
input int             LTL_MinPivotDifferentIgnore=4;            // LTL: min bars between pivots

input group "***** High Semafor Adjustment"
input bool   HighPivotTextAlarm        =true;         // High pivot: text alert
input string HighPivotSoundAlarm       ="alert.wav";  // High pivot: sound file
input int    HighPivotSemaforDrawOffset=28;           // High pivot: arrow offset (points)
input int    HighSemaforSymbol         =142;          // High pivot: arrow code

input group "***** Low Semafor Adjustment"
input bool   LowPivotTextAlarm         =false;        // Low pivot: text alert
input string LowPivotSoundAlarm        ="";           // Low pivot: sound file
input int    LowPivotSemaforDrawOffset =18;           // Low pivot: arrow offset (points)
input int    LowSemaforSymbol          =141;          // Low pivot: arrow code

input group "***** Lowest Semafor Adjustment"
input int    LowestSemaforSymbol       =115;          // Lowest pivot: arrow code

input group "***** Forecast Trend Line Adjustment"
input color           FTL_Color=clrDeepPink;          // FTL: color
input ENUM_LINE_STYLE FTL_Style=STYLE_DASH;           // FTL: line style
input int             FTL_Width=2;                    // FTL: line width
input double          FTL_Ext  =1.05;                 // FTL: extension factor

#define OBJ_PREFIX "WATL_"
#define FTL_NAME   "WATL_FTL"
#define LAB_NAME   "WATL_Label"

struct SWave
  {
   int               type;       // 1 - up wave (high pivot), 2 - down wave (low pivot)
   datetime          time_start; // wave start time
   datetime          time_end;   // wave end time
   double            price;      // pivot price
   int               bar;        // pivot bar shift at the moment of creation
   datetime          pivot_time; // pivot bar time
  };

struct SLine
  {
   datetime          time1;      // first point time
   double            price1;     // first point price
   datetime          time2;      // second point time
   double            price2;     // second point price
   int               type;       // 1 - resistance, 2 - support
   int               id;         // sequence number
  };

class CWaveChannel
  {
public:
   int               m_fast;        // fast SMA period
   int               m_slow;        // slow LWMA period
   datetime          m_wave_start;  // current wave start time
   datetime          m_wave_new;    // new wave start time
   int               m_wave_type;   // current wave type
   bool              m_new_flag;    // new wave found on the last processed bar
   SWave             m_waves[];     // found waves
   string            m_names[];     // names of created trend lines
   SLine             m_pending[];   // trend lines waiting to be created
   color             m_color_res;   // resistance line color
   color             m_color_sup;   // support line color
   ENUM_LINE_STYLE   m_style;       // line style
   int               m_width;       // line width
   double            m_ext;         // extension factor
   int               m_in_memory;   // number of lines kept on chart
   int               m_min_ignore;  // minimal bars between pivots
   string            m_tag;         // object name tag
   int               m_counter;     // line counter

   void              Reset(void);
  };

void CWaveChannel::Reset(void)
  {
   m_wave_start=0;
   m_wave_new  =0;
   m_wave_type =-1;
   m_new_flag  =false;
   m_counter   =0;
   ArrayResize(m_waves,0);
   ArrayResize(m_names,0);
   ArrayResize(m_pending,0);
  }

double     BufHigh[];
double     BufLow[];
double     BufLowest[];

CWaveChannel *g_channels[3];
string     g_tf;
double     g_pow;
double     g_sens;
int        g_bars=0;

datetime   g_time[];
double     g_high[];
double     g_low[];
double     g_close[];
double     g_weighted[];

datetime   g_done_time=0;
datetime   g_last_bar =0;
bool       g_history  =false;

bool       g_ftl_on  =false;
datetime   g_ftl_time=0;
double     g_ftl_price=0.0;
int        g_ftl_type=0;
bool       g_ftl_req =false;
datetime   g_req_time=0;
double     g_req_price=0.0;
int        g_req_type=0;

int BarShift(datetime time_value,bool exact)
  {
   if(g_bars<=0)
      return(-1);

   int low =0;
   int high=g_bars;
   while(low<high)
     {
      int mid=(low+high)/2;
      if(g_time[mid]<=time_value)
         high=mid;
      else
         low=mid+1;
     }
   if(low>=g_bars)
      return(-1);
   if(exact && g_time[low]!=time_value)
      return(-1);
   return(low);
  }

bool SmaAt(const double &src[],int shift,int period,double &out)
  {
   if(period<1 || shift<0 || shift+period>g_bars)
      return(false);
   double sum=0.0;
   for(int k=0; k<period; k++)
      sum+=src[shift+k];
   out=sum/period;
   return(true);
  }

bool LwmaAt(const double &src[],int shift,int period,double &out)
  {
   if(period<1 || shift<0 || shift+period>g_bars)
      return(false);
   double sum=0.0;
   for(int k=0; k<period; k++)
      sum+=src[shift+k]*(period-k);
   out=sum/(period*(period+1)/2.0);
   return(true);
  }

int WaveTypeAt(int fast,int slow,int shift)
  {
   double sma,lwma;
   if(!SmaAt(g_close,shift,fast,sma))
      return(-1);
   if(!LwmaAt(g_weighted,shift,slow,lwma))
      return(-1);
   double diff=(sma-lwma)*g_pow;
   if(MathAbs(diff)<=g_sens)
      return(0);
   if(diff>0.0)
      return(1);
   if(diff<0.0)
      return(2);
   return(-1);
  }

double FindZeroFromShift(int fast,int slow,int &shift)
  {
   int max_period=MathMax(fast,slow);
   for(int k=0; shift+k<g_bars; k++)
     {
      if(shift+k+max_period>g_bars)
         break;
      if(WaveTypeAt(fast,slow,shift+k)==0)
        {
         shift+=k;
         return((double)g_time[shift]);
        }
     }
   return(-55555);
  }

int FirstWaveFromShift(int fast,int slow,int &shift)
  {
   int max_period=MathMax(fast,slow);
   for(int k=0; shift+k<g_bars; k++)
     {
      if(shift+k+max_period>g_bars)
         break;
      int type=WaveTypeAt(fast,slow,shift+k);
      if(type>0)
        {
         shift+=k;
         return(type);
        }
     }
   return(-55555);
  }

void FindFirstWave(CWaveChannel *channel,int shift)
  {
   if(g_bars-shift<channel.m_slow*2)
      return;
   int type=WaveTypeAt(channel.m_fast,channel.m_slow,shift);
   int start_shift=shift;
   channel.m_wave_start=0;
   channel.m_wave_type =0;

   if(type>0)
     {
      double zero=FindZeroFromShift(channel.m_fast,channel.m_slow,start_shift);
      if(zero<=0.0)
         return;
     }
   else
     {
      type=FirstWaveFromShift(channel.m_fast,channel.m_slow,start_shift);
      if(type<=0)
         return;
      double zero=FindZeroFromShift(channel.m_fast,channel.m_slow,start_shift);
      if(zero<=0.0)
         return;
     }
   channel.m_wave_start=g_time[start_shift];
   channel.m_wave_type =type;
  }

void FindNextWave(CWaveChannel *channel,int shift)
  {
   int type=WaveTypeAt(channel.m_fast,channel.m_slow,shift);
   if(channel.m_wave_start==0 || channel.m_wave_type<=0)
      return;
   if(type<=0 || type==channel.m_wave_type)
     {
      channel.m_wave_new=0;
      return;
     }
   channel.m_wave_new=g_time[shift];
  }

datetime FindPivot(datetime time_start,datetime time_end,int type)
  {
   if(type<1 || time_start==0 || time_end==0)
      return(0);
   int shift_start=BarShift(time_start,true);
   int shift_end  =BarShift(time_end,true);
   if(shift_start<0 || shift_end<0)
      return(0);
   int count=shift_start-shift_end+1;
   if(count<1)
      return(0);
   int best=shift_end;

   if(type==1)
     {
      for(int i=shift_end; i<shift_end+count; i++)
         if(g_high[i]>g_high[best])
            best=i;
      return(g_time[best]);
     }

   if(type==2)
     {
      for(int i=shift_end; i<shift_end+count; i++)
         if(g_low[i]<g_low[best])
            best=i;
      return(g_time[best]);
     }
   return(0);
  }

void AddWave(CWaveChannel *channel)
  {
   int total=ArraySize(channel.m_waves)+1;
   ArrayResize(channel.m_waves,total);
   SWave wave;
   wave.type      =channel.m_wave_type;
   wave.time_start=channel.m_wave_start;
   wave.time_end  =channel.m_wave_new;
   wave.price     =0.0;
   wave.bar       =0;
   wave.pivot_time=0;
   datetime pivot=FindPivot(channel.m_wave_start,channel.m_wave_new,channel.m_wave_type);
   if(pivot!=0)
     {
      int bar=BarShift(pivot,false);
      if(bar>=0)
        {
         wave.bar       =bar;
         wave.pivot_time=pivot;
         if(channel.m_wave_type==1)
            wave.price=g_high[bar];
         else
            if(channel.m_wave_type==2)
               wave.price=g_low[bar];
        }
     }
   channel.m_waves[total-1]=wave;
  }

void CountExtension(double ext,datetime time1,double price1,datetime time2,double price2,
                    datetime &time_ext,double &price_ext)
  {
   int shift1=BarShift(time1,false);
   int shift2=BarShift(time2,false);
   if(shift1<0 || shift2<0)
     {
      time_ext =time2;
      price_ext=price2;
      return;
     }
   int    diff =shift1-shift2;
   int    add  =(int)MathRound(diff*ext);
   double delta=MathAbs(price2-price1);
   if(add==0 || diff==0)
      price_ext=price2;
   else
      if(price2>price1)
         price_ext=NormalizeDouble(price2+add*delta/diff,_Digits);
      else
         if(price2<price1)
            price_ext=NormalizeDouble(price2-add*delta/diff,_Digits);
         else
            price_ext=price2;
   time_ext=g_time[shift2]+(datetime)((long)PeriodSeconds()*add);
  }

double CorrectLine(string name,datetime time_value,double price)
  {
   ResetLastError();
   double value=ObjectGetValueByTime(0,name,time_value,0);
   if(GetLastError()>0 || value==0.0)
      return(0.0);
   double diff=value-price;
   if(MathAbs(diff)<=2.0*_Point)
      return(0.0);
   return(-diff);
  }

void AddLineName(CWaveChannel *channel,string name)
  {
   if(channel.m_in_memory<=0)
     {
      ObjectDelete(0,name);
      return;
     }
   int total=ArraySize(channel.m_names);
   if(total+1>channel.m_in_memory && total>0)
     {
      ObjectDelete(0,channel.m_names[0]);
      ArrayRemove(channel.m_names,0,1);
     }
   total=ArraySize(channel.m_names);
   ArrayResize(channel.m_names,total+1);
   channel.m_names[total]=name;
  }

void CreateTrendLine(CWaveChannel *channel,SLine &line)
  {
   string name=StringFormat("%s%s_%s_%s_%d",OBJ_PREFIX,channel.m_tag,g_tf,
                            (line.type==2 ? "Sup" : "Res"),line.id);
   double price1=NormalizeDouble(line.price1,_Digits);
   double price2=NormalizeDouble(line.price2,_Digits);
   if(!ObjectCreate(0,name,OBJ_TREND,0,line.time1,price1,line.time2,price2))
      return;
   ObjectSetInteger(0,name,OBJPROP_RAY_RIGHT,false);
   ObjectS

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