mql4: кодирование пустого буфера в строке

поэтому я немного кодирую, и теперь у меня пустой буфер. Я хочу спросить, как чувствовать EMPTY_BUFFER, поэтому, если использовать строку IF == EMPTY BUFFER, то FILL IT.. я уже пробовал кодировать, но все еще не заполняю пустой буфер.

#property strict
#property indicator_level1 75.0
#property indicator_level2 25.0
#property indicator_levelcolor LimeGreen
#property indicator_levelwidth 1
#property indicator_levelstyle 0

#property indicator_separate_window
#property indicator_buffers 5
#property indicator_color1 Green
#property indicator_color2 Red
#property indicator_color3 Blue
#property indicator_color4 Green
#property indicator_color5 Red

extern string howtouse= "scalping in m5";
extern string contact = "[email protected]";
extern string created = "created by reza rahmad";
extern int       barsToProcess=100;
double ExtMapBuffer1[];
double ExtMapBuffer2[];
double ExtMapBuffer3[];
double buy[];
double sell[];
int values;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- 
   SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(0,ExtMapBuffer1);

   SetIndexStyle(1,DRAW_LINE);
   SetIndexBuffer(1,ExtMapBuffer2);

   SetIndexStyle(2,DRAW_LINE);
   SetIndexBuffer(2,ExtMapBuffer3);

   SetIndexStyle(3,DRAW_NONE);
   SetIndexBuffer(3,buy);
   SetIndexEmptyValue(3,0.0);
   SetIndexStyle(4,DRAW_ARROW,EMPTY,3,Magenta);
   SetIndexArrow(4,234);
   SetIndexBuffer(4,sell);
   SetIndexEmptyValue(4,0.0);

// initialization of the generator of random numbers
   ObjectCreate("sig",OBJ_TEXT,0,0,0,0,0);
   ObjectSetText("sig","TAHAN",10,"Times New Roman",Magenta);

   ObjectCreate("sig1",OBJ_LABEL,0,0,0,0,0);

   ObjectSet("sig1",OBJPROP_XDISTANCE,750);
   ObjectSet("sig1",OBJPROP_YDISTANCE,20);
   ObjectSetText("sig1","created by reza rahmad  scalping use in tf 5m",10,"Times New Roman",Magenta);

//---
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int deinit()
  {

   ObjectDelete("tare");
   ObjectDelete("tarmid");
   ObjectDelete("tare1");
   ObjectDelete("sig");
   ObjectDelete("sig1");
   return(0);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()

  {

   int counted_bars=IndicatorCounted(),
   limit;

   if(counted_bars>0)
      counted_bars--;

   limit=Bars-counted_bars;

   if(limit>barsToProcess)
      limit=barsToProcess;

   for(int i=0;i<limit;i++)
     {

  double main5   = iStochastic( NULL, PERIOD_M5, 14, 3, 3, MODE_SMMA, 0, MODE_MAIN,   i );
  double signal5 = iStochastic( NULL, PERIOD_M5, 14, 3, 3, MODE_SMMA, 0, MODE_SIGNAL, i );
  double ma20    = iMA(         NULL, PERIOD_M5, 20, 0,    MODE_SMA, PRICE_CLOSE, 0 );
  double ma5     = iMA(         NULL, PERIOD_M5,  5, 0,    MODE_SMA, PRICE_CLOSE, 0 );

  ExtMapBuffer1[i] = EMPTY_VALUE;
  ExtMapBuffer2[i] = EMPTY_VALUE;

  if (  main5   > signal5
     && High[0] > ma5
     ){
        ExtMapBuffer1[i] = ( ( Close[i+1] + Close[i] ) / 2 );
        values           = 1;
     }
  if (  main5  < signal5
     && Low[0] < ma5
     ){
        ExtMapBuffer2[i] = ( ( Close[i+1] + Close[i] ) / 2 );
        values           = 2;
     }

пример изображения

Пример изображения


person Reza Rahmad    schedule 14.10.2014    source источник
comment
Пожалуйста, Реза, не могли бы вы также опубликовать свой код для всех #-директив(ы) строк заголовков CustomIndicator, установки соответствующих буферов и их инициализации? Спасибо   -  person user3666197    schedule 14.10.2014
comment
я уже добавил весь код, можете ли вы помочь с пустым буфером? и заполнить пробел   -  person Reza Rahmad    schedule 15.10.2014
comment
Проверьте Ответ, Реза, и не стесняйтесь задавать вопросы. Надеюсь, вы сочтете это полезным для своего кодирования.   -  person user3666197    schedule 15.10.2014


Ответы (1)


Как понимать EMPTY_VALUE в пользовательских индикаторах MQL4?

Соглашение MQL4 заключается в том, чтобы не рисовать/не показывать CustomIndicator-линейные сегменты от/до баров, где CustomIndicator-storageBuffer содержит специально распознаваемое "Empty_Value" == { EMPTY_VALUE | a value pre-set via SetIndexEmptyValue() }.

По умолчанию "Empty_Value" равно EMPTY_VALUE.

Ключевым шагом является этот трюк:

    if (  main5  < signal5
       && Low[0] < ma5
       ){
          ExtMapBuffer2[i]  = ( ( Close[i+1] + Close[i] ) / 2 ); // .CALC/.STO
          values            = MAIN_UNDER_SIGNAL;                 // .SET
          if (  values_PREV!= MAIN_UNDER_SIGNAL ){               // ? WAS A FLIP
                values_PREV = MAIN_UNDER_SIGNAL;                 //   .SET
                ExtMapBuffer3[i+1] = ExtMapBuffer1[i+1];         //   .STO[i+1]
                ExtMapBuffer3[i  ] = ExtMapBuffer2[i  ];         //   .STO[i+0]
             }
        }

Рекомендуемые изменения в контексте кода New-MQL4 приведены здесь:

// ------------------------------------------------------------------------------------
// FOR AN EA-INTEGRATION INTERFACE, ref. below
// ------------------------------------------------------------------------------------
#property strict                                           // check this against OnCalculate() syntax requirement

#property indicator_separate_window
//roperty indicator_level1         75.0                    // N/A for aPriceDOMAIN line
//roperty indicator_level2         25.0                    // N/A for aPriceDOMAIN line
//roperty indicator_levelcolor     clrLimeGreen
//roperty indicator_levelwidth      1
//roperty indicator_levelstyle      0

//roperty indicator_buffers         5                      // not used
#property indicator_buffers         3
#property indicator_color1         clrGreen
#property indicator_color2         clrRed
#property indicator_color3         clrDimGray
/*roperty indicator_color4         Green                   // not used
#property indicator_color5         Red                     // not used
*/
#property description         "Scalping in M5 Custom Indicator......................"
#property description         "How to use it ......................................."
#property description         "How to setup ........................................"

extern string howtouse      = "scalping in M5";            // "New"-MQL4 shows comments in dialog box
extern string contact       = "[email protected]";    // Contact Email
extern string created       = "created by reza rahmad";    // copyright notice
extern int    barsToProcess = 100;                         // Bars To Process ( Depth )
       double ExtMapBuffer1[],
              ExtMapBuffer2[],
              ExtMapBuffer3[];
       double buy[];
       double sell[];
       int    values,
              values_PREV = EMPTY;                         // <STATE-FULL>-logic

#define       MAIN_ABOVE_SIGNAL   1
#define       MAIN_UNDER_SIGNAL   2

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit() {
    IndicatorShortName( "SigREZ( " + DoubleToStr( barsToProcess, 0 ) + " )");
    IndicatorDigits(    Digits + 1 );                      // override default decimal points
                                                           // to be distinguishable once AVG(Close1,Close0) values are calculated 
    SetIndexStyle(      0, DRAW_LINE );                    // MAIN_ABOVE_SIGNAL
    SetIndexBuffer(     0, ExtMapBuffer1 );                // segments for values == 1
    SetIndexDrawBegin(  0, barsToProcess );

    SetIndexStyle(      1, DRAW_LINE );                    // MAIN_UNDER_SIGNAL
    SetIndexBuffer(     1, ExtMapBuffer2 );                // segments for values == 2
    SetIndexDrawBegin(  1, barsToProcess );

    SetIndexStyle(      2, DRAW_LINE );                    // EMPTY_SEGMENTs
    SetIndexBuffer(     2, ExtMapBuffer3 );
    SetIndexDrawBegin(  2, barsToProcess );
 /* 
    SetIndexStyle(      3, DRAW_NONE );                    // not used
    SetIndexBuffer(     3, buy );
    SetIndexEmptyValue( 3, 0.0 );

    SetIndexStyle(      4, DRAW_ARROW, EMPTY, 3, Magenta );
    SetIndexArrow(      4, 234 );
    SetIndexBuffer(     4, sell );
    SetIndexEmptyValue( 4, 0.0 );
 */ 
 // ----------------------------------------------------------------------------------
 // initialization of the generator of random numbers
 // ----------------------------------------------------------------------------------

    ObjectCreate(  "sig", OBJ_TEXT, 0, 0, 0, 0, 0 );
    ObjectSetText( "sig", "TAHAN", 10, "Times New Roman", Magenta );

    ObjectCreate(  "sig1", OBJ_LABEL, 0, 0, 0, 0, 0 );
    ObjectSet(     "sig1", OBJPROP_XDISTANCE, 750 );
    ObjectSet(     "sig1", OBJPROP_YDISTANCE,  20 );
    ObjectSetText( "sig1", "created by reza rahmad  scalping use in tf 5m", 10, "Times New Roman", Magenta );
    return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int deinit() {
    ObjectDelete( "tare" );
    ObjectDelete( "tarmid" );
    ObjectDelete( "tare1" );
    ObjectDelete( "sig" );
    ObjectDelete( "sig1" );
    return(0);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start() {
    int      limit        = Bars,
             counted_bars = IndicatorCounted();
    if (     counted_bars > 0 ) counted_bars--;
    limit -= counted_bars;

    if (  limit > barsToProcess ) limit = barsToProcess;

    for (  int i = 0; i < limit; i++ ) {

           double main5   = iStochastic( NULL, PERIOD_M5, 14, 3, 3, MODE_SMMA, 0, MODE_MAIN,   i );
           double signal5 = iStochastic( NULL, PERIOD_M5, 14, 3, 3, MODE_SMMA, 0, MODE_SIGNAL, i );
           double ma20    = iMA(         NULL, PERIOD_M5, 20, 0,    MODE_SMA, PRICE_CLOSE, 0 );
           double ma5     = iMA(         NULL, PERIOD_M5,  5, 0,    MODE_SMA, PRICE_CLOSE, 0 );

           if (  main5   > signal5
              && High[0] > ma5
              ){
                 ExtMapBuffer1[i]  = ( ( Close[i+1] + Close[i] ) / 2 ); // .CALC/.STO
                 values            = MAIN_ABOVE_SIGNAL;                 // .SET
                 if (  values_PREV!= MAIN_ABOVE_SIGNAL ){               // ? WAS A FLIP
                       values_PREV = MAIN_ABOVE_SIGNAL;                 //   .SET
                       ExtMapBuffer3[i+1] = ExtMapBuffer2[i+1];         //   .STO[i+1]
                       ExtMapBuffer3[i  ] = ExtMapBuffer1[i  ];         //   .STO[i+0]
                    }
               }
           if (  main5  < signal5
              && Low[0] < ma5
              ){
                 ExtMapBuffer2[i]  = ( ( Close[i+1] + Close[i] ) / 2 ); // .CALC/.STO
                 values            = MAIN_UNDER_SIGNAL;                 // .SET
                 if (  values_PREV!= MAIN_UNDER_SIGNAL ){               // ? WAS A FLIP
                       values_PREV = MAIN_UNDER_SIGNAL;                 //   .SET
                       ExtMapBuffer3[i+1] = ExtMapBuffer1[i+1];         //   .STO[i+1]
                       ExtMapBuffer3[i  ] = ExtMapBuffer2[i  ];         //   .STO[i+0]
                    }
               }
        }
  }

Инструмент для более безопасной интеграции MQL4. Интерфейс между советником и пользовательским индикатором.

Из-за особенностей синтаксиса iCustom() и порядка параметров намного безопаснее создать шаблон интерфейса копирования/вставки в качестве раздела заголовка для эксперта. , прямо на этапе разработки пользовательского индикатора, который подготовит все необходимые детали для контракта safe-call-API (независимо от того, насколько он технически слаб)

Этот инструмент-шаблон позволяет избежать бесчисленных проблем и потери производительности при отладке синтаксически возможных, но неправильных вызовов iCustom() из-за передачи неверных, плохо смешанных параметров (отсутствующий-один/неправильное-значение/неправильный-порядок/. .. )

                                                // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
                                                // COPY/PASTE.START
                                                // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
                                                // CALL-er SIDE INTERFACE |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
                                                // 
                                                // #define sIndicatorPathNAME             "#AliceInTheWonderlands_msMOD_0.00"
                                                // 
                                                // //_____________________________________INPUT(s)
                                                // // NONE                             // n/a
                                                // 
                                                // //_____________________________________OUTPUT(s):
                                                // #define iOutputDoubleOpenBUFFER     0
                                                // #define iOutputDoubleHighBUFFER     1
                                                // #define iOutputDoubleLowBUFFER      2
                                                // #define iOutputDoubleCloseBUFFER    3
                                                // #define iOutputDoubleVolumeBUFFER   4
                                                // #define iOutputDoubleTimeBUFFER     5
                                                // 
                                                //                            double  iCustom(  _Symbol,                      // string       symbol,           // symbol:                                                 Symbol name on the data of which the indicator will be calculated. NULL means the current symbol.
                                                //                                              PERIOD_CURRENT,               // int          timeframe,        // timeframe
                                                //                                              sIndicatorPathNAME,           // string       name,             // path/name of the custom indicator compiled program:     Custom indicator compiled program name, relative to the root indicators directory (MQL4/Indicators/). If the indicator is located in subdirectory, for example, in MQL4/Indicators/Examples, its name must be specified as "Examples\\indicator_name" (double backslash "\\"must be specified as separator instead of a single one).
                                                //                                              <<N/A>>,                      // ...[1]       ...,              // custom indicator [1]-st  input parameters (if necessary)
                                                //                                                                            // ...[2+]                        // custom indicator further input parameters (if necessary)
                                                //                                              <iOutputDouble*BUFFER>,       // int          mode,             // line index:                                             Line index. Can be from 0 to 7 and must correspond with the index, specified in call of the SetIndexBuffer() function.
                                                //                                              i                             // int          bar_shift         // shift
                                                //                                              );
                                                // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
                                                // COPY/PASTE.END
                                                // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

Остальные пробелы возникают из-за дизайна кода. Продемонстрированный подход с использованием построения строки с тройным буфером полностью соответствует заданному Вопросу.

Оставшаяся проблема связана с алгоритмизацией бизнес-логики, которая была закодирована O/P в виде независимых последовательных последовательностей if(){...}-конструкторов, которые просто не способны должным образом обрабатывать все существующие Переходы Tri-State-FSA.

Indicator_Line

person user3666197    schedule 15.10.2014
comment
спасибо, сэр, но все еще есть проблема, у него все еще есть пробел dropbox.com/ s/ewinfh7ymjf1pew/hasil.png?dl=0 - person Reza Rahmad; 16.10.2014
comment
Конечно, причина не в построении строк с тройным буфером, а в ваших последовательных, независимых if(), используемых в алгоритмизации, поскольку они не охватывают эти случаи (переход состояния трехсостояния-FSA ). - person user3666197; 24.10.2014