Как начать работу с MQL5 - страница 27

 
Vladimir Karputov:

Возможная идея: применить фракталы. Возможно, с фракталами картина станет яснее...

Это определенно поможет мне, но я не понимаю, как проверить, находится ли фрактал выше полосы Боллинджера.

 
Ahmad861 :

Это, безусловно, поможет мне, но я не понимаю, как проверить, находится ли фрактал выше полосы Боллинджера.

Покажите картинку, пожалуйста.

 
Vladimir Karputov:

Покажите картинку, пожалуйста.

Как вы можете видеть, левая вертикальная линия закрывается фракталом под полосой Боллинджера, а правая вертикальная линия имеет закрытие свечи 1 под полосой Боллинджера, код, который я использовал ранее, проверял цены закрытия под полосой bb, но теперь интегрирует фракталы, я не могу понять, как, поскольку некоторые фрактальные значения имеют случайные числа или пусты.

 
Vladimir Karputov:

Покажите картинку, пожалуйста.

Мне удалось разобраться с этим, используя !=EMPTY_VALUE для проверки того, пуст ли массив, содержащий значения фракталов, или нет

 
Ahmad861 :

Как вы можете видеть, левая вертикальная линия закрывается фракталом под полосой Боллинджера, а правая вертикальная линия имеет закрытие свечи 1 под полосой Боллинджера, код, который я использовал ранее, проверял цены закрытия под полосой bb, но теперь интегрирует фракталы, я не могу понять, как, поскольку некоторые фрактальные значения имеют случайные числа или пустые.

Да, фракталы могут содержать '0.0' или 'EMPTY_VALUE'. Пример:

Код: 'iFractals.mq5'

//+------------------------------------------------------------------+
//|                                                    iFractals.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property version   "1.000"
//--- input parameters
input int         InputBars=9;
//---
int      handle_iFractals;             // variable for storing the handle of the iFractals indicator
bool     m_init_error      = false;    // error on InInit
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- forced initialization of variables
   m_init_error            = false;    // error on InInit
//--- create handle of the indicator iFractals
   handle_iFractals=iFractals(Symbol(),Period());
//--- if the handle is not created
   if(handle_iFractals==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iFractals indicator for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      m_init_error=true;
      return(INIT_SUCCEEDED);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   if(m_init_error)
      return;
//---
   double upper[],lower[];
   ArraySetAsSeries(upper,true);
   ArraySetAsSeries(lower,true);
   int start_pos=0,count=6;
   if(!iGetArray(handle_iFractals,UPPER_LINE,start_pos,count,upper) || !iGetArray(handle_iFractals,LOWER_LINE,start_pos,count,lower))
      return;
//---
   string text="";
   for(int i=0; i<count; i++)
     {
      //---
      string text_upper="";
      if(upper[i]==0.0 || upper[i]==EMPTY_VALUE)
         text_upper="";
      else
         text_upper=DoubleToString(upper[i],Digits());
      //---
      string text_lower="";
      if(lower[i]==0.0 || lower[i]==EMPTY_VALUE)
         text_lower="";
      else
         text_lower=DoubleToString(lower[i],Digits());
      //---
      text=text+IntegerToString(i)+"#: "+"Upper "+text_upper+", Lower "+text_lower+"\n";
     }
   Comment(text);
  }
//+------------------------------------------------------------------+
//| Get value of buffers                                             |
//+------------------------------------------------------------------+
bool iGetArray(const int handle,const int buffer,const int start_pos,
               const int count,double &arr_buffer[])
  {
   bool result=true;
   if(!ArrayIsDynamic(arr_buffer))
     {
      PrintFormat("ERROR! EA: %s, FUNCTION: %s, this a no dynamic array!",__FILE__,__FUNCTION__);
      return(false);
     }
   ArrayFree(arr_buffer);
//--- reset error code
   ResetLastError();
//--- fill a part of the iBands array with values from the indicator buffer
   int copied=CopyBuffer(handle,buffer,start_pos,count,arr_buffer);
   if(copied!=count)
     {
      //--- if the copying fails, tell the error code
      PrintFormat("ERROR! EA: %s, FUNCTION: %s, amount to copy: %d, copied: %d, error code %d",
                  __FILE__,__FUNCTION__,count,copied,GetLastError());
      //--- quit with zero result - it means that the indicator is considered as not calculated
      return(false);
     }
   return(result);
  }
//+------------------------------------------------------------------+


Результат:

iFractals

Файлы:
iFractals.mq5  9 kb
 

Как закрыть позицию определенного типа

Код 'Close Positions Type.mq5'

Код выполняется в виде скрипта (ВНИМАНИЕ! Это не советник !!!). Код закрывает все позиции выбранного типа ПО ЛЮБОМУ СИМВОЛУ И ЛЮБОМУ МАГИЧЕСКОМУ ЧИСЛУ.

//+------------------------------------------------------------------+
//|                                         Close Positions Type.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property version   "1.000"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
CPositionInfo  m_position;                   // trade position object
CTrade         m_trade;                      // trading object
#property script_show_inputs
input ENUM_POSITION_TYPE InpPositionType  = POSITION_TYPE_BUY; // Close all position ...
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   ClosePositions(InpPositionType);
  }
//+------------------------------------------------------------------+
//| Close positions                                                  |
//+------------------------------------------------------------------+
void ClosePositions(const ENUM_POSITION_TYPE pos_type)
  {
   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions
      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if(m_position.PositionType()==pos_type)
           {
            if(m_position.PositionType()==POSITION_TYPE_BUY)
              {
               if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                  Print(__FILE__," ",__FUNCTION__,", ERROR: ","BUY PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());
              }
            if(m_position.PositionType()==POSITION_TYPE_SELL)
              {
               if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                  Print(__FILE__," ",__FUNCTION__,", ERROR: ","SELL PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());
              }
           }
  }
//+------------------------------------------------------------------+
Файлы:
 
Vladimir Karputov:

Да, фракталы могут содержать '0.0' или 'EMPTY_VALUE'. Пример:

Код: 'iFractals.mq5'


Результат:


Я узнал, как использовать фракталы, и это помогло мне в создании советника, но я возвращаюсь к своей первоначальной проблеме: график должен иметь форму V, в то время как свечи не обязательно образуют V.


 

Максимальная цена индикатора в видимом окне

Код: ChartGetDouble.mq5

Задача: в подокне с номером '1' найти максимальное значение окна

//+------------------------------------------------------------------+
//|                                               ChartGetDouble.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property version   "1.00"
#property script_show_inputs
//--- input parameters
input int   InpSubWindow   = 1;        // Subwindow number
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   Print(ChartGetDouble(ChartID(),CHART_PRICE_MAX,InpSubWindow));
  }
//+------------------------------------------------------------------+


Результат:

2021.06.10 05:33:34.362  ChartGetDouble (USDCAD,M15)    57.3267
Файлы:
 
Vladimir Karputov:

Начните с небольшой проблемы: опишите алгоритм "уровня". Начните воплощать свою идею в MQL5-коде. Тогда я помогу.

Вот что я имел в виду под уровнями, как можно автоматизировать процедуру проверки того, выступала ли цена в прошлом в качестве уровня поддержки или сопротивления

 
Ahmad861 :

Вот что я имел в виду под уровнями, как я могу автоматизировать процедуру проверки того, выступала ли цена в прошлом в качестве уровня поддержки или сопротивления

Задача № 1: Определите, на какую глубину вам нужно просканировать рынок.

Причина обращения: