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

 
Vladimir Karputov:
Что не так? Покажите свою идею в виде картинки

Скриншот

Скриншот___1

Файлы:
Screenshot_.png  19 kb
 
GeorgeReji :

Спасибо за уточняющий рисунок. Еще один вопрос: пересечение цены и индикатора iMA должно проверяться на баре "0" или "1"?

 
Vladimir Karputov:

Спасибо за уточняющий рисунок. Еще один вопрос: пересечение цены и индикатора iMA должно проверяться на баре "0" или "1"?

На баре 0 текущая цена покупки или продажи должна быть равна значению индикатора в зависимости от покупки или продажи
 
GeorgeReji :
На баре 0 текущие цены покупки или продажи должны быть равны значению индикатора в зависимости от покупки или продажи

Я вас понял. Только сразу предупреждаю: никогда не используйте условие "цена равна значению индикатора". Используйте условие "цена пересекла индикатор".

Код будет чуть позже...

 

Закрыть позицию на пересечении цены и iMA

Код 'Закрыть позицию на пересечении цены и iMA.mq5'

//+------------------------------------------------------------------+
//|    Close a position at the intersection of the price and iMA.mq5 |
//|                              Copyright © 2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property version   "1.000"
/*
   barabashkakvn Trading engine 3.154
*/
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class

//--- input parameters
input group             "MA Fast"
input int                  Inp_MA_ma_period     = 10;          // MA: averaging period
input int                  Inp_MA_ma_shift      = 0;           // MA: horizontal shift
input ENUM_MA_METHOD       Inp_MA_ma_method     = MODE_EMA;    // MA: smoothing type
input ENUM_APPLIED_PRICE   Inp_MA_applied_price = PRICE_CLOSE; // MA: type of price
input group             "Additional features"
input bool     InpPrintLog          = false;       // Print log
input uchar    InpFreezeCoefficient = 1;           // Coefficient (if Freeze==0 Or StopsLevels==0)
input ulong    InpDeviation         = 10;          // Deviation, in Points (1.00045-1.00055=10 points)
input ulong    InpMagic             = 300;         // Magic number
//---
int      handle_iMA;                            // variable for storing the handle of the iMA indicator

bool     m_need_close_buy           = false;    // close all buy positions
bool     m_need_close_sell          = false;    // close all sell positions
bool     m_init_error               = false;    // error on InInit
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- forced initialization of variables
   m_need_close_buy           = false;    // close all buy positions
   m_need_close_sell          = false;    // close all sell positions
   m_init_error               = false;    // error on InInit
//---
   ResetLastError();
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
   m_trade.SetDeviationInPoints(InpDeviation);
//--- create handle of the indicator iMA
   handle_iMA=iMA(m_symbol.Name(),Period(),Inp_MA_ma_period,Inp_MA_ma_shift,
                  Inp_MA_ma_method,Inp_MA_applied_price);
//--- if the handle is not created
   if(handle_iMA==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator for the symbol %s/%s, error code %d",
                  m_symbol.Name(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      m_init_error=true;
      return(INIT_SUCCEEDED);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   if(m_init_error)
      return;
//---
   if(m_need_close_buy || m_need_close_sell)
     {
      int      count_buys           = 0;
      int      count_sells          = 0;
      CalculateAllPositions(count_buys,count_sells);
      //---
      if(m_need_close_buy)
        {
         if(count_buys>0)
           {
            ClosePositions(POSITION_TYPE_BUY);
            return;
           }
         else
            m_need_close_buy=false;
        }
      if(m_need_close_sell)
        {
         if(count_sells>0)
           {
            ClosePositions(POSITION_TYPE_SELL);
            return;
           }
         else
            m_need_close_sell=false;
        }
     }
//---
   double ma[];
   MqlRates rates[];
   ArraySetAsSeries(ma,true);
   ArraySetAsSeries(rates,true);
   int start_pos=0,count=3;
   if(!iGetArray(handle_iMA,0,start_pos,count,ma) || CopyRates(m_symbol.Name(),Period(),start_pos,count,rates)!=count)
     {
      return;
     }
   else
     {
      if(rates[0].open<rates[0].close && rates[0].open<ma[0] && rates[0].close>ma[0])
         m_need_close_buy=true;
      else
         if(rates[0].open>rates[0].close && rates[0].open>ma[0] && rates[0].close<ma[0])
            m_need_close_sell=true;
     }
//---
  }
//+------------------------------------------------------------------+
//| 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))
     {
      if(InpPrintLog)
         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
      if(InpPrintLog)
         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);
  }
//+------------------------------------------------------------------+
//| 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.Symbol()==m_symbol.Name() && m_position.Magic()==InpMagic)
            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
                     if(InpPrintLog)
                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","BUY PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());
                 }
               else
                 {
                  if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                     if(InpPrintLog)
                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","SELL PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());
                 }
              }
  }
//+------------------------------------------------------------------+
//| Calculate all positions                                          |
//+------------------------------------------------------------------+
void CalculateAllPositions(int &count_buys,int &count_sells)
  {
   count_buys  = 0;
   count_sells = 0;
   for(int i=PositionsTotal()-1; i>=0; i--)
      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==InpMagic)
           {
            if(m_position.PositionType()==POSITION_TYPE_BUY)
              {
               count_buys++;
              }
            else
              {
               count_sells++;
              }
           }
  }
//+------------------------------------------------------------------+
 
Я хочу узнать ID графика определенного символа и таймфрейма, как мне это сделать?
 
Ahmad861 :
Я хочу узнать, каков идентификатор графика определенного символа и таймфрейма, как мне это сделать?

ChartID - это идентификатор графика, и он никак не связан с символом или таймфреймом. Если есть график, то у него есть идентификатор.

 
Vladimir Karputov:

ChartID - это идентификатор графика, и он никак не связан с символом или таймфреймом. Если есть график, то у него есть идентификатор.

О, я вижу.

 
RZAMK:

спасибо.

Но вы приводили этот код на предыдущих страницах.

Возможно, я не до конца объяснил, что имел в виду. Яне ищу в истории закрытые позиции.

Я хочу найти цену открытия последней позиции, которая все еще открыта, и взять другую позицию или позиции в соответствии с ее ценой.

Вот

//|                                                                  |
//+------------------------------------------------------------------+
double YoungestShortPositionPrice(const string symbol, const int MagicNumber) //Gewinn der Gesamtposition
  {
   double Price=0;
   datetime time=D'01.01.1970';
//--- in allen offenen Positionen suchen

   int i = PositionsTotal();
   while(i-->0)
     {
      //--- Parameter der Order
      ulong  position_ticket=PositionGetTicket(i);// das Ticket der Position
      PositionSelectByTicket(position_ticket);

      string position_symbol=PositionGetString(POSITION_SYMBOL); // Symbol
      ulong  magic=PositionGetInteger(POSITION_MAGIC); // MagicNumber der Position
      double position_lot=PositionGetDouble(POSITION_VOLUME);
      ENUM_POSITION_TYPE type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
      datetime opentime = (datetime)PositionGetInteger(POSITION_TIME);
      double position_price=PositionGetDouble(POSITION_PRICE_OPEN);

      //--- wenn die MagicNumber übereinstimmt, sind Stop Loss und Take Profit nicht gesetzt
      if(position_symbol==symbol
         && MagicNumber==magic
         && time < opentime
         && type == POSITION_TYPE_SELL
        )
        {
         time=opentime;
         Price = position_price;
        }
     }
   return(Price);
  }
 

Я пытался задать этот вопрос в другой статье, но, похоже, никто не смог на него ответить. Я буду использовать 2 полосы Боллинджера. Отклонения 2,5 и 1,0, я буду проверять, находится ли закрытие первой свечи выше полосы Боллинджера 2,5, и я установил цикл, идущий от 5 до 50. Этот цикл будет проверять, если любое из закрытий от close[5] до close[5] находится выше полосы Боллинджера 2,5. Я не могу понять, что делать с этими двумя условиями.

1. Все свечи между close[1] и свечой цикла 5-50 должны быть выше определенного отклонения полосы Боллинджера.

2. Хотя бы одна свеча должна быть ниже определенного уровня.

Я приведу пример с картинкой ниже.

Здесь видно, что close[1] находится выше полосы Боллинджера 2,5, а проходя по свечному контуру, мы видим, что close[23] закрывается выше полосы 2,5. Синяя полоса Боллинджера - это отклонение 1.0, и, как вы можете видеть на рисунке, все свечи от close[1] до close[23] находятся выше нижней полосы 1.0, и по крайней мере одна свеча закрывается ниже верхней полосы 1.0.

Пожалуйста, помогите с этим

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