Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1318

 
Kira27:

Please tell me which class to inherit your class from in order to use all the methods of these

to use all the methods of these classes inside of your class, without creating objects inside of your class?

Inheritance means creating a class.

 

Hi all!
I have an indicator - written in mql5 which I would like to use to create an EA.
When I create an EA, I can't find the buffers I need, it feels like I don't have them at all.
I have to do it this way:

  {
//--- indicator buffers mapping 
   SetIndexBuffer(2,BuyBuffer,INDICATOR_DATA);
   ResetLastError(); 

double   handle3 = 0; 
double   handle4 = 0;
double   UP = 0;
double   DW = 0;

for (int i=1; i<11; i++)
   {
      UP = iCustom(NULL,0,"StepMA_NRTR",Length,Kv,StepSize,Percentage,Switch,Shift,2,i); 
      DW = iCustom(NULL,0,"StepMA_NRTR",Length,Kv,StepSize,Percentage,Switch,Shift,3,i); 
 
      if (handle3==0)   
      if (UP != EMPTY_VALUE)
      handle3=1;

      if (handle4==0)   
      if (UP != EMPTY_VALUE)
      handle4=1;
      
      if (handle3>0 && handle4)
      break;      
   }  
   
Comment(DoubleToString(handle3,Digits())+"\n"+DoubleToString(handle3,Digits()));
   return(INIT_SUCCEEDED);
  }

No matter how I change or add an iCustom line - I keep getting the same thing in the log:

2021.06.26 17:59:42.251 Proba (EURUSD,M15) 1.00000

And the comment: 1.00000 and 1.00000 again.

Help me understand - is it suitable for creating an EA, or do I need to refine it, or maybe I'm doing something wrong?


Files:
StepMA_NRTR.mq5  13 kb
 

In MT5 it is used differently. Take a look at the example in the help.

iCustom

Returns the handle of the specified custom indicator.

https://www.mql5.com/ru/docs/indicators/icustom

Документация по MQL5: Технические индикаторы / iCustom
Документация по MQL5: Технические индикаторы / iCustom
  • www.mql5.com
iCustom - Технические индикаторы - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
Aleksei Stepanenko:

In MT5 it is used differently. Take a look at the example in the help.

iCustom

Returns the handle of the specified custom indicator.

https://www.mql5.com/ru/docs/indicators/icustom

I've already read this documentation, but I'm not quite sure where.... , or how to put in the buffer and plug number?

I am just starting to program and ask you to be lenient with me.

I'm beginning to suspect that this requires an additional function

int copy=CopyBuffer(MA_handle,0,0,rates_total,Label1Buffer); 

Please explain.... where .... and how....?

 
Sprut 185:

Hi all!
I have an indicator - written in mql5 which I would like to use to create an EA.
When I create an EA, I can't find the buffers I need, it feels like I don't have them at all.
I have to do it this way:

No matter how I change or add an iCustom line - I keep getting the same thing in the log:

2021.06.26 17:59:42.251 Proba (EURUSD,M15) 1.00000

And the comment: 1.00000 and 1.00000 again.

Help me understand - is it suitable for creating an EA, or do I need to refine it, or maybe I'm doing something wrong?


Code:

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   double up_buffer[],dn_buffer[],buy_buffer[],sell_buffer[];
   ArraySetAsSeries(up_buffer,true);
   ArraySetAsSeries(dn_buffer,true);
   ArraySetAsSeries(buy_buffer,true);
   ArraySetAsSeries(sell_buffer,true);
   int start_pos=0,count=3;
   if(!iGetArray(handle_iCustom,0,start_pos,count,up_buffer) ||
      !iGetArray(handle_iCustom,1,start_pos,count,dn_buffer) ||
      !iGetArray(handle_iCustom,2,start_pos,count,buy_buffer) ||
      !iGetArray(handle_iCustom,3,start_pos,count,sell_buffer))
      return;
//---
   string text=" | UpBuffer | DnBuffer | BuyBuffer | SellBuffer"+"\n";
   for(int i=0; i<count; i++)
     {
      text=text+"#"+IntegerToString(i)+" | "+DoubleToString((up_buffer[i]==EMPTY_VALUE?0.0:up_buffer[i]),Digits())
           +" | "+DoubleToString((dn_buffer[i]==EMPTY_VALUE?0.0:dn_buffer[i]),Digits())
           +" | "+DoubleToString((buy_buffer[i]==EMPTY_VALUE?0.0:buy_buffer[i]),Digits())
           +" | "+DoubleToString((sell_buffer[i]==EMPTY_VALUE?0.0:sell_buffer[i]),Digits())+"\n";
     }
   Comment(text);
  }

Result:


Files:
 
Sprut 185:

Hi all!
I have an indicator - written in mql5 - that I would like to use to create an EA.

Here I made it - it seems to work! (where yellow is for buffers)

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

I also need a stop loss(I couldn't figure out why it closed immediately).

BTCUSDM1 3

BTCUSDM1 4

//+------------------------------------------------------------------+
//|                                                    Sprut 185.mq5 |
//|                                  Copyright 2021, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#define    UNO_MAGIC 2344701
//---
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\AccountInfo.mqh>
//---
double            m_adjusted_point;             // point value adjusted for 3 or 5 points
CTrade            m_trade;                      // trading object
CSymbolInfo       m_symbol;                     // symbol info object
CPositionInfo     m_position;                   // trade position object
CAccountInfo      m_account;                    // account info wrapper
//---
enum PRICE_MODE
  {
   HighLow,     // High/Low
   CloseClose   // Close/Close
  };
//---
input group      "---- : StepMA_NRTR:  ----"
input int        Length        = 10;      // Volty Length
input double     Kv            = 1.0;     // Sensivity Factor
input int        StepSize      = 0;       // Constant Step Size (if need)
input double     Percentage    = 0;       // Percentage of Up/Down Moving
input PRICE_MODE Switch        = HighLow; // High/Low Mode Switch (more sensitive)
input int        Shift         = 0;       // Shift
input group      "---- : Parameters:  ----"
input uint       InpStopLoss   = 90;      // : Stop Loss
input uint       InpTakeProfit = 36;      // : Take Profit
input double     InpLots       = 0.1;     // : Lots
input bool       InpClOp       = true;    // : Close opposite
//---
int      price_uno;           //
double   m_stop_loss   = 0.0; // Stop Loss
double   m_take_profit = 0.0; // Take Profit
datetime m_last_open   = 0;   // "0" -> D'1970.01.01 00:00';
int StepMA_NRTR_Handle;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit(void)
  {
//--- initialize common information
   if(!m_symbol.Name(Symbol()))             // sets symbol name
      return(false);
   RefreshRates();
   m_trade.SetExpertMagicNumber(UNO_MAGIC); // magic
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(Symbol());
//--- tuning for 3 or 5 digits
   int digits_adjust=1;
   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)
      digits_adjust=10;
   m_adjusted_point=m_symbol.Point()*digits_adjust;
//--- set default deviation for trading in adjusted points
   m_stop_loss   = InpStopLoss*m_adjusted_point;
   m_take_profit = InpTakeProfit*m_adjusted_point;
//--- set default deviation for trading in adjusted points
   m_trade.SetDeviationInPoints(3*digits_adjust);
//---- получение хендла индикатора StepMA_NRTR
   StepMA_NRTR_Handle=iCustom(NULL,0,"StepMA_NRTR",Length,Kv,StepSize,Percentage,Switch,Shift);
   if(StepMA_NRTR_Handle==INVALID_HANDLE)
      Print(" Не удалось получить хендл индикатора StepMA_NRTR");
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(void)
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
      return;
//---
   if(!SearchTradingSignalsOpen())
     {
      return;
     }
  }
//+------------------------------------------------------------------+
//| Check for open position conditions                               |
//+------------------------------------------------------------------+
bool CheckForOpenBuy(void)
  {
   bool res=false;
//--- check for long position (BUY) possibility
   double price=m_symbol.Ask();
   double tp   =m_symbol.Bid()+m_take_profit;
   double sl   =m_symbol.Bid()-m_stop_loss;
//--- check for free money
   if(m_account.FreeMarginCheck(Symbol(),ORDER_TYPE_BUY,InpLots,price)<0.0)
      printf("We have no money. Free Margin = %f",m_account.FreeMargin());
   else
     {
      //--- open position
      if(m_trade.PositionOpen(Symbol(),ORDER_TYPE_BUY,InpLots,price,sl,tp))
         printf("Position by %s to be opened",Symbol());
      else
        {
         printf("Error opening BUY position by %s : '%s'",Symbol(),m_trade.ResultComment());
         printf("Open parameters : price=%f,SL=%f,TP=%f",price,sl,tp);
        }
     }
//--- in any case we must exit from expert
   res=true;
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check for open position conditions                               |
//+------------------------------------------------------------------+
bool CheckForOpenSell(void)
  {
   bool res=false;
//--- check for short position (SELL) possibility
   double price=m_symbol.Bid();
   double tp   =m_symbol.Ask()-m_take_profit;
   double sl   =m_symbol.Ask()+m_stop_loss;
//--- check for free money
   if(m_account.FreeMarginCheck(Symbol(),ORDER_TYPE_SELL,InpLots,price)<0.0)
      printf("We have no money. Free Margin = %f",m_account.FreeMargin());
   else
     {
      //--- open position
      if(m_trade.PositionOpen(Symbol(),ORDER_TYPE_SELL,InpLots,price,sl,tp))
         printf("Position by %s to be opened",Symbol());
      else
        {
         printf("Error opening SELL position by %s : '%s'",Symbol(),m_trade.ResultComment());
         printf("Open parameters : price=%f,SL=%f,TP=%f",price,sl,tp);
        }
     }
//--- in any case we must exit from expert
   res=true;
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check for close position conditions                              |
//+------------------------------------------------------------------+
void CheckForCloseBuy(void)
  {
//--- close position
   ClosePositions(POSITION_TYPE_BUY);
//---
  }
//+------------------------------------------------------------------+
//| Check for close position conditions                              |
//+------------------------------------------------------------------+
void CheckForCloseSell(void)
  {
//--- close position
   ClosePositions(POSITION_TYPE_SELL);
//---
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
     {
      return(false);
     }
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
     {
      return(false);
     }
//---
   return(true);
  }
//+------------------------------------------------------------------+
//| Check Freeze and Stops levels                                    |
//+------------------------------------------------------------------+
void FreezeStopsLevels(double &freeze,double &stops)
  {
//--- check Freeze and Stops levels
   double coeff=(double)1;
   if(!RefreshRates() || !m_symbol.Refresh())
      return;
//--- FreezeLevel -> for pending order and modification
   double freeze_level=m_symbol.FreezeLevel()*m_symbol.Point();
   if(freeze_level==0.0)
      if(1>0)
         freeze_level=(m_symbol.Ask()-m_symbol.Bid())*coeff;
//--- StopsLevel -> for TakeProfit and StopLoss
   double stop_level=m_symbol.StopsLevel()*m_symbol.Point();
   if(stop_level==0.0)
      if(1>0)
         stop_level=(m_symbol.Ask()-m_symbol.Bid())*coeff;
//---
   freeze=freeze_level;
   stops=stop_level;
//---
   return;
  }
//+------------------------------------------------------------------+
//| Close positions                                                  |
//+------------------------------------------------------------------+
void ClosePositions(const ENUM_POSITION_TYPE pos_type)
  {
   double freeze=0.0,stops=0.0;
   FreezeStopsLevels(freeze,stops);
   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()==UNO_MAGIC)
            if(m_position.PositionType()==pos_type)
              {
               if(m_position.PositionType()==POSITION_TYPE_BUY)
                 {
                  bool take_profit_level=((m_position.TakeProfit()!=0.0 && m_position.TakeProfit()-m_position.PriceCurrent()>=freeze) || m_position.TakeProfit()==0.0);
                  bool stop_loss_level=((m_position.StopLoss()!=0.0 && m_position.PriceCurrent()-m_position.StopLoss()>=freeze) || m_position.StopLoss()==0.0);
                  if(take_profit_level && stop_loss_level)
                     if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","BUY PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());
                 }
               if(m_position.PositionType()==POSITION_TYPE_SELL)
                 {
                  bool take_profit_level=((m_position.TakeProfit()!=0.0 && m_position.PriceCurrent()-m_position.TakeProfit()>=freeze) || m_position.TakeProfit()==0.0);
                  bool stop_loss_level=((m_position.StopLoss()!=0.0 && m_position.StopLoss()-m_position.PriceCurrent()>=freeze) || m_position.StopLoss()==0.0);
                  if(take_profit_level && stop_loss_level)
                     if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","SELL PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());
                 }
               PlaySound("ok.wav");
              }
  }
//+------------------------------------------------------------------+
//| Filling the indicator buffers from the indicator                 |
//+------------------------------------------------------------------+
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))
     {
      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)
     {
      return(false);
     }
   return(result);
  }
//+------------------------------------------------------------------+
//| Search trading signals                                           |
//+------------------------------------------------------------------+
bool SearchTradingSignalsOpen(void)
  {
//--- we work only at the time of the birth of new bar
   datetime time_0=iTime(Symbol(),Period(),0);
   if(time_0==m_last_open)
      return(true);
   m_last_open=time_0;
//--- we work only at the time of the birth of new bar
   double StepMA_NRTR[],StepMA_NRTRS[];
   bool StNRUp,StNRDn;
   ArraySetAsSeries(StepMA_NRTR,true);
   ArraySetAsSeries(StepMA_NRTRS,true);
   int start_pos=0,count=3;
   if(!iGetArray(StepMA_NRTR_Handle,0,start_pos,count,StepMA_NRTR)||
      !iGetArray(StepMA_NRTR_Handle,1,start_pos,count,StepMA_NRTRS))
     {
      return(false);
     }
//+------------------------------------------------------------------+
   StNRUp=StepMA_NRTR[0]<StepMA_NRTRS[0];
//---
   StNRDn=StepMA_NRTR[0]>StepMA_NRTRS[0];
//+------------------------------------------------------------------+
//--- BUY Signal
   if(StNRUp)
     {
      if(InpClOp)
         CheckForCloseSell();
      Sleep(1000);
      if(price_uno<0)
         CheckForOpenBuy();
      price_uno=+1;
      return(true);
     }
//--- SELL Signal
   if(StNRDn)
     {
      if(InpClOp)
         CheckForCloseBuy();
      Sleep(1000);
      if(price_uno>0)
         CheckForOpenSell();
      price_uno=-1;
      return(true);
     }
//---
   return(true);
  }
//+------------------------------------------------------------------+


 
Sprut 185:

I'm beginning to suspect that this requires an extra function

That's right. You connect the indicator in OnInit, set parameters there and get its handle. And then use the CopyBuffer.


https://www.mql5.com/ru/docs/series/copybuffer

Документация по MQL5: Доступ к таймсериям и индикаторам / CopyBuffer
Документация по MQL5: Доступ к таймсериям и индикаторам / CopyBuffer
  • www.mql5.com
CopyBuffer - Доступ к таймсериям и индикаторам - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
SanAlex:

I made this - it seems to be working! (where yellow is the buffers)

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

Turns out I need a stop loss - (couldn't figure out why it closed immediately) added a stop loss



Thanks a lot !!!

You did a good job, but I'm interested in a completely different algorithm for the EA. I would like to use a simple Martingale (sieve) with these customizable parameters :

input group "======== МАРТИН ========"; 
input int      MMType        = 1;        // 1 - вкл. , 2 - выкл.
input double   Multiplikator = 1.667;    // множитель следующего лота
input double   Step          = 150.0;    // Расстояние между ордерами
input group "==== МАНИ МЕНЕДЖМЕНТ ====; 
input bool     LotConst      = true;     // фиксированный - true, или от  баланса - false
input group "-: фиксированный лот :--"; 
input double   Lot           = 0.01;     // первый фиксированный лот, если МАРТИН включен
input group "---: лот от баланса :---"; 
input double   RiskPercent   = 30.0;     // первый лот в процентах от баланса, если МАРТИН включен
input group "== ПРИБЫЛЬ В ПУНКТАХ ==="; 
input double   TakeProfit    = 56.0;     // параметры тейкпрофита в пунктах
input group "========= Шаг =========="; 
input double   Step          = 150.0;    // шаг в пунктах между ордерами
input group "===== ОГРАНИЧИТЕЛЬ =====";  
input int      MaxTrades     = 15;       // Максимальное количество ордеров одного направления
input group "=== ПРОСКАЛЬЗОВАНИЕ ====";  
input double   Slippage      = 5.0;      // Допустимое проскальзывание на новостях в пунктах
input group "== МАГИЧЕСКИЙ  НОМЕР ===";  
input int      Magic         = 1111111 ; // Идентификатор ордера (Магик №)

, but add to it the indicator I put in - above. And use it as a trigger (false - work only in SHORT and true - work only in LONG).

I chose this indicator - only because it works like MovingAverages, but it has some smoothing filters and price direction change points, which can be used as a trigger for the EA to work only on trend using profit settings from the menu.

And as soon as the take profit is closed, we open the next order in the same direction (in the trend), until the trend is over and our trigger is switched over. If an order does appear out of trend (at the moment when the trend changes from one state to another), we should use Martins with settings from the menu for it.

If you want to help write such an EA, I would be very grateful.

Now on the subject:
I understand that in my code of the indicator itself - are not indicator buffers, but arrays of buffers and you - in the Expert Advisor brought them into the indicator.
Please, let me know if I got it right?


 
Sprut 185:

Now for the subject:

I understood that in my codes of the indicator itself - not indicator buffers are located, but arrays of buffers and you - in the Expert Advisor brought them to indicator.
Please advise if I understand correctly?


I am self-taught and i am not able to explain it, i have just selected the functions i need.

I basically copy the codes from Vladimir Karputov, thank him very much! - If you have any questions he will tell you.

Vladimir Karputov
Vladimir Karputov
  • 2021.06.25
  • www.mql5.com
Профиль трейдера
 
SanAlex:

I understand you need an indicator to filter !

You need to run your Expert Advisor through this filter

You didn't quite get me right !!!