Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1321

 
Kira27:

The base class of all these methods does not allow you to use methods of its descendant classes)))).

The conclusion is obvious - create objects of the classes you need in your own.

 
SanAlex:

this is probably not possible to implement

it does not give - on the symbol, there must be one position (if it is closed on a profit and reopened a position) (and when the opposite signal is applied - it cannot open in the other direction

if just from a signal (from a point) there is no problem . (and this should not be present in the code (line above)))

Hi!

I searched all over the net and did not find any solution for mql5 but for mql4 I've found an EA on mql4, that works for both sides: buy and sell - simultaneously. I may try to take it as the basis......... but I have to rewrite it from mql4 to MQL5.

I am attaching his file for you to get acquainted with it.

 
Sprut 185:

Hi!

I searched all over the net and did not find any solution for mql5, but I found an Expert Advisor on mql4, which works in both directions simultaneously - buy and sell. I may try to take it as the basis......... but I have to rewrite it from mql4 to MQL5.

I am attaching his file for you to get acquainted with it.

This EA does not work with the Indicator and it can open in any direction. You have an indicator and you want it to open while trend is moving.

-The Expert Advisor that we have built, it can also open in both directions, but only in the direction that the Indicator shows the trend.

 
SanAlex:

This Expert Advisor does not work with an Indicator and it can open in either direction. But you have an indicator and you want it to open in trend.

-The Expert Advisor that we have created, it also can open in both directions, but only in the direction that the trend is shown by the Indicator.

Excuse me?

The one I have sent you opens 2 orders simultaneously (Sell and Buy) and if one is closed at profit, the other one remains and the closed one is opened again, in the direction in which it was closed. And the one that was left begins to work by Martin. When the trend changes, everything happens in the opposite direction.

If that EA we have built may open in both directions simultaneously, then why does it open only in one direction (as indicated by the indicator)?

I do not get it!!!

 
Sprut 185:

What do you mean?

The one I sent opens 2 orders simultaneously (Sell and Buy) and if one is closed at profit, the other one stays and the closed one opens again - in the direction in which it was closed. And the one that was left begins to work by Martin. When the trend changes, everything happens in the opposite direction.

If that EA we have built may open in both directions simultaneously, then why does it open only in one direction (as indicated by the indicator)?

I do not get it!

You see, he opens from the signal and opens until the profit goes off.

Picture 3 input bool InpVariant =false; // Option 1.variant


Photo by input bool InpVariant =true; // Option 2.variant


Picture 2 input bool InpClOp =false; // Close opposite

 
SanAlex:

here - from the signal opens and until the profit is triggered.

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


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


input bool InpClOp =false; // Close

So it didn't work? Too bad !!!!

I don't believe there is no solution - I will continue to surf the Internet.

 
Sprut 185:

It didn't work, did it? Too bad !!!!

I don't believe there's no solution, so I'll keep surfing the net.

You can actually add an object to open and close - then it might work, but it's a painful task.

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

instead of the usual TP, make it from the Horizontal line to close and open

 
Artyom Trishkin:

The conclusion is obvious - create objects of classes you need in your own class.

I did so by inheriting my class from CTrade, so that I could at least use trade functions without objects))) Thank you!

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

Well, I do not believe that there can be no solution - I will continue to surf the Internet.

Probably as you intended - it seems to have turned out.

5 Sprut 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!

I searched all over the net and did not find any solution for mql5, but I found an Expert Advisor on mql4, which works in both directions simultaneously - buy and sell. I may try to take it as the basis......... but I have to rewrite it from mql4 to MQL5.

I am attaching the file for you to become familiar with it.

I downloaded it yesterday to take a look... All of a sudden the Internet was taken away from me. After a thunderstorm I had some technical works for the rest of the day. I decided to rewrite it in MQL5 out of idleness and published it here.

So every cloud has a silver lining.........

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