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

 

Как использовать торговый класс CSymbolInfo

Код:

//+------------------------------------------------------------------+
//|                                               Display prices.mq5 |
//|                         Copyright © 2018-2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2018-2020, Vladimir Karputov"
#property version   "1.001"
//---
#include <Trade\SymbolInfo.mqh>
//---
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   ResetLastError();
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
   RefreshRates();
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   if(!RefreshRates())
      return;
   Comment("Ask: ",DoubleToString(m_symbol.Ask(),m_symbol.Digits()),"\n",
           "Bid: ",DoubleToString(m_symbol.Bid(),m_symbol.Digits()));
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: ","RefreshRates error");
      return(false);
     }
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: ","Ask == 0.0 OR Bid == 0.0");
      return(false);
     }
//---
   return(true);
  }
//+------------------------------------------------------------------+
Documentation on MQL5: Standard Library / Trade Classes / CSymbolInfo
Documentation on MQL5: Standard Library / Trade Classes / CSymbolInfo
  • www.mql5.com
CSymbolInfo - Trade Classes - Standard Library - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
Файлы:
 
Эй, поскольку я использую циклы для перебора символов и таймфреймов, как я могу размещать ордера, изменять и закрывать их?
 
Ahmad861 :
Эй, поскольку я использую циклы для перебора символов и таймфреймов, как я могу размещать ордера, изменять и закрывать их?

Ваш вопрос не совсем понятен. Я не понимаю вашей цели - вы открываете ПОЗИЦИЮ (не ордер !!!) на символ. Таймфрейм здесь не имеет значения - ПОЗИЦИЯ будет открыта по символу. Другое дело, когда на хеджевом счете хотят торговать сразу несколько стратегий - тогда для каждой стратегии нужно использовать свое "магическое число".

Самый простой пример - Простой пример Одна позиция

How to start with MQL5
How to start with MQL5
  • 2020.07.05
  • www.mql5.com
This thread discusses MQL5 code examples. There will be examples of how to get data from indicators, how to program advisors...
 
Vladimir Karputov:

Ваш вопрос не совсем понятен. Я не понимаю вашей цели - вы открываете ПОЗИЦИЮ (не ордер !!!) на символ. Таймфрейм здесь не имеет значения - ПОЗИЦИЯ будет открыта по символу. Другое дело, когда на хедж-счете хотят торговать сразу несколько стратегий - тогда для каждой стратегии нужно использовать свое "магическое число".

Самый простой пример - Простой пример Одна позиция

Извините, что не совсем понятно объяснил, это скальпинговая стратегия, советник находит сетап на графике М3, а также М5 и открывает позицию, я хочу установить тейк-профит на основе индикатора, в данном случае графика М3, как мне это сделать?

 
Ahmad861 :

Извините, что не совсем понятно объяснил, это скальпинговая стратегия, советник находит сетап на графике M3, а также M5 и открывает позицию, я хочу установить тейк-профит на основе индикатора, в данном случае на графике M3, как мне это сделать?

Если Stop Loss устанавливается по индикатору с таймфрейма M3, то необходимо создать хэндл индикатора и при его создании указать таймфрейм.

Например, так:

//+------------------------------------------------------------------+
//|                                                            1.mq5 |
//|                              Copyright © 2020, Vladimir Karputov |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property link      "https://www.mql5.com"
#property version   "1.00"
//--- input parameters
input group             "MA"
input ENUM_TIMEFRAMES      Inp_MA_period        = PERIOD_M3;   // MA: timeframe
input int                  Inp_MA_ma_period     = 12;          // MA: averaging period
input int                  Inp_MA_ma_shift      = 0;           // MA: horizontal shift
input ENUM_MA_METHOD       Inp_MA_ma_method     = MODE_SMA;    // MA: smoothing type
input ENUM_APPLIED_PRICE   Inp_MA_applied_price = PRICE_CLOSE; // MA: type of price
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create handle of the indicator iMA
   handle_iMA=iMA(m_symbol.Name(),Inp_MA_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(Inp_MA_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()
  {
//---
  }
//+------------------------------------------------------------------+
 

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

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

 
Ahmad861:

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

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

Простой советник со стоп-лоссом и тейк-профитом

How to start with MQL5
How to start with MQL5
  • 2020.03.05
  • www.mql5.com
This thread discusses MQL5 code examples. There will be examples of how to get data from indicators, how to program advisors...
 

Пересечение двух iMAs

Код: ' Пример Пересечение двух иМА.mq5 '

Задача: определить момент пересечения двух iMA.

Код эксперта демонстрирует, как получить значения от двух индикаторов iMA (отображается прочерк для значения "Fast" и три значения для "Slow").

Также при обнаружении пересечения на экран выводится сообщение.

//+------------------------------------------------------------------+
//|                             Example Intersection of two iMAs.mq5 |
//|                        Copyright 2021, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.000"
//--- input parameters
input group             "Moving Average 'Fast'"
input int                  Inp_MA_Fast_ma_period      = 3;           // MA Fast: averaging period
input int                  Inp_MA_Fast_ma_shift       = 0;           // MA Fast: horizontal shift
input ENUM_MA_METHOD       Inp_MA_Fast_ma_method      = MODE_SMA;    // MA Fast: smoothing type
input ENUM_APPLIED_PRICE   Inp_MA_Fast_applied_price  = PRICE_CLOSE; // MA Fast: type of price
input group             "Moving Average 'Slow'"
input int                  Inp_MA_Slow_ma_period      = 12;          // MA Slow: averaging period
input int                  Inp_MA_Slow_ma_shift       = 1;           // MA Slow: horizontal shift
input ENUM_MA_METHOD       Inp_MA_Slow_ma_method      = MODE_SMA;    // MA Slow: smoothing type
input ENUM_APPLIED_PRICE   Inp_MA_Slow_applied_price  = PRICE_CLOSE; // MA Slow: type of price
input group             "Additional features"
input bool                 InpPrintLog                = false;       // Print log
//---
bool     m_init_error               = false;    // error on InInit

int      handle_iMA_Fast;                       // variable for storing the handle of the iMA indicator
int      handle_iMA_Slow;                       // variable for storing the handle of the iMA indicator
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create handle of the indicator iMA
   handle_iMA_Fast=iMA(Symbol(),Period(),Inp_MA_Fast_ma_period,Inp_MA_Fast_ma_shift,
                       Inp_MA_Fast_ma_method,Inp_MA_Fast_applied_price);
//--- if the handle is not created
   if(handle_iMA_Fast==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator (\"Fast\") for the symbol %s/%s, error code %d",
                  Symbol(),Period(),GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//--- create handle of the indicator iMA
   handle_iMA_Slow=iMA(Symbol(),Period(),Inp_MA_Slow_ma_period,Inp_MA_Slow_ma_shift,
                       Inp_MA_Slow_ma_method,Inp_MA_Slow_applied_price);
//--- if the handle is not created
   if(handle_iMA_Slow==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator (\"Slow\") for the symbol %s/%s, error code %d",
                  Symbol(),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()
  {
//---
   double ma_fast[],ma_slow[];
   ArraySetAsSeries(ma_fast,true);
   ArraySetAsSeries(ma_slow,true);
   int start_pos=0,count=3;
   if(!iGetArray(handle_iMA_Fast,0,start_pos,count,ma_fast) || !iGetArray(handle_iMA_Slow,0,start_pos,count,ma_slow))
      return;
   string ima_values="";
   for(int i=0; i<count; i++)
      ima_values=ima_values+IntegerToString(i)+": Fast "+DoubleToString(ma_fast[i],Digits()+1)+", Slow "+DoubleToString(ma_slow[i],Digits()+1)+"\n";
   string ima_intersections="no crossing";
   if(ma_fast[1]<ma_slow[1] && ma_fast[0]>ma_slow[0])
      ima_intersections="crossing up";
   else
      if(ma_fast[1]>ma_slow[1] && ma_fast[0]<ma_slow[0])
         ima_intersections="crossing down";
   Comment(ima_values+"\n"+ima_intersections);
  }
//+------------------------------------------------------------------+
//| 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);
  }
//+------------------------------------------------------------------+


Результат:

Пример Пересечение двух iMA

How to start with MQL5
How to start with MQL5
  • 2020.03.05
  • www.mql5.com
This thread discusses MQL5 code examples. There will be examples of how to get data from indicators, how to program advisors...
 

Мы ждем, пока размер текущего бара достигнет указанного размера

Код: Пример Размер текущей свечи.mq5

//+------------------------------------------------------------------+
//|                                  Example Current candle size.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property version   "1.001"
//+------------------------------------------------------------------+
//| Enum Pips Or Points                                              |
//+------------------------------------------------------------------+
enum ENUM_PIPS_OR_POINTS
  {
   pips=0,     // Pips (1.00045-1.00055=1 pips)
   points=1,   // Points (1.00045-1.00055=10 points)
  };
//--- input parameters
input ENUM_PIPS_OR_POINTS  InpPipsOrPoints   = pips;           // Pips Or Points:
input uint                 InpCandleSize     = 80;             // Candle: Size
//---
double   m_candle_size           = 0.0;      // Candle: Size               -> double
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- tuning for 3 or 5 digits
   int digits_adjust=1;
   if(Digits()==3 || Digits()==5)
      digits_adjust=10;
   double m_adjusted_point=Point()*digits_adjust;
   if(InpPipsOrPoints==pips) // Pips (1.00045-1.00055=1 pips)
     {
      m_candle_size              = InpCandleSize               * m_adjusted_point;
     }
   else // Points (1.00045-1.00055=10 points)
     {
      m_candle_size              = InpCandleSize               * Point();
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| 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;
//--- signal search
   if(MathAbs(rates[0].open-rates[0].close)>=m_candle_size)
     {
      //--- the current candle has reached the specified size
      //--- Your code is here ...
      int d=0;
     }
  }
//+------------------------------------------------------------------+
Файлы:
 
Итак, когда размер бара достигнут, как мы можем заставить его вызвать покупку или продажу?
Причина обращения: