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

 
Kira27:

La clase base de todos estos métodos no permite utilizar métodos de sus clases descendientes)))).

La conclusión es obvia: crea objetos de las clases que necesites en las tuyas.

 
SanAlex:

esto probablemente no es posible de implementar

no da - en el símbolo, debe haber una posición (si se cierra en un beneficio y reabre una posición) (y cuando se aplica la señal contraria - no puede abrir en la otra dirección

si sólo de una señal (de un punto) no hay problema . (y esto no debería estar presente en el código (línea anterior))

¡Hola!

He buscado por toda la red y no he encontrado ninguna solución para mql5 pero para mql4 he encontrado un EA en mql4, que funciona para ambos lados: compra y venta - simultáneamente. Puedo intentar tomarlo como base......... pero tengo que reescribirlo de mql4 a MQL5.

Te adjunto su ficha para que la conozcas.

Archivos adjuntos:
 
Sprut 185:

¡Hola!

He buscado por toda la red y no he encontrado ninguna solución para mql5, pero he encontrado un Asesor Experto en mql4, que funciona en ambas direcciones simultáneamente - compra y venta. Puedo intentar tomarlo como base......... pero tengo que reescribirlo de mql4 a MQL5.

Te adjunto su ficha para que la conozcas.

Este EA no funciona con el Indicador y puede abrir en cualquier dirección. Tienes un indicador y quieres que se abra mientras la tendencia se mueve.

-Este Asesor Experto que hemos construido, también puede abrir en ambas direcciones, pero sólo en la dirección que el Indicador muestra la tendencia.

 
SanAlex:

Este Asesor Experto no funciona con un Indicador y puede abrirse en cualquier dirección. Pero tienes un indicador y quieres que se abra en tendencia.

-El Asesor Experto que hemos creado, también puede abrir en ambas direcciones, pero sólo en la dirección que muestra la tendencia el Indicador.

¿Perdón?

La que te he enviado abre 2 órdenes simultáneamente (Venta y Compra) y si una se cierra en beneficio, la otra se mantiene y la cerrada se abre de nuevo, en la dirección en la que se cerró. Y el que se quedó empieza a trabajar por Martin. Cuando la tendencia cambia, todo sucede en sentido contrario.

Si ese EA que hemos construido puede abrirse en ambas direcciones simultáneamente, entonces ¿por qué se abre sólo en una dirección (como indica el indicador)?

¡¡¡No lo entiendo!!!

 
Sprut 185:

¿Qué quieres decir?

La que envié abre 2 órdenes a la vez (de venta y de compra) y si una se cierra en beneficio, la otra se queda y la cerrada se abre de nuevo - en la dirección en la que se cerró. Y el que se quedó empieza a trabajar por Martin. Cuando la tendencia cambia, todo sucede en sentido contrario.

Si ese EA que hemos construido puede abrirse en ambas direcciones simultáneamente, entonces ¿por qué se abre sólo en una dirección (como indica el indicador)?

No lo entiendo.

Verás, abre desde la señal y abre hasta que el beneficio se dispara.

Imagen 3 input bool InpVariant =false; // Opción 1.variant


Foto de input bool InpVariant =true; // Opción 2.variant


Imagen 2 input bool InpClOp =false; // Cerrar frente

 
SanAlex:

aquí - desde que se abre la señal y hasta que se dispara el beneficio.

input bool InpVariant =false; // Opción 1.variant


input bool InpVariant =true; // Opción 2.variant


input bool InpClOp =false; // Cerrar

¿Así que no funcionó? ¡¡¡¡Lástima que !!!!

No creo que no haya solución: seguiré navegando por Internet.

 
Sprut 185:

No funcionó, ¿verdad? ¡¡¡¡Lástima que !!!!

No creo que no haya solución, así que seguiré navegando por la red.

En realidad, se puede añadir un objeto para abrir y cerrar - entonces podría funcionar, pero es una tarea dolorosa.

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

en lugar del habitual TP, hazlo desde la línea Horizontal para cerrar y abrir

 
Artyom Trishkin:

La conclusión es obvia: crea objetos de clases que necesites en tu propia clase.

Lo hice heredando mi clase de CTrade, para poder al menos utilizar las funciones de comercio sin objetos)) ¡Gracias!

#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
//--------------------------------------------------------------------

// Mas_Ord_New_[150][9];   // Массив ордеров последний известный
// Mas_Ord_Old_[150][9];   // Массив ордеров предыдущий (старый)
// Mas_Tip_[6];              // Массив коллич. ордеров всех типов

//+------------------------------------------------------------------+
#include <Trade\Trade.mqh> //Класс CTrade обеспечивает упрощенный доступ к торговым функциям.

#include <Trade\SymbolInfo.mqh>    //Класс CTrade 
CSymbolInfo SymbolInfo;            // Объект класса Для получения параметров по инструменту

#include <Trade\PositionInfo.mqh>;
CPositionInfo PositionInfo;        //объект PositionInfo класса СPositionInfo Для получения параметров открытых позиций

#include <Trade\OrderInfo.mqh>;
COrderInfo OrderInfo;          //Объект OrderInfo класса COrderInfo Для получения параметров отложеных ордеров

#include <Fibo_Level.mqh>
Fibo_Levell Level_Fibo2;
//+------------------------------------------------------------------+


class Terminal : public CTrade

  {
private:

public:
                     Terminal();
                    ~Terminal();

   void              Order_and_Pozition_Info
   (
      int &up_F_,          //Глобальный счётчик  типов TrendLineUp
      int &down_F_,        //Глобальный счётчик  типов TrendLineDown
      int &ID_Fibo_Up_,    //Счётчик-идентификатор фибо для сделок 
      int &ID_Fibo_Down_,
      int OrderFibo_78_,
      int STP_,
      int &Mas_Tip_[],              // Массив колич. ордеров всех типов
      double &FiboUp_New_[][],
      double &FiboDown_New_[][],
      string Sparam,
      double &Mas_Ord_New_[][],
      double &Mas_Ord_Old_[][],
      bool Alert_sig_Terminal_,
      bool &flag_interation_
   );
  };
 

Sprut 185 :    Короче не прокатило? А жаль !!!!

Bueno, no creo que no haya solución, seguiré navegando por Internet.

Probablemente como pretendías, parece haber resultado.

5 brote 185

 //+------------------------------------------------------------------+
//|                                                  5 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 MACD_MAGIC 1234502
//---
#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
//---
input double InpLots          = 0.1 ;     // Lots
input int     InpTakeProfit    = 50 ;     // Take Profit (in pips)
input bool    InpClOp          = false ;   // Close opposite
//---
string InpObjDownName = "Sprutbuy" ;     // : Obj: Follows the price up (Horizontal Line)
string InpObjUpName   = "Sprutsell" ;     // : Obj: Follows the price down (Horizontal Line)
//---
double    m_take_profit;
int       m_price_uno;
datetime m_ExtPrevBars          = D'1970.01.01 00:00' ;
datetime m_ExtLastSignals       = D'1970.01.01 00:00' ;
datetime m_ExtPrevBars_x        = D'1970.01.01 00:00' ;
datetime m_ExtLastSignals_x     = D'1970.01.01 00:00' ;
int       m_handle_macd; // MACD indicator handle
int       ExtTimeOut= 10 ; // time out in seconds between trade operations
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()
  {
//--- initialize common information
   m_symbol.Name( Symbol ());                   // symbol
   m_trade.SetExpertMagicNumber(MACD_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_take_profit     =InpTakeProfit*m_adjusted_point;
//--- set default deviation for trading in adjusted points
   m_trade.SetDeviationInPoints( 3 *digits_adjust);
//--- create MACD indicator
   m_handle_macd= iCustom ( NULL , 0 , "StepMA_NRTR" );
   if (m_handle_macd== INVALID_HANDLE )
     {
       printf ( "Error creating MACD indicator" );
       return ( false );
     }
//---
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ( void )
  {
   static datetime limit_time= 0 ; // last trade processing time + timeout
//---
   if (ProcessingUp() || ProcessingDown())
     {
       return ;
     }
//--- don't process if timeout
   if ( TimeCurrent ()>=limit_time)
     {
       //--- check for data
       if ( Bars ( Symbol (), Period ())> 2 )
        {
         //--- change limit time by timeout in seconds if processed
         if (Processing())
            limit_time= TimeCurrent ()+ExtTimeOut;
        }
     }
  }
//+------------------------------------------------------------------+
//| main function returns true if any position processed             |
//+------------------------------------------------------------------+
bool Processing( void )
  {
//--- refresh rates
   if (!m_symbol.RefreshRates())
       return ( false );
   double m_buff_MACD_main[],m_buff_MACD_signal[];
   bool StNRUp,StNRDn;
   ArraySetAsSeries (m_buff_MACD_main, true );
   ArraySetAsSeries (m_buff_MACD_signal, true );
   int start_pos= 1 ,count= 3 ;
   if (!iGetArray(m_handle_macd, 0 ,start_pos,count,m_buff_MACD_main)||
      !iGetArray(m_handle_macd, 1 ,start_pos,count,m_buff_MACD_signal))
     {
       return ( false );
     }
//---
   StNRUp=m_buff_MACD_main[ 0 ]<m_buff_MACD_signal[ 0 ];
   StNRDn=m_buff_MACD_main[ 0 ]>m_buff_MACD_signal[ 0 ];
//--- BUY Signal
   if (StNRUp)
     {
       if (InpClOp)
         if (ShortClosed())
             Sleep ( 1000 );
       if (m_price_uno< 0 )
         LongOpened();
      m_price_uno=+ 1 ;
       return ( true );
     }
//--- SELL Signal
   if (StNRDn)
     {
       if (InpClOp)
         if (LongClosed())
             Sleep ( 1000 );
       if (m_price_uno> 0 )
         ShortOpened();
      m_price_uno=- 1 ;
       return ( true );
     }
//--- exit without position processing
   return ( false );
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool LongClosed( void )
  {
   bool res= false ;
//--- should it be closed?
   ClosePositions( POSITION_TYPE_BUY );
//--- processed and cannot be modified
   res= true ;
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for short position closing                                 |
//+------------------------------------------------------------------+
bool ShortClosed( void )
  {
   bool res= false ;
//--- should it be closed?
   ClosePositions( POSITION_TYPE_SELL );
//--- processed and cannot be modified
   res= true ;
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for long position opening                                  |
//+------------------------------------------------------------------+
bool LongOpened( void )
  {
   bool res= false ;
//--- check for long position (BUY) possibility
   double price=m_symbol.Ask();
   double tp   =m_symbol.Bid()+m_take_profit;
//--- 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, 0.0 ,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,TP=%f" ,price,tp);
        }
       PlaySound ( "ok.wav" );
       if (!InpClOp)
         CreateHline( 0 , 0 ,InpObjDownName,tp, clrGreen , 0 , 0 , 1 , 1 , 1 , 1 , 2 );
     }
//--- in any case we must exit from expert
   res= true ;
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| Check for short position opening                                 |
//+------------------------------------------------------------------+
bool ShortOpened( void )
  {
   bool res= false ;
//--- check for short position (SELL) possibility
   double price=m_symbol.Bid();
   double tp   =m_symbol.Ask()-m_take_profit;
//--- 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, 0.0 ,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,TP=%f" ,price,tp);
        }
       PlaySound ( "ok.wav" );
       if (!InpClOp)
         CreateHline( 0 , 0 ,InpObjUpName,tp, clrGreen , 0 , 0 , 1 , 1 , 1 , 1 , 2 );
     }
//--- in any case we must exit from expert
   res= true ;
//--- result
   return (res);
  }
//+------------------------------------------------------------------+
//| 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()==MACD_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);
  }
//+------------------------------------------------------------------+
//| ProcessingClosSell                                               |
//+------------------------------------------------------------------+
bool ProcessingUp( void )
  {
   bool rv= false ;
   datetime time_current= TimeCurrent ();
   if (time_current-m_ExtLastSignals> 10 )
     {
       MqlRates rates[];
       int start_pos= 0 ,count= 1 ;
       if ( CopyRates (m_symbol.Name(), Period (),start_pos,count,rates)!=count)
        {
         m_ExtPrevBars= 0 ;
         return ( true );
        }
       double price_line= 0.0 ;
       if ( ObjectFind ( 0 ,InpObjUpName)>= 0 )
        {
         long object_type= ObjectGetInteger ( 0 ,InpObjUpName, OBJPROP_TYPE );
         if (object_type== OBJ_HLINE )
            price_line= ObjectGetDouble ( 0 ,InpObjUpName, OBJPROP_PRICE );
         if (price_line> 0.0 )
           {
             if ((rates[ 0 ].open>price_line && rates[ 0 ].close<price_line) ||
               (rates[ 0 ].open<price_line && rates[ 0 ].close>price_line))
              {
               //--- try to close or modify short position
               if (ShortOpened())
                   return ( true );
              }
           }
        }
     }
   return (rv);
  }
//+------------------------------------------------------------------+
//| ProcessingClosBuy                                                |
//+------------------------------------------------------------------+
bool ProcessingDown( void )
  {
   bool rv= false ;
   datetime time_current= TimeCurrent ();
   if (time_current-m_ExtLastSignals_x> 10 )
     {
       MqlRates rates[];
       //ArraySetAsSeries(rates,true);
       int start_pos= 0 ,count= 1 ;
       if ( CopyRates (m_symbol.Name(), Period (),start_pos,count,rates)!=count)
        {
         m_ExtPrevBars_x= 0 ;
         return ( true );
        }
       double price_line= 0.0 ;
       if ( ObjectFind ( 0 ,InpObjDownName)>= 0 )
        {
         long object_type= ObjectGetInteger ( 0 ,InpObjDownName, OBJPROP_TYPE );
         if (object_type== OBJ_HLINE )
            price_line= ObjectGetDouble ( 0 ,InpObjDownName, OBJPROP_PRICE );
         if (price_line> 0.0 )
           {
             if ((rates[ 0 ].open>price_line && rates[ 0 ].close<price_line) ||
               (rates[ 0 ].open<price_line && rates[ 0 ].close>price_line))
              {
               //--- try to close or modify long position
               if (LongOpened())
                   return ( true );
              }
           }
        }
     }
   return (rv);
  }
//+------------------------------------------------------------------+
//|  Creating a horizontal price level                               |
//+------------------------------------------------------------------+
bool CreateHline( long ch_id, int sub_window,
                 string name, double price,
                 color clr, ENUM_LINE_STYLE style,
                 int width, bool back,
                 bool selectable, bool selected,
                 bool hidden, long z_order)
  {
   int     err = GetLastError ();
   string lnName = name;
   err = 0 ;
   if ( ObjectFind ( 0 ,lnName)!=- 1 )
       ObjectDelete ( 0 ,lnName);
   if (! ObjectCreate (ch_id,lnName, OBJ_HLINE ,sub_window, 0 ,price))
     {
      err = GetLastError ();
       Print ( "Can't create object #" , lnName, "# Error(" ,err, "):" , err);
       return ( false );
     }
   ObjectSetInteger (ch_id,lnName, OBJPROP_COLOR ,clr);
   ObjectSetInteger (ch_id,lnName, OBJPROP_STYLE ,style);
   ObjectSetInteger (ch_id,lnName, OBJPROP_WIDTH ,width);
   ObjectSetInteger (ch_id,lnName, OBJPROP_BACK ,back);
   ObjectSetInteger (ch_id,lnName, OBJPROP_SELECTABLE ,selectable);
   ObjectSetInteger (ch_id,lnName, OBJPROP_SELECTED ,selected);
   ObjectSetInteger (ch_id,lnName, OBJPROP_HIDDEN ,hidden);
   ObjectSetInteger (ch_id,lnName, OBJPROP_ZORDER ,z_order);
   return ( true );
  }
//+------------------------------------------------------------------+
 
Sprut 185:

¡Hola!

He buscado por toda la red y no he encontrado ninguna solución para mql5, pero he encontrado un Asesor Experto en mql4, que funciona en ambas direcciones simultáneamente - compra y venta. Puede que intente usar ......... como base pero hay que reescribirlo de mql4 a MQL5.

Te adjunto el archivo para que te familiarices con él.

Lo descargué ayer para echarle un vistazo... De repente me quitaron Internet. Después de una tormenta eléctrica, tuve algunos trabajos técnicos durante el resto del día. Decidí reescribirlo en MQL5 por ociosidad y lo publiqué aquí.

Así que todas las nubes tienen un forro de plata.........

Советники: DVA_Martin
Советники: DVA_Martin
  • 2021.06.30
  • www.mql5.com
Статьи и техническая библиотека по автоматическому трейдингу: Советники: DVA_Martin
Razón de la queja: