Preguntas de los principiantes MQL5 MT5 MetaTrader 5 - página 1318

 
Kira27:

Por favor, dígame de qué clase heredar su clase para utilizar todos los métodos de estos

para utilizar todos los métodos de estas clases dentro de su clase, sin la creación de objetos dentro de su clase?

Heredar significa crear una clase.

 

Hola a todos!
Tengo un indicador - escrito en mql5 que me gustaría utilizar para crear un EA.
Cuando creo un EA, no encuentro los topes que necesito, parece que no los tengo.
Así es como lo hago yo:

  {
//--- 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 importa cómo cambie o añada una línea iCustom - sigo obteniendo lo mismo en el registro:

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

Y el comentario: 1,00000 y 1,00000 de nuevo.

Ayúdame a entender: ¿es adecuado para crear un EA, o tengo que refinarlo, o tal vez estoy haciendo algo mal?


Archivos adjuntos:
StepMA_NRTR.mq5  13 kb
 

En MT5 se utiliza de manera diferente. Mira el ejemplo en la ayuda.

iCustom

Devuelve el asa del indicador personalizado especificado.

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

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

En MT5 se utiliza de manera diferente. Consulta el ejemplo en la ayuda.

iCustom

Devuelve el asa del indicador personalizado especificado.

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

Ya he leído esta documentación, pero no sé muy bien dónde.... ¿o cómo poner el número de búfer y de enchufe?

Estoy empezando a programar y les pido que sean indulgentes conmigo.

Empiezo a sospechar que esto requiere una función adicional

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

Por favor, explique.... donde .... ¿y cómo....?

 
Sprut 185:

Hola a todos!
Tengo un indicador - escrito en mql5 que me gustaría utilizar para crear un EA.
Cuando creo un EA, no encuentro los topes que necesito, parece que no los tengo.
Así es como lo hago yo:

No importa cómo cambie o añada una línea iCustom - sigo obteniendo lo mismo en el registro:

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

Y el comentario: 1,00000 y 1,00000 de nuevo.

Ayúdame a entender: ¿es adecuado para crear un EA, o tengo que refinarlo, o tal vez estoy haciendo algo mal?


Código:

//+------------------------------------------------------------------+
//| 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);
  }

Resultado:


Archivos adjuntos:
 
Sprut 185:

Hola a todos!
Tengo un indicador - escrito en mql5 - que me gustaría utilizar para crear un EA.

Aquí lo hice - ¡parece que funciona! (donde el amarillo es para los topes)

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

También necesito un stop loss(no pude averiguar por qué se cerró inmediatamente).

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:

Empiezo a sospechar que esto requiere una función extra

Así es. Conectas el indicador en OnInit, estableces los parámetros allí y obtienes su mango. Y luego usar el CopyBuffer.


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

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

He hecho esto - ¡parece que funciona! (donde el color amarillo es el de los topes)

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

Resulta que necesito un stop loss- (no podía entender por qué se cerró inmediatamente) añadió un stop loss



¡¡¡Muchas gracias!!!

Hiciste un buen trabajo, pero estoy interesado en un algoritmo completamente diferente para el EA. Me gustaría utilizar una simple martingala (tamiz) con estos parámetros personalizables :

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 ; // Идентификатор ордера (Магик №)

pero añádele el indicador que he puesto - arriba. Y utilícelo como disparador (falso - funciona sólo en CORTO y verdadero - funciona sólo en LARGO).

Elegí este indicador - sólo porque funciona como MovingAverages, pero tiene algunos filtros de suavizado y los puntos de cambio de dirección del precio, que puede ser utilizado como un disparador para el Asesor de Expertos para trabajar sólo en la tendencia utilizando la configuración de beneficios desde el menú.

Y tan pronto como se cierre el take profit, abrimos la siguiente orden en la misma dirección (en la tendencia), hasta que se acabe la tendencia y se cambie nuestro disparador. Si una orden aparece fuera de tendencia (en el momento en que la tendencia cambia de un estado a otro), debemos utilizar Martins con los ajustes del menú para ello.

Si quieres ayudar a escribir tal EA, te lo agradecería mucho.

Ahora en el tema:
Entiendo que en mi código del indicador en sí - no son búferes del indicador, pero las matrices de búferes y que - en el Asesor de Expertos los trajo en el indicador.
Por favor, dígame si lo he entendido bien.


 
Sprut 185:

Ahora el tema:

Entendí que en mis códigos del indicador mismo - no se encuentran los búferes del indicador, sino las matrices de los búferes y usted - en el Asesor Experto los trajo al indicador.
Por favor, indíqueme si lo he entendido bien.


Soy autodidacta y no soy capaz de explicarlo, sólo he seleccionado las funciones que necesito.

Básicamente copio los códigos de Vladimir Karputov, ¡muchas gracias! - Si tiene alguna pregunta, él se la dirá.

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

¡Entiendo que se necesita un indicador para filtrar !

Debe pasar su Asesor Experto por este filtro

¡¡¡No me has entendido bien !!!
Razón de la queja: