Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 59

 
Please help me to complete this code.

I need to add a limit to the number of open orders.
Files:
mjj.txt  21 kb
 
Vadim Podoprigora:
Please help me to complete this code.

I need to add a limit to the number of open orders.

and how should the code work and after what should the restriction be placed?

----------------------------------------------------------------------

By the way, who can explain why at any data value

expression if ((AccountInfoDouble(ACCOUNT_EQUITY)*1.1>=AccountInfoDouble(ACCOUNT_BALANCE)) || (AccountInfoDouble(ACCOUNT_EQUITY)*0.9>=AccountInfoDouble(ACCOUNT_BALANCE))

gives out true

purpose is to trim large fluctuations

one last thing.

Looking for material on making buttons

I need to merge all these codes into a panel
 
trader781:

and how should the code work and after what should the restriction be placed?

----------------------------------------------------------------------

By the way, who can explain why at any data value

expression if ((AccountInfoDouble(ACCOUNT_EQUITY)*1.1>=AccountInfoDouble(ACCOUNT_BALANCE)) || (AccountInfoDouble(ACCOUNT_EQUITY)*0.9>=AccountInfoDouble(ACCOUNT_BALANCE))

gives out true

purpose is to trim large fluctuations

one last thing.

looking for material on creating buttons

need to merge all these codes into a panel
The article section is full of such materials. The simplest examples can be found in the help for each type of graphical objecthttps://www.mql5.com/ru/docs/constants/objectconstants/enum_object/obj_button.
Документация по MQL5: Стандартные константы, перечисления и структуры / Константы объектов / Типы объектов / OBJ_BUTTON
Документация по MQL5: Стандартные константы, перечисления и структуры / Константы объектов / Типы объектов / OBJ_BUTTON
  • www.mql5.com
Стандартные константы, перечисления и структуры / Константы объектов / Типы объектов / OBJ_BUTTON - справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
trader781:

how should the code work and after what should the restriction be placed?

----------------------------------------------------------------------

By the way, who can explain why at any data value

expression if ((AccountInfoDouble(ACCOUNT_EQUITY)*1.1>=AccountInfoDouble(ACCOUNT_BALANCE)) || (AccountInfoDouble(ACCOUNT_EQUITY)*0.9>=AccountInfoDouble(ACCOUNT_BALANCE))

gives out true

purpose is to trim large fluctuations

one last thing.

looking for material on making buttons

we have to put all these codes together in a panel
Limit the number of open orders at the same time.
 
Vadim Podoprigora:
Limit the number of open orders at the same time.
Hold
Files:
55677.mq4  42 kb
 
Hello, I was given a task to write an EA that trades as follows:
Determine the price minimum and maximum for the period of time specified by the user (for example, from 00-00 to 02-00). Buy: the price went below the minimum on the candle, sell: the price went above the maximum. With an open position new transactions do not open. We close the position at a specified time (also specified by the user, let's say at 22-00) or by SL\TP (specified by the user).


The question is how to actually define this minimum and maximum in the time period? And the EA cannot start trading before the end of the time period specified by the user (where the minimum and maximum are searched for). And how to track the number of orders (so they would not be more than one)?

Who knows where to dig and where to look for it, thanks in advance. If someone can help with the code that would be great.
 
Anarchist:
Hello, I was given a task to write an EA that trades as follows:
Determine the price minimum and maximum for the period of time specified by the user (for example, from 00-00 to 02-00). Buy: the price went below the minimum on the candle, sell: the price went above the maximum. With an open position new transactions do not open. We close the position at a specified time (also specified by the user, let's say at 22-00) or by SL\TP (specified by the user).


The question is how to actually define this minimum and maximum in the time period? And the EA cannot start trading before the end of the time period specified by the user (where the minimum and maximum are searched for). And how to track the number of orders (so they would not be more than one)?

Who knows where to dig and where to look for it, thanks in advance. If someone can help with the code that would be great.
Is this a term paper?
 
Alexey Viktorov:
Is this a term paper?
This is a simple laboratory work, here all these (user specified) are specified as variables in the code at the beginning of the programme + consider that the user is not stupid.
 
Anarchist :
Hello everyone, I was given the task to write an Expert Advisor that trades as follows:
We determine the minimum and maximum prices for the period of time specified by the user (for example, from 00-00 to 02-00). Buy: on the candle, the price has gone above the low, Sell: the price has gone above the high. With an open position, we do not open new deals. We close the position at the specified time (also specified by the user, let's say at 22-00) or by SL \ TP (specified by the user).


The question is, how to actually determine this minimum and maximum for a period of time? Moreover, the adviser cannot start trading before the end of the time specified by the user (where the minimum and maximum are searched). And how to track the number of orders (so that there is not more than one)?

Who will tell you where to dig and where to look, thanks in advance. If someone can help with the code, that would be great.

Keep sketched out quickly, without any special checks, it will do for the tester.

//+------------------------------------------------------------------+
//|                                                       test07.mq4 |
//|                                                   Sergey Gritsay |
//|                         https://www.mql5.com/ru/users/sergey1294 |
//+------------------------------------------------------------------+
#property copyright "Sergey Gritsay"
#property link        "https://www.mql5.com/ru/users/sergey1294"
#property version    "1.00"
#property strict

input string analysis_time_start= "10:00" ;
input string analysis_time_end= "12:00" ;
input string time_out= "16:00" ;
input string time_out_close= "23:00" ;

input int     shift_open= 0 ;
input int     MagicNumber= 20110315 ;       // Номер копии
input double Lot= 0.01 ;           // Объем лота
input int     StopLoss     = 300 ;             // Стоп Лосс (Пипс)
input int     TakeProfit   = 500 ;             // Тейк Профит (Пипс)
input int     Slippage     = 10 ;             // Проскальзование (Пипс)
input string CommentOrder= "test" ;     // Комментарий к ордеру

double    up_price= 0.0 ;
double down_price= 0.0 ;
double hist_high[];
double hist_low[];
double hist_close[];
MqlDateTime times;
MqlRates rates[];
datetime d1;
datetime d2;
datetime d3;
datetime d4;
bool flag_open= false ;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()
  {
//---
   VLineCreate( 0 , "Line_start" );
   VLineCreate( 0 , "Line_end" );
   VLineCreate( 0 , "Line_time_out" );
   VLineCreate( 0 , "Line_time_out_close" );
   HLineCreate( 0 , "Line_max" );
   HLineCreate( 0 , "Line_min" );
//---
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
//---
   VLineDelete( 0 , "Line_start" );
   VLineDelete( 0 , "Line_end" );
   VLineDelete( 0 , "Line_time_out" );
   VLineDelete( 0 , "Line_time_out_close" );
   HLineDelete( 0 , "Line_max" );
   HLineDelete( 0 , "Line_min" );
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ()
  {
//---
   datetime date= TimeCurrent (times);
   int ty=times.year;
   int tm=times.mon;
   int td=times.day;
   d1= StringToTime (( string )ty+ "." +( string )tm+ "." +( string )td+ " " +analysis_time_start);
   d2= StringToTime (( string )ty+ "." +( string )tm+ "." +( string )td+ " " +analysis_time_end);
   d3= StringToTime (( string )ty+ "." +( string )tm+ "." +( string )td+ " " +time_out);
   d4= StringToTime (( string )ty+ "." +( string )tm+ "." +( string )td+ " " +time_out_close);

   if (!flag_open && date>d1 && date<d2)flag_open= true ;
   if (date>=d3 && d2<d3)flag_open= false ;

   if (date>d2)
     {
       if ( CopyLow ( _Symbol , 0 ,d1,d2,hist_low)< 0 ) return ;
       if ( CopyHigh ( _Symbol , 0 ,d1,d2,hist_high)< 0 ) return ;
      up_price= NormalizeDouble (hist_high[ ArrayMaximum (hist_high)], _Digits );
      down_price= NormalizeDouble (hist_low[ ArrayMinimum (hist_low)], _Digits );
     }

   VLineMove( 0 , "Line_start" ,d1);
   VLineMove( 0 , "Line_end" ,d2);
   VLineMove( 0 , "Line_time_out" ,d3);
   VLineMove( 0 , "Line_time_out_close" ,d4);
   HLineMove( 0 , "Line_max" ,up_price);
   HLineMove( 0 , "Line_min" ,down_price);

   Comment (
           "\n date = " ,date,
           "\n d1 = " , TimeToString (d1),
           "\n d2 = " , TimeToString (d2),
           "\n d3 = " , TimeToString (d3),
           "\n d4 = " , TimeToString (d4)
           );

   if (flag_open)
     {
       if (TotalOrder()== 0 )
        {
         if ( CopyRates ( _Symbol , PERIOD_CURRENT , 0 ,shift_open+ 2 ,rates)==shift_open+ 2 )
           {
             if (date>d2 && date<d3 && d2<d3 && rates[shift_open].time>d2)
              {
               if (rates[shift_open].close>=up_price && rates[shift_open+ 1 ].close<=up_price)
                 {
                  OrderOpen( OP_BUY );
                 }

               if (rates[shift_open].close<=down_price && rates[shift_open+ 1 ].close>=down_price)
                 {
                  OrderOpen( OP_SELL );
                 }
              }
           }
        }
     }

   if (date>=d4 && d2<d4)
     {
       OrderClose ();
     }

   ModifySL(StopLoss);
   ModifyTP(TakeProfit);
  }
//+------------------------------------------------------------------+
int TotalOrder()
  {
   int value= 0 ;
   int total= OrdersTotal ();
   for ( int i=total- 1 ; i>= 0 ; i--)
     {
       if (! OrderSelect (i, SELECT_BY_POS )) continue ;
       if ( OrderSymbol ()!= Symbol ()) continue ;
       if ( OrderMagicNumber ()!=MagicNumber) continue ;
       if ( OrderType ()> 1 ) continue ;
      value++;
     }
   return (value);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OrderOpen( int type)
  {
   double price_open= 0.0 ;
   if (type== WRONG_VALUE ) return ;
   if (! IsTradeAllowed ()) return ;

   if (type== OP_BUY )price_open = NormalizeDouble ( Ask , _Digits );
   if (type== OP_SELL )price_open = NormalizeDouble ( Bid , _Digits );

   int ticket= OrderSend ( _Symbol ,type,Lot,price_open,Slippage, 0 , 0 ,CommentOrder,MagicNumber);
   if (ticket< 0 ) Print ( "Ошибка открытия ордера № - " , GetLastError ());
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OrderClose ()
  {
   double price_close= 0.0 ;
   if (! IsTradeAllowed ()) return ;
   int total= OrdersTotal ();
   for ( int i=total- 1 ; i>= 0 ; i--)
     {
       if (! OrderSelect (i, SELECT_BY_POS )) continue ;
       if ( OrderMagicNumber ()!=MagicNumber) continue ;
       if ( OrderSymbol ()!= _Symbol ) continue ;
       if ( OrderType ()!= OP_BUY  &&  OrderType ()!= OP_SELL ) continue ;
       if ( OrderType ()== OP_BUY )price_close= NormalizeDouble ( Bid , _Digits );
       if ( OrderType ()== OP_SELL )price_close= NormalizeDouble ( Ask , _Digits );
       bool res= OrderClose ( OrderTicket (), OrderLots (),price_close,Slippage);
       if (!res) Print ( "Ошибка закрытия ордера № - " , GetLastError ());
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void ModifySL( double sl)
  {
   if (sl<= 0 ) return ;
   double price_sl= 0.0 ;
   int total= OrdersTotal ();
   for ( int i=total- 1 ; i>= 0 ; i--)
     {
       if (! OrderSelect (i, SELECT_BY_POS )) continue ;
       if ( OrderMagicNumber ()!=MagicNumber) continue ;
       if ( OrderSymbol ()!= _Symbol ) continue ;
       if ( OrderType ()> 1 ) continue ;
       if ( OrderStopLoss ()== 0 )
        {
         if ( OrderType ()== OP_BUY )price_sl= NormalizeDouble ( OrderOpenPrice ()-sl* _Point , _Digits );
         if ( OrderType ()== OP_SELL )price_sl= NormalizeDouble ( OrderOpenPrice ()+sl* _Point , _Digits );
         if (price_sl<= 0 ) continue ;
         bool res= OrderModify ( OrderTicket (), OrderOpenPrice (),price_sl, OrderTakeProfit (), 0 );
         if (!res) Print ( "Ошибка модификации стоп лосса ордера № - " , GetLastError ());
        }
     }
  }
//+------------------------------------------------------------------+
void ModifyTP( double tp)
  {
   if (tp<= 0 ) return ;
   double price_tp= 0.0 ;
   int total= OrdersTotal ();
   for ( int i=total- 1 ; i>= 0 ; i--)
     {
       if (! OrderSelect (i, SELECT_BY_POS )) continue ;
       if ( OrderMagicNumber ()!=MagicNumber) continue ;
       if ( OrderSymbol ()!= _Symbol ) continue ;
       if ( OrderType ()> 1 ) continue ;
       if ( OrderTakeProfit ()== 0 )
        {
         if ( OrderType ()== OP_BUY )price_tp= NormalizeDouble ( OrderOpenPrice ()+tp* _Point , _Digits );
         if ( OrderType ()== OP_SELL )price_tp= NormalizeDouble ( OrderOpenPrice ()-tp* _Point , _Digits );
         if (price_tp<= 0 ) continue ;
         bool res= OrderModify ( OrderTicket (), OrderOpenPrice (), OrderStopLoss (),price_tp, 0 );
         if (!res) Print ( "Ошибка модификации тейк профита ордера № - " , GetLastError ());
        }
     }
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Создает вертикальную линию                                       |
//+------------------------------------------------------------------+
bool VLineCreate( const long             chart_ID= 0 ,         // ID графика
                 const string           name= "VLine" ,       // имя линии
                 const int              sub_window= 0 ,       // номер подокна
                 datetime               time= 0 ,             // время линии
                 const color            clr= clrRed ,         // цвет линии
                 const ENUM_LINE_STYLE style= STYLE_SOLID , // стиль линии
                 const int              width= 1 ,           // толщина линии
                 const bool             back= false ,         // на заднем плане
                 const bool             selection= true ,     // выделить для перемещений
                 const bool             ray= true ,           // продолжение линии вниз
                 const bool             hidden= true ,       // скрыт в списке объектов
                 const long             z_order= 0 )         // приоритет на нажатие мышью
  {
//--- если время линии не задано, то проводим ее через последний бар
   if (!time)
      time= TimeCurrent ();
//--- сбросим значение ошибки
   ResetLastError ();
//--- создадим вертикальную линию
   if (! ObjectCreate (chart_ID,name, OBJ_VLINE ,sub_window,time, 0 ))
     {
       Print ( __FUNCTION__ ,
             ": не удалось создать вертикальную линию! Код ошибки = " , GetLastError ());
       return ( false );
     }
//--- установим цвет линии
   ObjectSetInteger (chart_ID,name, OBJPROP_COLOR ,clr);
//--- установим стиль отображения линии
   ObjectSetInteger (chart_ID,name, OBJPROP_STYLE ,style);
//--- установим толщину линии
   ObjectSetInteger (chart_ID,name, OBJPROP_WIDTH ,width);
//--- отобразим на переднем (false) или заднем (true) плане
   ObjectSetInteger (chart_ID,name, OBJPROP_BACK ,back);
//--- включим (true) или отключим (false) режим перемещения линии мышью
//--- при создании графического объекта функцией ObjectCreate, по умолчанию объект
//--- нельзя выделить и перемещать. Внутри же этого метода параметр selection
//--- по умолчанию равен true, что позволяет выделять и перемещать этот объект
   ObjectSetInteger (chart_ID,name, OBJPROP_SELECTABLE ,selection);
   ObjectSetInteger (chart_ID,name, OBJPROP_SELECTED ,selection);
//--- включим (true) или отключим (false) режим отображения линии в подокнах графика
   ObjectSetInteger (chart_ID,name, OBJPROP_RAY ,ray);
//--- скроем (true) или отобразим (false) имя графического объекта в списке объектов
   ObjectSetInteger (chart_ID,name, OBJPROP_HIDDEN ,hidden);
//--- установим приоритет на получение события нажатия мыши на графике
   ObjectSetInteger (chart_ID,name, OBJPROP_ZORDER ,z_order);
//--- успешное выполнение
   return ( true );
  }
//+------------------------------------------------------------------+
//| Перемещение вертикальной линии                                   |
//+------------------------------------------------------------------+
bool VLineMove( const long    chart_ID= 0 ,   // ID графика
               const string name= "VLine" , // имя линии
               datetime      time= 0 )       // время линии
  {
//--- если время линии не задано, то перемещаем ее на последний бар
   if (!time)
      time= TimeCurrent ();
//--- сбросим значение ошибки
   ResetLastError ();
//--- переместим вертикальную линию
   if (! ObjectMove (chart_ID,name, 0 ,time, 0 ))
     {
       Print ( __FUNCTION__ ,
             ": не удалось переместить вертикальную линию! Код ошибки = " , GetLastError ());
       return ( false );
     }
//--- успешное выполнение
   return ( true );
  }
//+------------------------------------------------------------------+
//| Удаляет вертикальную линию                                       |
//+------------------------------------------------------------------+
bool VLineDelete( const long    chart_ID= 0 ,   // ID графика
                 const string name= "VLine" ) // имя линии
  {
//--- сбросим значение ошибки
   ResetLastError ();
//--- удалим вертикальную линию
   if (! ObjectDelete (chart_ID,name))
     {
       Print ( __FUNCTION__ ,
             ": не удалось удалить вертикальную линию! Код ошибки = " , GetLastError ());
       return ( false );
     }
//--- успешное выполнение
   return ( true );
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Создает горизонтальную линию                                     |
//+------------------------------------------------------------------+
bool HLineCreate( const long             chart_ID= 0 ,         // ID графика
                 const string           name= "HLine" ,       // имя линии
                 const int              sub_window= 0 ,       // номер подокна
                 double                 price= 0 ,           // цена линии
                 const color            clr= clrRed ,         // цвет линии
                 const ENUM_LINE_STYLE style= STYLE_SOLID , // стиль линии
                 const int              width= 1 ,           // толщина линии
                 const bool             back= false ,         // на заднем плане
                 const bool             selection= true ,     // выделить для перемещений
                 const bool             hidden= true ,       // скрыт в списке объектов
                 const long             z_order= 0 )         // приоритет на нажатие мышью
  {
//--- если цена не задана, то установим ее на уровне текущей цены Bid
   if (!price)
      price= SymbolInfoDouble ( Symbol (), SYMBOL_BID );
//--- сбросим значение ошибки
   ResetLastError ();
//--- создадим горизонтальную линию
   if (! ObjectCreate (chart_ID,name, OBJ_HLINE ,sub_window, 0 ,price))
     {
       Print ( __FUNCTION__ ,
             ": не удалось создать горизонтальную линию! Код ошибки = " , GetLastError ());
       return ( false );
     }
//--- установим цвет линии
   ObjectSetInteger (chart_ID,name, OBJPROP_COLOR ,clr);
//--- установим стиль отображения линии
   ObjectSetInteger (chart_ID,name, OBJPROP_STYLE ,style);
//--- установим толщину линии
   ObjectSetInteger (chart_ID,name, OBJPROP_WIDTH ,width);
//--- отобразим на переднем (false) или заднем (true) плане
   ObjectSetInteger (chart_ID,name, OBJPROP_BACK ,back);
//--- включим (true) или отключим (false) режим перемещения линии мышью
//--- при создании графического объекта функцией ObjectCreate, по умолчанию объект
//--- нельзя выделить и перемещать. Внутри же этого метода параметр selection
//--- по умолчанию равен true, что позволяет выделять и перемещать этот объект
   ObjectSetInteger (chart_ID,name, OBJPROP_SELECTABLE ,selection);
   ObjectSetInteger (chart_ID,name, OBJPROP_SELECTED ,selection);
//--- скроем (true) или отобразим (false) имя графического объекта в списке объектов
   ObjectSetInteger (chart_ID,name, OBJPROP_HIDDEN ,hidden);
//--- установим приоритет на получение события нажатия мыши на графике
   ObjectSetInteger (chart_ID,name, OBJPROP_ZORDER ,z_order);
//--- успешное выполнение
   return ( true );
  }
//+------------------------------------------------------------------+
//| Перемещение горизонтальной линии                                 |
//+------------------------------------------------------------------+
bool HLineMove( const long    chart_ID= 0 ,   // ID графика
               const string name= "HLine" , // имя линии
               double        price= 0 )       // цена линии
  {
//--- если цена линии не задана, то перемещаем ее на уровень текущей цены Bid
   if (!price)
      price= SymbolInfoDouble ( Symbol (), SYMBOL_BID );
//--- сбросим значение ошибки
   ResetLastError ();
//--- переместим горизонтальную линию
   if (! ObjectMove (chart_ID,name, 0 , 0 ,price))
     {
       Print ( __FUNCTION__ ,
             ": не удалось переместить горизонтальную линию! Код ошибки = " , GetLastError ());
       return ( false );
     }
//--- успешное выполнение
   return ( true );
  }
//+------------------------------------------------------------------+
//| Удаляет горизонтальную линию                                     |
//+------------------------------------------------------------------+
bool HLineDelete( const long    chart_ID= 0 ,   // ID графика
                 const string name= "HLine" ) // имя линии
  {
//--- сбросим значение ошибки
   ResetLastError ();
//--- удалим горизонтальную линию
   if (! ObjectDelete (chart_ID,name))
     {
       Print ( __FUNCTION__ ,
             ": не удалось удалить горизонтальную линию! Код ошибки = " , GetLastError ());
       return ( false );
     }
//--- успешное выполнение
   return ( true );
  }

//+------------------------------------------------------------------+

...

Files:
test07.mq4  34 kb
 
There was a bug in the order closing block, fixed it.
Reason: