Domande dai principianti MQL5 MT5 MetaTrader 5 - pagina 1321

 
Kira27:

La classe base di tutti questi metodi non permette di utilizzare i metodi delle sue classi discendenti )))).

La conclusione è ovvia: create gli oggetti delle classi che vi servono nel vostro.

 
SanAlex:

questo non è probabilmente possibile da implementare

non dà - sul simbolo, ci deve essere una posizione (se è chiuso su un profitto e riaperto una posizione) (e quando il segnale opposto è applicato - non può aprire nell'altra direzione

se solo da un segnale (da un punto) non c'è problema. (e questo non dovrebbe essere presente nel codice (linea sopra))

Ciao!

Ho cercato in tutta la rete e non ho trovato alcuna soluzione per mql5 ma per mql4 ho trovato un EA su mql4, che funziona per entrambi i lati: comprare e vendere - contemporaneamente. Posso provare a prenderlo come base......... ma devo riscriverlo da mql4 a MQL5.

Vi allego il suo file perché possiate conoscerlo.

 
Sprut 185:

Ciao!

Ho cercato in tutta la rete e non ho trovato nessuna soluzione per mql5, ma ho trovato un Expert Advisor su mql4, che lavora in entrambe le direzioni contemporaneamente - comprare e vendere. Posso provare a prenderlo come base......... ma devo riscriverlo da mql4 a MQL5.

Vi allego il suo file perché possiate conoscerlo.

Questo EA non funziona con l'indicatore e può aprirsi in qualsiasi direzione. Avete un indicatore e volete che si apra mentre il trend è in movimento.

-Questo Expert Advisor che abbiamo costruito, può anche aprire in entrambe le direzioni, ma solo nella direzione in cui l'indicatore mostra la tendenza.

 
SanAlex:

Questo Expert Advisor non funziona con l'indicatore e può aprirsi in entrambe le direzioni. Ma avete un indicatore e volete che si apra in tendenza.

-L'Expert Advisor che abbiamo creato, può anche aprire in entrambe le direzioni, ma solo nella direzione in cui il trend è mostrato dall'indicatore.

Come?

Quello che ti ho inviato apre 2 ordini simultaneamente (Vendere e Comprare) e se uno viene chiuso a profitto, l'altro rimane e quello chiuso viene aperto di nuovo, nella direzione in cui è stato chiuso. E quello che è stato lasciato comincia a lavorare da Martin. Quando la tendenza cambia, tutto accade nella direzione opposta.

Se l'EA che abbiamo costruito può aprirsi in entrambe le direzioni simultaneamente, allora perché si apre solo in una direzione (come indicato dall'indicatore)?

Non capisco!!!

 
Sprut 185:

Cosa vuoi dire?

Quello che ho inviato apre 2 ordini contemporaneamente (Sell e Buy) e se uno viene chiuso a profitto, l'altro rimane e quello chiuso si apre di nuovo - nella direzione in cui è stato chiuso. E quello che è stato lasciato comincia a lavorare da Martin. Quando la tendenza cambia, tutto accade nella direzione opposta.

Se l'EA che abbiamo costruito può aprirsi in entrambe le direzioni simultaneamente, allora perché si apre solo in una direzione (come indicato dall'indicatore)?

Non capisco!

Vedete, apre dal segnale e apre fino a quando il profitto si spegne.

Immagine 3 input bool InpVariant =false; // Opzione 1.variant


Foto di input bool InpVariant =true; // Opzione 2.variant


Immagine 2 input bool InpClOp =false; // Chiudi di fronte

 
SanAlex:

qui - dall'apertura del segnale e fino all'attivazione del profitto.

input bool InpVariant =false; // Opzione 1.variant


input bool InpVariant =true; // Opzione 2.variant


input bool InpClOp =false; // Chiudi

In breve, non ha funzionato, vero? Peccato !!!!

Non credo che non ci sia una soluzione - continuerò a navigare in Internet.

 
Sprut 185:

Non ha funzionato, vero? Peccato !!!!

Non credo che non ci sia una soluzione, quindi continuerò a navigare in rete.

Si può effettivamente aggiungere un oggetto da aprire e chiudere - allora potrebbe funzionare, ma è un compito doloroso.

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

invece del solito TP, farlo dalla linea orizzontale per chiudere e aprire

 
Artyom Trishkin:

La conclusione è ovvia: create gli oggetti delle classi che vi servono nella vostra classe.

L'ho fatto ereditando la mia classe da CTrade, in modo da poter almeno usare le funzioni commerciali senza oggetti))) Grazie!

#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 :    Короче не прокатило? А жаль !!!!

Bene, non credo che non ci possa essere una soluzione: continuerò a navigare in Internet.

Probabilmente come avevi pianificato - sembra che si sia rivelato.

5 Spruzzo 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:

Ciao!

Ho cercato in tutta la rete e non ho trovato nessuna soluzione per mql5, ma ho trovato un Expert Advisor su mql4, che lavora in entrambe le direzioni contemporaneamente - comprare e vendere. Posso provare a prenderlo come base......... ma devo riscriverlo da mql4 a MQL5.

Vi allego il file perché possiate familiarizzare con esso.

L'ho scaricato ieri per dare un'occhiata... All'improvviso Internet mi è stato portato via. Dopo un temporale ho avuto alcuni lavori tecnici per il resto della giornata. Ho deciso di riscriverlo in MQL5 per pigrizia e l'ho pubblicato qui.

Quindi ogni nuvola ha un rivestimento d'argento.........

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