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

 
trader781 :

ok i got it

I understand that at the moment this is all far from an acceptable form, but it can be shown why, in the case of a purchase, I cannot get a given dash -dotted line of the specified color, although it will calmly give out white or just green.

Well

double OP = 5.00000

TP = (OP/100);

Print("TP= ",TP);

2017.02.09 21:36:03.650 2015.01.05 04:00:00 martin H1-1 USDJPY,H1: TP= 0.5

I don’t understand since when dividing 5 by 100 will be 0.5

I posted the corrected code for you, as it should be

//+------------------------------------------------------------------+
//|                                                     Close_MA.mq4 |
//|                        Copyright 2016, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2016, MetaQuotes Software Corp."
#property link        "https://www.mql5.com"
#property version    "1.00"
#property strict

extern bool Uslovie1= false ; //Uslovie 4 6+50 MA

extern bool OpenOrders= false ; //+---Открыть ордер

extern double Lots= 0.01 ; //Oбьем открываемого ордера

extern const string Настройки_работы_советника= "" ;

extern int Period1= 6 ; //Период 1МА
extern ENUM_APPLIED_PRICE PRICE1= PRICE_MEDIAN ;             // 1МА По цене

extern int Period2= 50 ; //Период 2МА
extern ENUM_APPLIED_PRICE PRICE2= PRICE_MEDIAN ;             // 2МА По цене

extern int Period3= 1000 ; //Период 3МА
extern ENUM_APPLIED_PRICE PRICE3= PRICE_MEDIAN ;             // 3МА По цене

extern uint X= 1 ;                                           // отклонение от ма, пунктов
extern bool PlaySound = false ;
extern int M= 1000 ;                                         // миллисекунды в Sleep
extern int R;                                               // раз повторения музыки
extern int count= 0 ;
extern int Step= 500 ;                                       // счетчик тиков 500макс.
int    i;                                                   // исходный счетчик ордеров
int    p= 0 ;                                                 // внутренняя для playSound
bool   y = false ;                                           // для удобства сравнений условий 1,2,3,4,5,6  
bool   dummy;                                               // для выхода функций в переменную
int    ticket = 0 ;                                           // тикет открываемого ордера
int Magic= 222 ;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+



int OnInit ()
  {
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+



//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick ()
  {
     {
       if ( Bars < 801 || ( IsTradeAllowed ()== false )) //--- Проверим достаточна ли в истории баров для анализа и разрешение торговли
         return ;
     }
//+----------------------------------------------------------------

   double ma1= NormalizeDouble ( iMA ( NULL , 0 ,Period1, 0 , MODE_SMA ,PRICE1, 0 ), 5 );

   double ma2= NormalizeDouble ( iMA ( NULL , 0 ,Period2, 0 , MODE_SMA ,PRICE1, 0 ), 5 );   //три заданных параметра ма

   double ma3= NormalizeDouble ( iMA ( NULL , 0 ,Period3, 0 , MODE_SMA ,PRICE1, 0 ), 5 );
//+-----------------------------------------------------------------  Открытие ордеров

//+----Купить

     {
       if ( MathAbs ( Bid -ma3)< 1000 * Point () && (myOrdersTotal()== false ))
        {
         ticket= OrderSend ( Symbol (), OP_BUY ,Lots, Ask , 50 , 0 , 0 , "" ,Magic, 0 , clrLightGray ); //+------отправка 1 ордера
         HLineCreate( 0 , "buy" , 0 ,FindLastOrderOpenPrice(), clrAzure , STYLE_DASHDOT , 3 );
        }
       else if (( Ask >=(FindLastOrderOpenPrice()+(Step* _Point ))) && myOrdersTotal()) //+------------если ордер в плюс
        {
         ticket= OrderSend ( Symbol (), OP_BUY ,Lots, Ask , 50 , 0 , 0 , "" ,Magic, 0 , clrLightGray );
         HLineMove( 0 , "buy" ,FindLastOrderOpenPrice());
        }
       else if (( Ask <=(FindLastOrderOpenPrice()-(Step* _Point ))) && myOrdersTotal()) //+------------если ордер вплюс
        {
         ticket= OrderSend ( Symbol (), OP_BUY ,Lots, Ask , 50 , 0 , 0 , "" ,Magic, 0 , clrLightGray );
         HLineMove( 0 , "buy" ,FindLastOrderOpenPrice());
        }
       else if (ticket== 0 )
        {
         return ;
        }

/*          
                               //+----Продать

         if(MathAbs(Bid-ma3)>1000*Point() && (myOrdersTotal()==false))
           {
            ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,50,0,0,"",Magic,0,clrLightGray);//+------отправка 1 ордера
            HLineCreate1();  
           }
         else if ((Ask>=(FindLastOrderOpenPrice()+(Step*_Point)))&& myOrdersTotal())//+------------если ордер в минус
              {
            ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,50,0,0,"",Magic,0,clrLightGray);
            HLineMove1();
              }
         else if ((Ask<=(FindLastOrderOpenPrice()-(Step*_Point)))&& myOrdersTotal())//+------------если ордер вплюс
              {
            ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,50,0,0,"",Magic,0,clrLightGray);
            HLineMove1();
              }
         else if(ticket==0)
           {
            return;
           }       */

     }

//+------------------------------------------------------------------Условия
   if (Uslovie1== true ) //Bid+ma800
     {
       if (( Bid >=ma3-X* Point && Bid <ma3) || ( Bid <=ma3+X* Point && Bid >ma3))
        {
           {y= true ;}
        }
     }
//+------------------------------------------------------------------закрыть покупки или продажи

   if ((y== true ) && (myOrdersTotal()== true )) //продажа
     {
      dummy=( OrderClose ( OrderTicket (), OrderLots (), Ask , 0 ,White));
     }
   if ((y== true ) && (myOrdersTotal()== false ))
     {
      dummy= false ;
      HLineDelete( 0 , "buy" );
       //  ExpertRemove();  
     }

  }
//+------------------------------------------------------------------+
bool myOrdersTotal() //если ордера есть
  {
   for (i= OrdersTotal ()- 1 ; i>= 0 ; i--) //   цикл будет работать пока не останется ордеров
     {
       if ((( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))== true ) && OrderSymbol ()== Symbol () && ( OrderType ()< 2 ))
        {
         return true ;
        }
     }
   return false ;
  }
//-------------------------------------------------------------------
double FindLastOrderOpenPrice()
  {
   double oldorderopenprice= 0 ;
   int     oldticket= 0 ;
   ticket= 0 ;
   for (i= OrdersTotal ()- 1 ; i>= 0 ; i--) //   цикл будет работать пока не останется ордеров
     {
       if (( OrderSelect (i, SELECT_BY_POS , MODE_TRADES )) && OrderSymbol ()== Symbol () && ( OrderMagicNumber ()==Magic)
         && ( OrderType ()== OP_BUY || OrderType ()== OP_SELL ))
        {
         oldticket= OrderTicket ();
         if (oldticket>=ticket)
           {
            ticket=oldticket;
            oldorderopenprice= OrderOpenPrice ();
           }
        }
     }
   return (oldorderopenprice);
  }
//-------------------------------------------------------------------  

//+------------------------------------------------------------------+
//| Создает горизонтальную линию                                     |
//+------------------------------------------------------------------+
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 ( ObjectFind (chart_ID,name)!=sub_window)
     {
       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 ( ObjectFind (chart_ID,name)==- 1 ) return ( false );
   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 ( ObjectFind (chart_ID,name)==- 1 ) return ( false );
   if (! ObjectDelete (chart_ID,name))
     {
       Print ( __FUNCTION__ ,
             ": не удалось удалить горизонтальную линию! Код ошибки = " , GetLastError ());
       return ( false );
     }
//--- успешное выполнение
   return ( true );
  }
//+------------------------------------------------------------------+


...

 
trader781:

Okay, I get it.

I understand that this is all far from acceptable at the moment, but can you show me why I can't get a given dashedline of a specified colour in the case of a purchase, although white or plain green it will easily give out.

and

double OP = 5.00000

TP = (OP/100);

Print("TP= ",TP);

2017.02.09 21:36:03.650 2015.01.05 04:00:00 martin H1-1 USDJPY,H1: TP= 0.5

i dont understand since when do you divide 5 by 100 it is 0. 5

I don't know why you can't divide it right, it all works for me

void OnStart()
  {
//---
   double OP = 5.00000;

  double TP = OP/100;

  Print("TP= ",TP);
  }

Result

2017.02.10 06:22:48.633 Script test USDCHF,H1: loaded successfully
2017.02.10 06:22:48.663 test USDCHF,H1: initialized
2017.02.10 06:22:48.663 test USDCHF,H1: TP= 0.05
2017.02.10 06:22:48.663 test USDCHF,H1: uninit reason 0
2017.02.10 06:22:48.663 Script test USDCHF,H1: removed


...

 
Sergey Gritsay:

I don't know why you can't divide it properly, it's all divisible for me

I understand the principle, it will cut the current code by about half if it works. As for the previous one, it didn't start. It simply died together with the terminal, being overwritten with an empty sheet.
 

Hello.

Help me out with a question.

I am modifying a pending order by changing the opening price. Requesting a new open price after a successful change. The response gives the old, previous price. In what is the problem?

Code:

modify=OrderModify(OrderTicket(),new_Pr+50*Point,OrderStopLoss(),OrderTakeProfit(),0,Blue);

if(modify==true)

{

Print("BUYSTOP order modify OrderOpenPrice() : ",OrderOpenPrice());

}

And log entry :

modify #1 buy stop 1.00 GBPUSD at 1.60150 sl: 1.59590 tp: 1.63464 ok

BUYSTOP order modify OrderOpenPrice() : 1.6028

modify #1 buy stop 1.00 GBPUSD at 1.60070 sl: 1.59590 tp: 1.63464 ok

BUYSTOP order modify OrderOpenPrice() : 1.6015

 
Роман:

Hello.

Help me out with a question.

I am modifying a pending order by changing the opening price. Requesting a new open price after a successful change. The response gives the old, previous price. In what is the problem?

Code:

modify=OrderModify(OrderTicket(),new_Pr+50*Point,OrderStopLoss(),OrderTakeProfit(),0,Blue);

if(modify==true)

{

Print("BUYSTOP order modify OrderOpenPrice() : ",OrderOpenPrice());

}

And log entry :

modify #1 buy stop 1.00 GBPUSD at 1.60150 sl: 1.59590 tp: 1.63464 ok

BUYSTOP order modify OrderOpenPrice() : 1.6028

modify #1 buy stop 1.00 GBPUSD at 1.60070 sl: 1.59590 tp: 1.63464 ok

BUYSTOP order modify OrderOpenPrice() : 1.6015

OrderOpenPrice() stores the price that was there when OrderSelect() was applied. The value will not change by itself, no way. You have to call OrderSelect() again after modifying the order.
 
Vitalie Postolache:
OrderOpenPrice() stores the price that was there when OrderSelect() was applied. The value will not change by itself, no way. We should call OrderSelect() again after modifying the order.
Thank you. I will try to do it.
 

Please help!

The goal is to cut zeros (other numbers) from the array, while maintaining the sequence of numbers in the array

Made this code, but the array gets overwritten - something is wrong - please advise what is wrong.

//+------------------------------------------------------------------+
//|                                             Test_MassivObrez.mq4 |
//|                        Copyright 2017, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   int massivSize=19; //размер массива  
   double summDelta[19]=
     {
      0,
      20,
      30,
      0,
      0,
      51,
      0,
      53,
      54,
      60,
      70,
      80,
      120,
      150,
      0,
      210,
      223,
      232,
      250,
      0
     };


      int SizeMass=ArraySize(summDelta);//Узнаем размер массива
      int CalcZrero=0;
      for(int i=0;i<SizeMass;i++)
      {
       Print ("Число на проверку=",summDelta[i], " цикл ",i);
       if (summDelta[i]!=0)
       {
         Print ("Число до исключения нуля=",summDelta[i], " цикл ",i);
         for(int i=0;i<SizeMass;i++) printf("Состав массива до исключения нуля summDelta[%d] = %G",i,summDelta[i]);  
         ArrayCopy(summDelta,summDelta,i-CalcZrero,i);
         Print ("Число после исключения нуля=",summDelta[i-CalcZrero], " цикл ",i);
         for(int i=0;i<SizeMass;i++) printf("Состав массива после исключения нуля summDelta[%d] = %G",i,summDelta[i]);  
       }
       else CalcZrero++;      
      }

     for(int i=0;i<SizeMass;i++) printf("Массив после исключения нуля summDelta[%d] = %G",i,summDelta[i]);            
     ArrayResize(summDelta,SizeMass-CalcZrero,0);
     SizeMass=ArraySize(summDelta);//Узнаем новый размер массива
     for(int i=0;i<SizeMass;i++) printf("Массив после исключения нуля и обрезания summDelta[%d] = %G",i,summDelta[i]);            
  }
//+------------------------------------------------------------------+
 
-Aleks-:

Please help!

Objective is to cut zeros (other numbers) from the array, while maintaining the sequence of numbers in the array

Made this code, but the array is overwritten - something is wrong - please advise what is wrong.

//+------------------------------------------------------------------+
//|                                             Test_MassivObrez.mq4 |
//|                        Copyright 2017, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+

I would do the following:

   int n=-1;
   double ResummDelta[]; // создадим новый массив
   double summDelta[]=
     {
      0,
      20,
      30,
      0,
      0,
      51,
      0,
      53,
      54,
      60,
      70,
      80,
      120,
      150,
      0,
      210,
      223,
      232,
      250,
      0
     };
    
    for(int i=0;i<ArraySize(summDelta);i++) {    
     if(summDelta[i]!=0) {
      n++;
      ArrayResize(ResummDelta,n+1);
      ResummDelta[n]=summDelta[i];
     }  
    }
   // Print( ArraySize(summDelta)," = ",ArraySize(ResummDelta) );//Узнаем новый размер массива  
 
-Aleks-:

Please help!

The goal is to cut zeros (other numbers) from the array, while maintaining the sequence of numbers in the array

Made this code, but the array gets overwritten - something is wrong - please advise what is wrong.

At a glance, I would have done it in a different way.

double a[ 20 ] = { /*массив значений*/ };
double b[ 20 ];
//--- Проверяем массив а на наличие 0 значений
int j = 0;
for( int i = 0; i < 20; i++ )
   {
    if( a[ i ] != 0 )
      {
       b[ j ] = a[ i ];
       j++;
      }  
   }
//--- Изменяем размер массива а на значение j
//--- Копируем массив b в массив a

Yes, there's also a question of correctness of comparing real numbers with 0 by this method.

 

I'm thinking about a task like this, I haven't tested it in real life, should I do it or not. Or indicate other options.

Suppose I have a signal - in case of sharp spread widening (on news)

close all current trades

But the orders will not be given to just close or open during the news

Therefore, if we take a command, say, OrderClose, put it into a loop and execute it until it closes (similarly to OrderSend) and other commands that may terminate unsuccessfully

Reason: