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

 

Good afternoon,

Can you tell me how I can manage an EAon the vpc without re-synchronisation ?

I mean: on the terminal I can put buttons on the chart and change the mode without re-synchronisation. Can I use the bot to give commands to the EA on the PPC ?

Or should I use another alternative to change EA mode on mql vps without re-sync ?


Thanks for the reply !

 

Hello, dear experts!

Please help me to solve this problem.

When testing any pair, everything works properly, but when working with other currencies, the pending orders are not placed (I have to expose the pending order) and are not closed after take profit triggering.

Please advise how to change the code, if possible:

bool operation=0;for(int pos=0;pos<OrdersTotal();pos++)
     {if ( OrderSelect (pos, SELECT_BY_POS) == false )  continue;
      if ( OrderSymbol()==Symbol()) break;}


//=========================================================================================================
if(Hour()>=2&&Hour()<=18&&operation==0){
if(OPB1==1)
   {operation=1;if(operation==0 &&OrderSymbol()!=Symbol()||OrdersTotal()==0)
        {OrderSend(Symbol(),OP_BUY,lots,Ask,0,Bid-ss*Point,Ask+T*Point,"My order#",mn,0,Green);}}
        if (OrderType()==OP_BUY &&OrdersTotal()==1&&OrderMagicNumber()==8)
        {OrderSend(Symbol(),OP_SELLSTOP,5*lots,OrderOpenPrice()-(ss-ss/4)*Point,0,0,SstopClose,"My order#",80,0,Red);}
       

if(OPS1==1)
   {operation=1;if(operation==0 &&OrderSymbol()!=Symbol()||OrdersTotal()==0)        
         {OrderSend(Symbol(),OP_SELL,lots,Bid,0,Ask+ss*Point,Bid-T*Point,"My order#",mn,0,Red);}}
         if (OrderType()==OP_SELL &&OrdersTotal()==1&&OrderMagicNumber()==8)
         {OrderSend(Symbol(),OP_BUYSTOP,5*lots,OrderOpenPrice()+(ss-ss/4)*Point,0,0,BstopClose,"My order#",80,0,Green);}}



if(OrderMagicNumber()==80){operation=0;
 {for( int  ii=OrdersTotal()-1;ii>=0;ii--)
       {OrderSelect(ii, SELECT_BY_POS);
        int  type   = OrderType();bool result = false;
        switch(type)
         {case OP_BUYSTOP   : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );//break;
          case OP_SELLSTOP  : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red ); //break;
         
          result = OrderDelete( OrderTicket() );//break;
          }}}}
 

Good afternoon Dear forum users.

Please help me to improve the indicator that builds the zones on the chart.

In the current indicator the zones are set for all days of the week.

I need to be able to set zones for each day of the week separately.

//+------------------------------------------------------------------+
//|                                            2 ЗОНЫ.mq4            |
//|                                                                  |
//|                                                                  |
//|                                                                  |
//|  2017                                                            |
//+------------------------------------------------------------------+

#property indicator_chart_window

//------- Внешние параметры индикатора -------------------------------
extern int    NumberOfDays = 150;        // Количество дней
extern string Begin_1      = "03:00";
extern string End_1        = "08:00";
extern color  Color_1      = PowderBlue;
extern string Begin_2      = "09:00";
extern string End_2        = "16:30";
extern color  Color_2      = Yellow;
extern bool   HighRange    = true;


//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
void init() {
  DeleteObjects();
  for (int i=0; i<NumberOfDays; i++) {
    CreateObjects("PWT1"+i, Color_1);
    CreateObjects("PWT2"+i, Color_2);
  }
  Comment("");
}

//+------------------------------------------------------------------+
//| Custor indicator deinitialization function                       |
//+------------------------------------------------------------------+
void deinit() {
  DeleteObjects();
  Comment("");
}

//+------------------------------------------------------------------+
//| Создание объектов индикатора                                     |
//| Параметры:                                                       |
//|   no - наименование объекта                                      |
//|   cl - цвет объекта                                              |
//+------------------------------------------------------------------+
void CreateObjects(string no, color cl) {
  ObjectCreate(no, OBJ_RECTANGLE, 0, 0,0, 0,0);
  ObjectSet(no, OBJPROP_STYLE, STYLE_SOLID);
  ObjectSet(no, OBJPROP_COLOR, cl);
  ObjectSet(no, OBJPROP_BACK, True);
}

//+------------------------------------------------------------------+
//| Удаление объектов индикатора                                     |
//+------------------------------------------------------------------+
void DeleteObjects() {
  for (int i=0; i<NumberOfDays; i++) {
    ObjectDelete("PWT1"+i);
    ObjectDelete("PWT2"+i);
  }
}

//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
void start() {
  datetime dt=CurTime();

  for (int i=0; i<NumberOfDays; i++) {
    DrawObjects(dt, "PWT1"+i, Begin_1, End_1);
    DrawObjects(dt, "PWT2"+i, Begin_2, End_2);
    dt=decDateTradeDay(dt);
    while (TimeDayOfWeek(dt)>5) dt=decDateTradeDay(dt);
  }
}

//+------------------------------------------------------------------+
//| Прорисовка объектов на графике                                   |
//| Параметры:                                                       |
//|   dt - дата торгового дня                                        |
//|   no - наименование объекта                                      |
//|   tb - время начала сессии                                       |
//|   te - время окончания сессии                                    |
//+------------------------------------------------------------------+
void DrawObjects(datetime dt, string no, string tb, string te) {
  datetime t1, t2, t3;
  double   p1, p2, p3;
  int      b1, b2;

  t1=StrToTime(TimeToStr(dt, TIME_DATE)+" "+tb);
  t2=StrToTime(TimeToStr(dt, TIME_DATE)+" "+te);
  t3=StrToTime(TimeToStr(dt, TIME_DATE)+" ""23:00");
  b1=iBarShift(NULL, 0, t1);                            //Поиск бара по времени
  b2=iBarShift(NULL, 0, t2);
  p1=High[iHighest(NULL, PERIOD_M5, MODE_HIGH, b1-b2, b2)];  // 
  p2=Low [iLowest (NULL, PERIOD_M5, MODE_LOW , b1-b2, b2)]; // 
  p3=p2;
  if (!HighRange) {p1=0; p2=2*p2;}
  ObjectSet(no, OBJPROP_TIME1 , t1);
  ObjectSet(no, OBJPROP_PRICE1, p1);
  ObjectSet(no, OBJPROP_TIME2 , t2);
  ObjectSet(no, OBJPROP_PRICE2, p2);
  ObjectSet(no, OBJPROP_TIME2 , t3);
  ObjectSet(no, OBJPROP_PRICE2, p3);
}

//+------------------------------------------------------------------+
//| Уменьшение даты на один торговый день                            |
//| Параметры:                                                       |
//|   dt - дата торгового дня                                        |
//+------------------------------------------------------------------+
datetime decDateTradeDay (datetime dt) {
  int ty=TimeYear(dt);
  int tm=TimeMonth(dt);
  int td=TimeDay(dt);
  int th=TimeHour(dt);
  int ti=TimeMinute(dt);

  td--;
  if (td==0) {
    tm--;
    if (tm==0) {
      ty--;
      tm=12;
    }
    if (tm==1 || tm==3 || tm==5 || tm==7 || tm==8 || tm==10 || tm==12) td=31;
    if (tm==2) if (MathMod(ty, 4)==0) td=29; else td=28;
    if (tm==4 || tm==6 || tm==9 || tm==11) td=30;
  }
  return(StrToTime(ty+"."+tm+"."+td+" "+th+":"+ti));
}
//+------------------------------------------------------------------+

Files:
2_aqi4.ex4  17 kb
2_mne7.mq4  11 kb
 
Maxim Kuznetsov:

remove the conditions "if (OrdersTotal()==0)....". - they are just saying: search for entries and open new orders only when there are no orders at all.

If you want to avoid opening a big pack of new orders without such a condition, you should provide them with additional conditions. This depends on your strategy: not to open a new one within time T from the previous one, or to control bars or to keep distances in pips between orders.

Got it, thanks)

 
Is it possible in MT5 to present the results of trading on a real account as a chart, as you can see in the strategy tester?
Тестирование стратегий - Алгоритмический трейдинг, торговые роботы - Справка по MetaTrader 5
Тестирование стратегий - Алгоритмический трейдинг, торговые роботы - Справка по MetaTrader 5
  • www.metatrader5.com
Тестер стратегий позволяет тестировать и оптимизировать торговые стратегии (советники) перед началом использования их в реальной торговле. При тестировании советника происходит его однократная прогонка с начальными параметрами на исторических данных. При оптимизации торговая стратегия прогоняется несколько раз с различным набором параметров...
 

Guys, especially the developers, can you tell me if it's possible to solve this problem? The task in the picture


 

Good afternoon, the warning"possible loss of data due to type conversion" appears on variable n in the highlighted location

// Переводим строку в верхний регистр
string StringUpper(string s) {
  int c, i, k=StringLen(s), n;
  for (i=0; i<k; i++) {
    n=0;
    c=StringGetChar(s, i);
    if (c>96 && c<123) n=c-32;    // a-z -> A-Z
    if (c>223 && c<256) n=c-32;   // а-я -> А-Я
    if (c==184) n=168;            //  ё  ->  Ё
    if (n>0) s=StringSetChar(s, i, n);
  }
  return(s);
}

Can you please tell me how to correct it?

 
Sergey:

Good afternoon, the warning"possible loss of data due to type conversion" appears on variable n in the highlighted location

Can you please advise how to correct it?

Either ushort n=0;

Or StringSetChar(s, i, (ushort)n);

But it's better to use StringSetCharacter().

Документация по MQL5: Строковые функции / StringSetCharacter
Документация по MQL5: Строковые функции / StringSetCharacter
  • www.mql5.com
Если значение pos меньше длины строки и значение символьного кода = 0, то строка усекается (но размер буфера, распределенного под строку остается неизменным). Длина строки становится равной значению pos.
 
Does this site have the functionality to add articles to favourites?
How is it done for themes.
 

Afternoon.

In a multicurrency Expert Advisor, I need to close a pending order placed against a profit when an open position triggers.

Right now, when I close a pending order at profit, all the pending orders for all currencies are closed.

How do I change the code so that only the pending order related to a currency pair will close and the rest of the pending orders will remain open?

What should I change in this code?

if(OrderMagicNumber()==Mn){operation=0;
 {for( int  i=OrdersTotal()-1;i>=0;i--)
       {OrderSelect(i, SELECT_BY_POS);
        int  type   = OrderType();bool result = false;
        switch(type)
         {case OP_BUYSTOP   : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );//break;
          case OP_SELLSTOP  : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red ); //break; 
          
          result = OrderDelete( OrderTicket() );//break;
          }}}}

Mn in this code is a magic number of a pending order BUY_STOP or SELL_STOP.

The logic is that when an open position is closed at Take Profit, this magic number is left and the command to delete it is supposed to be executed.

This works when testing each pair. However, when working with other currencies, all orders placed on all pairs are deleted.

Please help, if you can.

I understand that no one has to bother with this problem, but maybe someone has a ready template?

I would be very grateful.