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

 
DroidM # :
Я запутался в том, как я могу получить доступ к нужной свече на более высоком таймфрейме. Например, массив закрытий свечей для 1-минутных свечей - close[].
Моя стратегия выбрала close[8], которая была на уровне 1.69230. Как я могу узнать, на какой свече на графике m5 была отметка 1.69230?

Необходимо использоватьCopyRates.

Пример:

//+------------------------------------------------------------------+
//|                                                     Script 1.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property version   "1.000"
#property script_show_inputs
//--- input parameters
input ENUM_TIMEFRAMES   Inp_period  = PERIOD_D1;   // Timeframe
//---
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   MqlRates rates[];
   ArraySetAsSeries(rates,true);
   int start_pos=0,count=9;
   if(CopyRates(Symbol(),Inp_period,start_pos,count,rates)==count)
     {
      string text="";
      for(int i=0; i<count; i++)
         text=text+"Close #"+IntegerToString(i)+" "+DoubleToString(rates[i].close,Digits())+"\n";
      Print(text);
     }
//---
  }
//+------------------------------------------------------------------+

Результат:

2021.11.13 10:12:04.265 Script 1 (AUDCAD,M20)   Close #0 0.91977
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #1 0.91685
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #2 0.91525
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #3 0.91752
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #4 0.92345
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #5 0.92193
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #6 0.92177
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #7 0.92280
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #8 0.92194
Documentation on MQL5: Timeseries and Indicators Access / CopyRates
Documentation on MQL5: Timeseries and Indicators Access / CopyRates
  • www.mql5.com
CopyRates - Timeseries and Indicators Access - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
Файлы:
Script_1.mq5  3 kb
 
Vladimir Karputov #:

Необходимо использоватьCopyRates.

Пример:

Результат:

Наверное, я запутал вас своим вопросом, я использую ea, которая ищет дивергенцию с помощью полос Боллинджера, при сделке на продажу, максимум и более высокий максимум должны закрыться выше полосы Боллинджера, более высокий максимум - это 1-я свеча, т.е. close[1], а высокая свеча может быть любой свечой от close[5] до close[50], например, максимум находится на close[11], я бы хотел проверить, пересекла ли эта цена (close[11]) полосу Боллинджера и на графике m5.
 
DroidM # :
Наверное, я запутал вас своим вопросом, я использую ea, которая ищет дивергенцию с помощью полос Боллинджера, при сделке на продажу, максимум и более высокий максимум должны закрыться выше полосы Боллинджера, более высокий максимум - это 1-я свеча, т.е. close[1], а высокая свеча может быть любой свечой от close[5] до close[50], например, максимум находится на close[11], я бы хотел проверить, пересекла ли эта цена (close[11]) полосу Боллинджера и на графике m5.

Не спешите с ответом - внимательно изучите мой пример.

 
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 #:

Не спешите с ответом - внимательно изучите мой пример.

Да, я понял, что на audcad m20 вы смогли получить цены закрытия дневных свечей.
Но в моем случае close[11] не будет ни open, ни high, ни low, ни close на свече m5, только между ними, как мне взять индекс свечи m5, которую я хочу проверить?
 

Как получить данные индикатора iFrAMA

Код: 'iFrAMA get value.mq5'

Помните - согласно стилю MQL5, хэндл индикатора должен быть создан в OnInit !!!

Пример:

//+------------------------------------------------------------------+
//|                                             iFrAMA get value.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.000"
//--- input parameters
input group             "FrAMA"
input int                  Inp_FrAMA_ma_period           = 14;             // FrAMA: averaging period
input int                  Inp_FrAMA_ma_shift            = 0;              // FrAMA: horizontal shift of indicator
input ENUM_APPLIED_PRICE   Inp_FrAMA_applied_price       = PRICE_CLOSE;    // FrAMA: type of price
input group                "Additional features"
input bool                 InpPrintLog          = false;       // Print log
//---
int      handle_iFrAMA;                         // variable for storing the handle of the iFrAMA indicator
bool     m_init_error               = false;    // error on InInit
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create handle of the indicator
   handle_iFrAMA=iFrAMA(Symbol(),Period(),Inp_FrAMA_ma_period,
                        Inp_FrAMA_ma_shift,Inp_FrAMA_applied_price);
//--- if the handle is not created
   if(handle_iFrAMA==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iFrAMA 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);
     }
//---
   ChartIndicatorAdd(ChartID(),0,handle_iFrAMA);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   if(handle_iFrAMA!=INVALID_HANDLE)
      IndicatorRelease(handle_iFrAMA);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   if(m_init_error)
      return;
//---
   double frama[];
   ArraySetAsSeries(frama,true);
   int start_pos=0,count=3;
   if(!iGetArray(handle_iFrAMA,0,start_pos,count,frama))
      return;
//---
   string text="";
   int limit=(count>3)?3:count;
   for(int i=0; i<limit; i++)
     {
      text=text+
           " bar #"+IntegerToString(i)+": "+
           " FrAMA "+DoubleToString(frama[i],Digits()+1)+"\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);
  }
//+------------------------------------------------------------------+

Результат:

iFrAMA получить ценность

Рис. 1. iFrAMA get value

Файлы:
 

Пример использования 'CopyRates' и 'MqlRates'

Код: 'CopyRates и MqlRates.mq5'

Мы будем использовать'CopyRates', первую форму вызова:

Вызов по первой позиции и количеству необходимых элементов

int  CopyRates(
   string           symbol_name,       // symbol name
   ENUM_TIMEFRAMES  timeframe,         // period
   int              start_pos,         // start position
   int              count,             // data count to copy
   MqlRates         rates_array[]      // target array to copy
   );

Код:

//+------------------------------------------------------------------+
//|                                       CopyRates and MqlRates.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.00"
//--- 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="";
   for(int i=0; i<count; i++)
     {
      text=text+
           " bar #"+IntegerToString(i)+": "+
           " time "+TimeToString(rates[i].time,TIME_DATE|TIME_MINUTES)+": "+
           " open "+DoubleToString(rates[i].open,Digits())+"\n";
     }
   Comment(text);
  }
//+------------------------------------------------------------------+

Результат:




Documentation on MQL5: Timeseries and Indicators Access / CopyRates
Documentation on MQL5: Timeseries and Indicators Access / CopyRates
  • www.mql5.com
CopyRates - Timeseries and Indicators Access - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
Файлы:
 

Открытие и изменение позиций:

Открытие и изменение позиций

 

Простой советник: на рынке всегда есть две противоположные позиции

Код: 'Open Two Positions.mq5'

//+------------------------------------------------------------------+
//|                                           Open Two Positions.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.000"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
//--- input parameters
input group             "Trading settings"
input uint                 InpStopLoss             = 450;            // Stop Loss
input uint                 InpTakeProfit           = 450;            // Take Profit
input group             "Position size management (lot calculation)"
input double               InpLots                 = 0.01;           // Lots
input group             "Additional features"
input ulong                InpDeviation            = 10;             // Deviation, in Points (1.00045-1.00055=10 points)
input ulong                InpMagic                = 200;            // Magic number
//---
double   m_stop_loss                = 0.0;      // Stop Loss                  -> double
double   m_take_profit              = 0.0;      // Take Profit                -> double
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(Symbol());
   m_trade.SetDeviationInPoints(InpDeviation);
//---
   double point=0.0;
   if(!SymbolInfoDouble(Symbol(),SYMBOL_POINT,point))
      return(INIT_FAILED);
   m_stop_loss                = InpStopLoss                 * point;
   m_take_profit              = InpTakeProfit               * point;
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   int count_buys=0,count_sells=0;
   CalculateAllPositions(count_buys,count_sells);
   if(count_buys==0 || count_sells==0)
     {
      MqlTick tick;
      if(!SymbolInfoTick(Symbol(),tick))
         return;
      if(count_buys==0)
         m_trade.Buy(InpLots,Symbol(),tick.ask,tick.ask-m_stop_loss,tick.ask+m_take_profit);
      if(count_sells==0)
         m_trade.Sell(InpLots,Symbol(),tick.bid,tick.bid+m_stop_loss,tick.bid-m_take_profit);
     }
  }
//+------------------------------------------------------------------+
//| Calculate all positions Buy and Sell                             |
//+------------------------------------------------------------------+
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()==Symbol() && m_position.Magic()==InpMagic)
           {
            if(m_position.PositionType()==POSITION_TYPE_BUY)
               count_buys++;
            if(m_position.PositionType()==POSITION_TYPE_SELL)
               count_sells++;
           }
//---
   return;
  }
//+------------------------------------------------------------------+
Файлы:
 

Уважаемый Владимир,


Я хочу спросить о PostitionCloseBy.

Скажем, сработал BuyStop, он закрывает позицию Sell. Заранее спасибо.