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

 

Простой советник Три iMA

Код: Simple EA Three iMA.mq5

Вы совершаете грубую ошибку: в MQL5 работа с получением данных индикатора разделена на два этапа.

  1. Шаг 1: создаем HANDL индикатора (ЭТО ДЕЛАЕТСЯ ТОЛЬКО ОДИН РАЗ - В OnInit !!!).
  2. Шаг 2: получить данные (как правило, это делается в OnTick ().

//+------------------------------------------------------------------+
//|                                              Simple EA Three iMA |
//|                              Copyright © 2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property version   "1.000"
//---
#include <Trade\Trade.mqh>
//---
CTrade         m_trade;                      // object of CTrade class
//--- input parameters
input int                  Inp_Small_MA_ma_period        = 20;          // Small MA: averaging period
input int                  Inp_Small_MA_ma_shift         = 0;           // Small MA: horizontal shift
input ENUM_MA_METHOD       Inp_Small_MA_ma_method        = MODE_EMA;    // Small MA: smoothing type
input ENUM_APPLIED_PRICE   Inp_Small_MA_applied_price    = PRICE_CLOSE; // Small MA: type of price
input int                  Inp_Middle_MA_ma_period       = 50;          // Middle MA: averaging period
input int                  Inp_Middle_MA_ma_shift        = 0;           // Middle MA: horizontal shift
input ENUM_MA_METHOD       Inp_Middle_MA_ma_method       = MODE_EMA;    // Middle MA: smoothing type
input ENUM_APPLIED_PRICE   Inp_Middle_MA_applied_price   = PRICE_CLOSE; // Middle MA: type of price
input int                  Inp_Big_MA_ma_period          = 1000;        // Big MA: averaging period
input int                  Inp_Big_MA_ma_shift           = 0;           // Big MA: horizontal shift
input ENUM_MA_METHOD       Inp_Big_MA_ma_method          = MODE_EMA;    // Big MA: smoothing type
input ENUM_APPLIED_PRICE   Inp_Big_MA_applied_price      = PRICE_CLOSE; // Big MA: type of price
//---
input ushort   InpStopLossBuy    = 100;      // Stop Loss Buy, in points (1.00045-1.00055=10 points)
input ushort   InpTakeProfitBuy  = 100;      // Take Profit Buy, in points (1.00045-1.00055=10 points)
input ushort   InpStopLossSell   = 100;      // Stop Loss Sell, in points (1.00045-1.00055=10 points)
input ushort   InpTakeProfitSell = 100;      // Take Profit Sell, in points (1.00045-1.00055=10 points)
//---
double   m_stop_loss_buy            = 0.0;      // Stop Loss Buy           -> double
double   m_take_profit_buy          = 0.0;      // Take Profit Buy         -> double
double   m_stop_loss_sell           = 0.0;      // Stop Loss Sell          -> double
double   m_take_profit_sell         = 0.0;      // Take Profit Sell        -> double

int      handle_iMA_Small;                      // variable for storing the handle of the iMA indicator
int      handle_iMA_Middle;                     // variable for storing the handle of the iMA indicator
int      handle_iMA_Big;                        // variable for storing the handle of the iMA indicator

datetime m_prev_bars                = 0;        // "0" -> D'1970.01.01 00:00';
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   m_trade.SetExpertMagicNumber(159);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(Symbol());
   m_trade.SetDeviationInPoints(30);
//---
   m_stop_loss_buy         = InpStopLossBuy     * Point();
   m_take_profit_buy       = InpTakeProfitBuy   * Point();
   m_stop_loss_sell        = InpStopLossSell    * Point();
   m_take_profit_sell      = InpTakeProfitSell  * Point();
//--- create handle of the indicator iMA
   handle_iMA_Small=iMA(Symbol(),Period(),Inp_Small_MA_ma_period,Inp_Small_MA_ma_shift,
                        Inp_Small_MA_ma_method,Inp_Small_MA_applied_price);
//--- if the handle is not created
   if(handle_iMA_Small==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator (\"Small\") for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//--- create handle of the indicator iMA
   handle_iMA_Middle=iMA(Symbol(),Period(),Inp_Middle_MA_ma_period,Inp_Middle_MA_ma_shift,
                         Inp_Middle_MA_ma_method,Inp_Middle_MA_applied_price);
//--- if the handle is not created
   if(handle_iMA_Middle==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator (\"Middle\") for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//--- create handle of the indicator iMA
   handle_iMA_Big=iMA(Symbol(),Period(),Inp_Big_MA_ma_period,Inp_Big_MA_ma_shift,
                      Inp_Big_MA_ma_method,Inp_Big_MA_applied_price);
//--- if the handle is not created
   if(handle_iMA_Big==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator (\"Big\") for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- we work only at the time of the birth of new bar
   datetime time_0=iTime(Symbol(),Period(),0);
   if(time_0==m_prev_bars)
      return;
   m_prev_bars=time_0;

   if(PositionsTotal()>0)
      return;
//---
   double SmallMovingAverageArray[],MiddleMovingAverageArray[],BigMovingAverageArray[];
   ArraySetAsSeries(SmallMovingAverageArray,true);
   ArraySetAsSeries(MiddleMovingAverageArray,true);
   ArraySetAsSeries(BigMovingAverageArray,true);
   int start_pos=0,count=6;
   if(!iGetArray(handle_iMA_Small,0,start_pos,count,SmallMovingAverageArray) ||
      !iGetArray(handle_iMA_Middle,0,start_pos,count,MiddleMovingAverageArray) ||
      !iGetArray(handle_iMA_Big,0,start_pos,count,BigMovingAverageArray))
     {
      return;
     }

   MqlTick tick;
   if(!SymbolInfoTick(Symbol(),tick))
      return;

   if(SmallMovingAverageArray[1]<MiddleMovingAverageArray[1]&&MiddleMovingAverageArray[1]<BigMovingAverageArray[1])
     {
      m_trade.Buy(1.00,Symbol(),tick.ask,tick.ask-m_stop_loss_buy,tick.ask+m_take_profit_buy);
      return;
     }

   if(SmallMovingAverageArray[1]>MiddleMovingAverageArray[1]&&MiddleMovingAverageArray[1]>BigMovingAverageArray[1])
     {
      m_trade.Sell(1.00,Symbol(),tick.bid,tick.bid+m_stop_loss_sell,tick.bid-m_take_profit_sell);
      return;
     }
  }
//+------------------------------------------------------------------+
//| 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);
  }
//+------------------------------------------------------------------+
Файлы:
 
Кто-нибудь может помочь мне построить вертикальные линии и линии тренда на графике на основе закрытия определенных свечей, например, close[10] и close[1], вертикальные линии на обеих свечах и линия тренда, соединяющая их обе. Спасибо
 
GeorgeReji :
Кто-нибудь может помочь мне построить вертикальные линии и линии тренда на графике на основе закрытия определенных свечей, например, close[10] и close[1], вертикальные линии на обеих свечах и линия тренда, соединяющая их обе. Спасибо

Вот код (используем Lines of specific candles.mq5)

Линии специфических свечей

Почти полностью использован код из справки (с). Введена небольшая оптимизация (для уменьшения количества перерисовываемых объектов) и проверка на наличие объектов (проверяем каждые три секунды: если одна из линий удаляется, создаем ее снова).

Вертикальные линии создаются в'VLineCreate'. Линия тренда создается в'TrendCreate'. Перемещение вертикальных линий осуществляется в'VLineMove', а линия тренда перемещается путем перемещения опорных точек в'TrendPointChange'.

Файлы:
 
Я здесь новичок. Есть ли у вас совет, как мне лучше всего оценить и измерить производительность между различными экспертами и сигналами, которые я запускаю через несколько недель?
 
Magnus Thysell :
Я здесь новичок. Есть ли у вас совет, как мне лучше всего оценить и измерить производительность между различными экспертами и сигналами, которые я запускаю через несколько недель?

Внимательно прочитайте первое сообщение этой темы. Вы обратились не по адресу.

 
Vladimir Karputov:

Вот код (используйте Lines of specific candles.mq5)


Код из справки (s) используется практически полностью. Введена небольшая оптимизация (для уменьшения количества перерисовываемых объектов) и проверка наличия объектов (проверяем каждые три секунды: если одна из линий удаляется, создаем ее снова).

Вертикальные линии создаются в'VLineCreate'. Линия тренда создается в'TrendCreate'. Перемещение вертикальных линий осуществляется в'VLineMove', а линия тренда перемещается путем перемещения точек привязки в'TrendPointChange'.

Спасибо, прояснил для меня ситуацию.
 
Как можно закодировать свечи heiken ashi? Например, используя CopyClose для копирования в aray close[] и если close[1]>ma11[1] - это логика, как я должен кодировать это?
 
GeorgeReji :
Как можно закодировать свечи heiken ashi? Например, используя CopyClose для копирования в aray close[] и если close[1]>ma11[1] - это логика, как я должен это закодировать?

Уточните: Вы спрашиваете о каком типе программы - советник или индикатор?

 
Vladimir Karputov:

Уточните: Вы спрашиваете о каком типе программы - советник или индикатор?

Я хочу использовать heiken ashi в советнике, но не понимаю, как получить OHLC heiken ashi

 
GeorgeReji :

Я хочу использовать heiken ashi в советнике, но не знаю, как получить OHLC для heiken ashi.

Является ли heiken ashi индикатором? Где ссылка на индикатор?

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