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

 
Vladimir Karputov:

Алгоритм: выдаем команду 'ChartOpen' -> проверяем значение, если значение больше '0' -> пробуем шаблон с помощью команды 'ChartApplyTemplate'.

Код: ChartOpen ChartApplyTemplate.mq5

Спасибо за помощь, все работает отлично. Но иногда стратегия по моей логике выполняется еще через 3 свечи или около того, и ChartOpen ChartApplyTemplete выполняется снова и тот же график открывается снова, как я могу закодировать его так, чтобы если график уже открыт, не открывать его снова, Спасибо
 
GeorgeReji :
Советник

Код: Пример Bullish Bearish.mq5

Чтобы получить OHLC от советника, оптимально запросить CopyRates к массиву структуры MqlRates. Примените к массиву

- теперь в массиве 'rates' элемент [0] соответствует крайнему правому бару на графике.

//+------------------------------------------------------------------+
//|                                      Example Bullish Bearish.mq5 |
//|                              Copyright © 2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property version   "1.000"
//--- input parameters
input int      Input1=9;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   Comment("");
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   MqlRates rates[];
   ArraySetAsSeries(rates,true);
   int start_pos=0,count=3;
   if(CopyRates(Symbol(),Period(),start_pos,count,rates)!=count)
      return;
//---
   string text=(rates[0].open<rates[0].close)?"Bullish":"Bearish";
   Comment(text);
  }
//+------------------------------------------------------------------+


Результат:

Пример Бычий Медвежий

Documentation on MQL5: Timeseries and Indicators Access / CopyRates
Documentation on MQL5: Timeseries and Indicators Access / CopyRates
  • www.mql5.com
Gets history data of MqlRates structure of a specified symbol-period in specified quantity into the rates_array array. The elements ordering of the copied data is from present to the past, i.e., starting position of 0 means the current bar. If you know the amount of data you need to copy, it should better be done to a statically allocated...
Файлы:
 
Ahmad861 :
Спасибо за помощь, все работает нормально. Но иногда стратегия по моей логике выполняется еще через 3 свечи или около того и снова выполняется ChartOpen ChartApplyTemplete и снова открывается тот же график, как я могу закодировать это так, чтобы если график уже открыт, не открывать его снова, Спасибо.

Ведите учет открытых графиков (точнее, ведите учет не номеров графиков, а учет действий: символ "такой-то и такой-то", таймфрейм "такой-то и такой-то" уже открыт.

 
Vladimir Karputov:

Код: Пример "Бычье-медвежье".mq5

Чтобы получить OHLC от советника, оптимально запросить CopyRates к массиву структуры MqlRates. Применить к массиву

- теперь в массиве 'rates' элемент [0] соответствует крайнему правому бару на графике.


Результат:


Не обычные бычьи или медвежьи свечи, а небольшие свечи с большими фитилями с обеих сторон
 
Ahmad861 :
Не обычные бычьи или медвежьи свечи, а небольшие свечи с крупными фитилями с обеих сторон.

Вы должны взять мой пример и внести в него изменения самостоятельно. Я не вижу вашего кода. Я не вижу вашего желания кодить.

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

double   BB_pSize = NormalizeDouble((BB_2_Upper[1]-BB_2_Lower[1])/_Point,2);
double   BB_MinSize = 300.00;

    
    
    
if(BB_pSize>=BB_MinSize)Alert("YES");
else Alert("NO");

Это отлично работает, когда я тестирую на скрипте и запускаю, но я использую это в логике моего советника, и даже если условие ложно, код выполняется без каких-либо проблем

Bollinger Bands ®
Bollinger Bands ®
  • www.mql5.com
Bollinger Bands ® technical indicator (BB) is similar to Envelopes. The only difference is that the bands of Envelopes are plotted a fixed distance (%) away from the moving average, while the Bollinger Bands are plotted a certain number of standard deviations away from it. Standard deviation is a measure of volatility, therefore Bollinger Bands...
 
GeorgeReji :
Я использую полосы Боллинджера и перед торговлей проверяю, что расстояние между верхней и нижней полосой Боллинджера составляет минимум 30 пунктов.

Это отлично работает, когда я тестирую на скрипте и запускаю, но я использую это в логике моего советника, и даже если условие ложно, код выполняется без каких-либо проблем

В чем заключается ваш вопрос?

 

Пример: как получить значение индикатора iSAR в советнике.

Код: iSAR Get Value.mq5

ВНИМАНИЕ: В OnInit мы получаем хэндл индикатора (тип 'int') - делаем это ОДИН раз. Далее мы получаем значения индикатора с помощью CopyBuffer.

Код советника:

//+------------------------------------------------------------------+
//|                                               iSAR Get Value.mq5 |
//|                              Copyright © 2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property version   "1.000"
//--- input parameters
input group                "SAR"
input double            Inp_SAR_step          = 0.02;       // SAR: price increment step - acceleration factor
input double            Inp_SAR_maximum       = 0.2;        // SAR: maximum value of step
input group                "Additional features"
input bool              InpPrintLog          = false;       // Print log
//---
int    handle_iSAR;                          // variable for storing the handle of the iSAR indicator
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create handle of the indicator iSAR
   handle_iSAR=iSAR(Symbol(),Period(),Inp_SAR_step,Inp_SAR_maximum);
//--- if the handle is not created
   if(handle_iSAR==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iSAR indicator 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)
  {
//---
   if(handle_iSAR!=INVALID_HANDLE)
      IndicatorRelease(handle_iSAR);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   double sar[];
   MqlRates rates[];
   ArraySetAsSeries(sar,true);
   ArraySetAsSeries(rates,true);
   int start_pos=0,count=2;
   if(!iGetArray(handle_iSAR,0,start_pos,count,sar) || CopyRates(Symbol(),Period(),start_pos,count,rates)!=count)
      return;
//---
   string text="";
   int limit=(count>2)?2:count;
   for(int i=0; i<limit; i++)
     {
      text=text+
           " bar #"+IntegerToString(i)+": "+
           " sar "+DoubleToString(sar[i],Digits())+((sar[i]>=rates[i].high)?" UP":" DOWN")+
           "\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))
     {
      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);
  }
//+------------------------------------------------------------------+


Результат:

iSAR Получить значение

Documentation on MQL5: Timeseries and Indicators Access / CopyBuffer
Documentation on MQL5: Timeseries and Indicators Access / CopyBuffer
  • www.mql5.com
Counting of elements of copied data (indicator buffer with the index buffer_num) from the starting position is performed from the present to the past, i.e., starting position of 0 means the current bar (indicator value for the current bar). When copying the yet unknown amount of data, it is recommended to use a dynamic array as a buffer[]...
Файлы:
 

Проблема: одновременно может существовать только одна позиция. Проверка одинакова для неттинга и хеджевых счетов.

Мы проверяем наличие позиции по символу, а по магическому номеру проверки нет.

Код: IsPositionExists.mq5


//+------------------------------------------------------------------+
//|                                             IsPositionExists.mq5 |
//|                              Copyright © 2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property version   "1.000"
#include <Trade\PositionInfo.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
//--- input parameters
input int      Input1=9;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   if(!IsPositionExists("EURUSD"))
     {
      //--- open positions "EURUSD"
     }
   else
     {
      return;
     }
//---
   if(!IsPositionExists("USDJPY"))
     {
      //--- open positions "USDJPY"
     }
   else
     {
      return;
     }
//---
  }
//+------------------------------------------------------------------+
//| Is position exists                                               |
//+------------------------------------------------------------------+
bool IsPositionExists(const string symbol)
  {
   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()==symbol)
            return(true);
//---
   return(false);
  }
//+------------------------------------------------------------------+
Файлы:
 
Уважаемый Владимир, не могли бы вы помочь мне сделать советник только с сигналами фрактального индикатора. и носить SL и TP и трейлинг. для скальпинговой торговли. надеюсь, что это может обеспечить лучшие цвета в мире mql5. Вы очень хороший программист.

10:21

Уважаемый Владимир, вы можете помочь мне сделать советник, основанный на сигналах только от фрактальных индикаторов. и использовать SL, TP и трейлинг. для скальпинга. Надеюсь, это увеличит цвет в мире MQL5. Вы очень хороший программист.

10:22

надеюсь вы мне поможете просто поделиться. с кодовой базой фрактального индикатора только для каждой сделки. если есть знак фрактала то открывается если нет то опережает. и выставляю отложенные ордера выше линии фрактала от зоны пробоя.

10:26

Фактически, каждый раз, когда происходит сделка, фрактал будетфункционировать. Например, фрактал выше, сделка будет продавать дан SL и TP.
Документация по MQL5: Константы, перечисления и структуры / Именованные константы / Предопределенные макроподстановки
Документация по MQL5: Константы, перечисления и структуры / Именованные константы / Предопределенные макроподстановки
  • www.mql5.com
//| Expert initialization function                                   | //| Expert deinitialization function                                 | //| Expert tick function                                             | //| test1                                                            |...
Причина обращения: