Perguntas de Iniciantes MQL5 MT5 MetaTrader 5 - página 1321

 
Kira27:

A classe base de todos estes métodos não lhe permite utilizar métodos das suas classes descendentes)))).

A conclusão é óbvia - criar objectos das aulas de que necessita na sua própria aula.

 
SanAlex:

isto provavelmente não é possível de implementar

não dá - no símbolo, deve haver uma posição (se for fechada com lucro e reaberta uma posição) (e quando é aplicado o sinal oposto - não pode abrir na outra direcção

se apenas a partir de um sinal (de um ponto) não houver problema . (e isto não deve estar presente no código (linha acima)))

Hi!

Procurei por toda a rede e não encontrei nenhuma solução para mql5, mas para mql4 encontrei uma EA em mql4, que funciona para ambos os lados: comprar e vender - simultaneamente. Posso tentar tomá-lo como base......... mas tenho de reescrevê-lo de mql4 para MQL5.

Estou a anexar o seu ficheiro para que se possa familiarizar com ele.

Arquivos anexados:
 
Sprut 185:

Hi!

Procurei por toda a rede e não encontrei nenhuma solução para mql5, mas encontrei um Expert Advisor em mql4, que funciona em ambas as direcções simultaneamente - compra e venda. Posso tentar tomá-lo como base......... mas tenho de reescrevê-lo de mql4 para MQL5.

Estou a anexar o seu ficheiro para que se possa familiarizar com ele.

Esta EA não funciona com o Indicador e pode abrir em qualquer direcção. Tem um indicador e quer que ele se abra enquanto a tendência se move.

-Este Expert Advisor que construímos, também pode abrir em ambas as direcções, mas apenas na direcção em que o Indicador mostra a tendência.

 
SanAlex:

Este Conselheiro Especialista não trabalha com um Indicador e pode abrir em qualquer direcção. Mas tem um indicador e quer que ele se abra em tendência.

-O Expert Advisor que criámos, também pode abrir em ambas as direcções, mas apenas na direcção em que a tendência é mostrada pelo Indicador.

Desculpe-me?

A que lhe enviei abre 2 encomendas simultaneamente (Venda e Compra) e se uma for fechada com lucro, a outra permanece e a fechada é novamente aberta, na direcção em que foi fechada. E a que foi deixada por Martin começa a funcionar. Quando a tendência muda, tudo acontece na direcção oposta.

Se essa EA que construímos pode abrir em ambas as direcções simultaneamente, então porque é que abre apenas numa direcção (como indicado pelo indicador)?

Não percebo!!!!

 
Sprut 185:

O que quer dizer?

A que enviei abre 2 encomendas de uma vez (Vender e Comprar) e se uma for fechada com lucro, a outra fica e a fechada abre novamente - na direcção em que foi fechada. E a que foi deixada por Martin começa a funcionar. Quando a tendência muda, tudo acontece na direcção oposta.

Se essa EA que construímos pode abrir em ambas as direcções simultaneamente, então porque é que abre apenas numa direcção (como indicado pelo indicador)?

Não percebo!

Como vê, ele abre a partir do sinal e abre até o lucro disparar.

Imagem 3 input bool InpVariant =false; // Opção 1.variante


Foto por input bool InpVariant =true; // Opção 2.variante


Imagem 2 input bool InpClOp =false; // Fechar em frente

 
SanAlex:

aqui - a partir do sinal aberto e até que o lucro seja desencadeado.

input bool InpVariant =false; // Opção 1.variante


input bool InpVariant =true; // Opção 2.variante


input bool InpClOp =false; // Fechar

Então não funcionou? Pena !!!!

Não acredito que não haja solução - vou continuar a navegar na Internet.

 
Sprut 185:

Não funcionou, pois não? Pena !!!!

Não acredito que não haja solução, por isso vou continuar a navegar na rede.

Pode realmente adicionar um objecto para abrir e fechar - então pode funcionar, mas é uma tarefa dolorosa.

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

em vez do TP habitual, fazer a partir da linha Horizontal para fechar e abrir

 
Artyom Trishkin:

A conclusão é óbvia - criar objectos de aulas de que necessita na sua própria aula.

Fi-lo herdando a minha turma do CTrade, para que pudesse pelo menos utilizar funções comerciais sem objectos)))) Obrigado!

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

Bem, não acredito que não possa haver solução - continuarei navegando na Internet.

Provavelmente como você planejou - parece que acabou.

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

Hi!

Procurei por toda a rede e não encontrei nenhuma solução para mql5, mas encontrei um Expert Advisor em mql4, que funciona em ambas as direcções simultaneamente - compra e venda. Posso tentar usar......... como base, mas tem de ser reescrita de mql4 para MQL5.

Estou a anexar o ficheiro para que se familiarize com ele.

Descarreguei-o ontem para dar uma vista de olhos... De repente, a Internet foi-me tirada. Depois de uma trovoada, tive alguns trabalhos técnicos durante o resto do dia. Decidi reescrevê-lo na MQL5 por inactividade e publiquei-o aqui.

Assim, cada nuvem tem um lado positivo.........

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