Любые вопросы новичков по MQL4 и MQL5, помощь и обсуждение по алгоритмам и кодам - страница 2547

 
Tretyakov Rostyslav #:
bar

Подправил код, вышло вот, что


При этом параметр bar, прописал в глобалке.
 
Игорь #:

Подправил код, вышло вот, что


При этом параметр bar, прописал в глобалке.
Код
 
Игорь #:

Если, не трудно, подскажи (так как с макд), у меня в коде всё логично? Желтым цветом отмечен зигзаг, сигнал которого должен подтверждаться стрелочным индикатором, по причинам переписывания индикатора зигзага.   

Вот подправил (как в учебниках) код индикатора зигзаг с дополнительным сигналом, дата "идёт" друг за другом. При этом сигналка работает, а зигзаг не формируется.

#property indicator_chart_window
#property indicator_buffers 12 //4
#property indicator_plots   7 //1
//--- plot ZigZag 
#property indicator_label1  "ZigZag"
#property indicator_type1   DRAW_SECTION
#property indicator_color1  clrRed
#property indicator_style1  STYLE_SOLID
#property indicator_width1  3
//--- plot 
#property indicator_type2   DRAW_ARROW
#property indicator_color2  clrWhite
#property indicator_width3  5
#property indicator_color3  clrLime
#property indicator_width3  2
#property indicator_color4  clrBlue //C'0,128,255'
#property indicator_width4  7
#property indicator_type4   DRAW_ARROW
#property indicator_color5  clrRed //C'192,0,192'
#property indicator_width5  7
#property indicator_type5   DRAW_ARROW
#property indicator_color6  clrDodgerBlue //C'0,128,255'
#property indicator_width6  3
#property indicator_type6   DRAW_ARROW
#property indicator_color7  clrMediumVioletRed //C'192,0,192'
#property indicator_width7  3
#property indicator_type7   DRAW_ARROW
//----------------------------------------------------------------   
int OnInit()
 {
   SetIndexBuffer(0, Lmt, INDICATOR_DATA);
   SetIndexBuffer(1,ZigBuffer,INDICATOR_DATA);
   SetIndexBuffer(2, Up, INDICATOR_DATA);
   SetIndexBuffer(3, Dn, INDICATOR_DATA);
   SetIndexBuffer(4, pUp, INDICATOR_DATA);  
   SetIndexBuffer(5, pDn, INDICATOR_DATA);
///*
   SetIndexBuffer(6, LZZ, INDICATOR_DATA);
   if (DrawZZ)
   {
      PlotIndexSetInteger(6, PLOT_DRAW_TYPE, DRAW_SECTION);
      PlotIndexSetDouble(6, PLOT_EMPTY_VALUE, 0);
   }
   else PlotIndexSetInteger(6, PLOT_DRAW_TYPE, DRAW_NONE);
   ArraySetAsSeries(LZZ, true);
//   */
   PlotIndexSetInteger(0, PLOT_ARROW, 167);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, 0);
   ArraySetAsSeries(Lmt, true);
   PlotIndexSetInteger(2, PLOT_ARROW, 233); // Green up arrow
   PlotIndexSetDouble(2, PLOT_EMPTY_VALUE, 0);
   ArraySetAsSeries(Up, true);

   PlotIndexSetInteger(3, PLOT_ARROW, 234); // Green up arrow
   PlotIndexSetDouble(3, PLOT_EMPTY_VALUE, 0);
   ArraySetAsSeries(Dn, true);
   
   PlotIndexSetInteger(4, PLOT_ARROW, 104); // Green up markers
   PlotIndexSetDouble(4, PLOT_EMPTY_VALUE, 0);
   ArraySetAsSeries(pUp, true);

   PlotIndexSetInteger(5, PLOT_ARROW, 104); // Red down markers
   PlotIndexSetDouble(5, PLOT_EMPTY_VALUE, 0);
   ArraySetAsSeries(pDn, true);

   SetIndexBuffer(7, SA, INDICATOR_CALCULATIONS);
   ArraySetAsSeries(SA, true);
   SetIndexBuffer(8, SM, INDICATOR_CALCULATIONS);
   ArraySetAsSeries(SM, true);
    SetIndexBuffer(9,trend,INDICATOR_CALCULATIONS);
   SetIndexBuffer(10,HighBar,INDICATOR_CALCULATIONS);
   SetIndexBuffer(11,LowBar,INDICATOR_CALCULATIONS);
   
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
   
   if (SR < 2) SR = 2;
   if (SRZZ <= SR)
   {
      Alert("SRZZ should be greater than SR (", SR, ")");
      return(INIT_FAILED);
 
Игорь #:

Вот подправил (как в учебниках) код индикатора зигзаг с дополнительным сигналом, дата "идёт" друг за другом. При этом сигналка работает, а зигзаг не формируется.

Проблема не в OnInit(), а в коде расчета данных.
 
Tretyakov Rostyslav #:
Код
//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2020, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
#property copyright   "Copyright 2000-2024, MetaQuotes Ltd."
#property link        "https://www.mql5.com"
#property description "Moving Average Convergence/Divergence"
#include <MovingAverages.mqh>
//--- indicator settings
#property indicator_separate_window
#property indicator_buffers 6//4
#property indicator_plots   4//2
// /*
#property indicator_type1   DRAW_HISTOGRAM
#property indicator_type2   DRAW_LINE
#property indicator_color1  clrBlue
#property indicator_color2  clrMediumVioletRed
#property indicator_width1  2
#property indicator_width2  1
#property indicator_label1  "MACD"
#property indicator_label2  "Signal"
// */
// //*
#property indicator_type4   DRAW_ARROW
#property indicator_color4  clrWhite
#property indicator_width4  4
#property indicator_label4  "Up signal"
#property indicator_type5   DRAW_ARROW
#property indicator_color3  clrRed
#property indicator_width3  4
#property indicator_label3 "Down signal"
//
// */
sinput string  AA_Params = "Параметры MACD";
input int                InpFastEMA=12;               // Fast EMA period
input int                InpSlowEMA=26;               // Slow EMA period
input int                InpSignalSMA=9;              // Signal SMA period
input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // Applied price
// /*
sinput string  EA_Params = "Параметры дополнительного сигнала";
input uint GSv_range=12;
input int Shift=0; // сдвиг индикатора по горизонтали в барах
input uint  UpLable=170;//значёк верхнего фрактала
input uint  DnLable=170;//значёк нижнего фрактала
// */
//--- indicator buffers
double ExtMacdBuffer[];
double ExtSignalBuffer[];
double ExtFastMaBuffer[];
double ExtSlowMaBuffer[];

int    ExtFastMaHandle;
int    ExtSlowMaHandle;
//
double HighestBuffer[];
double LowestBuffer[];

int    min_rates_total;

// /*
double h,l, bar;
bool cur_h,cur_l;
bool draw_up,draw_dn,initfl;
int  fPoint_i,sPoint_i,s_up,s_dn,drawf,lb;
// */
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
void OnInit()
  {
   min_rates_total=2;

//--- indicator buffers mapping
   SetIndexBuffer(0,ExtMacdBuffer,INDICATOR_DATA);
   SetIndexBuffer(1,ExtSignalBuffer,INDICATOR_DATA);
   SetIndexBuffer(2,LowestBuffer,INDICATOR_DATA);
   SetIndexBuffer(3,HighestBuffer,INDICATOR_DATA);
   SetIndexBuffer(4,ExtFastMaBuffer,INDICATOR_CALCULATIONS);
   SetIndexBuffer(5,ExtSlowMaBuffer,INDICATOR_CALCULATIONS);
//

//---- запрет на отрисовку индикатором пустых значений
   PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0.0);
   PlotIndexSetDouble(2,PLOT_EMPTY_VALUE,NULL);
   PlotIndexSetDouble(3,PLOT_EMPTY_VALUE,NULL);
//--- sets first bar from what index will be drawn
   PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,InpSignalSMA-1);
   PlotIndexSetInteger(2,PLOT_ARROW,DnLable);
   PlotIndexSetInteger(3,PLOT_ARROW,UpLable);
// /*
//---- установка позиции, с которой начинается отрисовка уровней Боллинджера
   PlotIndexSetInteger(2,PLOT_DRAW_BEGIN,min_rates_total);
   PlotIndexSetInteger(3,PLOT_DRAW_BEGIN,min_rates_total);
//---- осуществление сдвига индикатора по горизонтали на Shift
   PlotIndexSetInteger(2,PLOT_SHIFT,Shift);//2
   PlotIndexSetInteger(3,PLOT_SHIFT,Shift);//3
//---- индексация элементов в буферах как в таймсериях
   ArraySetAsSeries(LowestBuffer,true);
   ArraySetAsSeries(HighestBuffer,true);
//--- создание имени для отображения в отдельном подокне и во всплывающей подсказке
//    IndicatorSetString(INDICATOR_SHORTNAME,"GannZIGZAG_Arrows");
// */
//--- name for indicator subwindow label
//  string short_name=StringFormat("MACD(%d,%d,%d)",InpFastEMA,InpSlowEMA,InpSignalSMA);
// IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- get MA handles
   ExtFastMaHandle=iMA(NULL,0,InpFastEMA,0,MODE_EMA,InpAppliedPrice);
   ExtSlowMaHandle=iMA(NULL,0,InpSlowEMA,0,MODE_EMA,InpAppliedPrice);
//   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);

  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
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[])
  {
   OnCalculateOne(rates_total,prev_calculated,time,open,high,low,close,tick_volume,volume,spread);
   OnCalculateTwo(rates_total,prev_calculated,time,open,high,low,close,tick_volume,volume,spread);
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+-----------------------------------------------------------------+
//|                           OnCalculateOne                        |
//+-----------------------------------------------------------------+
// /*
int OnCalculateOne(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[])
  {
   if(rates_total<InpSignalSMA)
      return(0);
//--- not all data may be calculated
   int calculated=BarsCalculated(ExtFastMaHandle);
   if(calculated<rates_total)
     {
      Print("Not all data of ExtFastMaHandle is calculated (",calculated," bars). Error ",GetLastError());
      return(0);
     }
   calculated=BarsCalculated(ExtSlowMaHandle);
   if(calculated<rates_total)
     {
      Print("Not all data of ExtSlowMaHandle is calculated (",calculated," bars). Error ",GetLastError());
      return(0);
     }
//--- we can copy not all data
   int to_copy;
   if(prev_calculated>rates_total || prev_calculated<0)
      to_copy=rates_total;
   else
     {
      to_copy=rates_total-prev_calculated;
      if(prev_calculated>0)
         to_copy++;
     }
//--- get Fast EMA buffer
   if(IsStopped()) // checking for stop flag
      return(0);
   if(CopyBuffer(ExtFastMaHandle,0,0,to_copy,ExtFastMaBuffer)<=0)
     {
      Print("Getting fast EMA is failed! Error ",GetLastError());
      return(0);
     }
//--- get SlowSMA buffer
   if(IsStopped()) // checking for stop flag
      return(0);
   if(CopyBuffer(ExtSlowMaHandle,0,0,to_copy,ExtSlowMaBuffer)<=0)
     {
      Print("Getting slow SMA is failed! Error ",GetLastError());
      return(0);
     }
//---
   int start;
   if(prev_calculated==0)
      start=0;
   else
      start=prev_calculated-1;
//--- calculate MACD
   for(int i=start; i<rates_total && !IsStopped(); i++)
      ExtMacdBuffer[bar]=ExtFastMaBuffer[i]-ExtSlowMaBuffer[i];
//--- calculate Signal
   SimpleMAOnBuffer(rates_total,prev_calculated,0,InpSignalSMA,ExtMacdBuffer,ExtSignalBuffer);
//--- OnCalculate done. Return new prev_calculated.
   return(rates_total);
  }
//  */
 
Люди вопрос, общего характера. Как, кинуть сигнал с мт5 на сайт mql5? Сейчас по евро/баксу на д1 формируется сигнал на продажу, по ходу дела цена будет тестить минимум. На D1.
 
Игорь #:

В коде MACD ничего менять не нужно.

Вам нужно было просто h и l  на ExtMacdBuffer[bar]

HighestBuffer[bar]=ExtMacdBuffer[bar];
LowestBuffer[bar]=ExtMacdBuffer[bar];
 

Добрый день!

Подскажите, пожалуйста, есть ли возможность убрать из Обзора рынка МТ5 колонки Bid и Ask?

Убрать временно - сдвинув их границы влево - получается. Но потом - при запуске терминала, они опять на месте.

Можно что то сделаь?

Спасибо!

 
Tretyakov Rostyslav #:

В коде MACD ничего менять не нужно.

Вам нужно было просто h и l  на ExtMacdBuffer[bar]

MACD исправлен полностью, правда сигнального индюка нет). Однако, спасибо за полученный опыт в программировании MQL5.

 

Как округлить число к ближайшему лоту?

Задача получить меньшее

0.0151 = 0.01

0.0192 = 0.01

0.0201 = 0.02

0.0349 = 0.03

Так не получается

  double lotStep = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
  double lots = NormalizeDouble(0.0151/lotStep,0)*lotStep; // Print = 0.02

Срезать лишнее после сотых?

Задача:

На каждые 5000 депозита при лоте 0.01, повышать лот на 0.01

Сейчас при росте баланса до 7501, лот получается 0.02, а нужен 0.01, пока баланс не станет 10000

P.S. Наверное как решение, подойдёт

nLot = int(AccountInfoDouble(ACCOUNT_BALANCE)/5000)*0.01