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

 
trader781:
#property strict


//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2012, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
extern double Lots=0.01; //Oбьем открываемого ордера
extern double Martin=2;
extern int    Step=200;
extern int    TakeProfit=250;

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

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

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

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

int Period4=25;//Период 4МА
ENUM_APPLIED_PRICE PRICE4=PRICE_MEDIAN;             // 4МА По цене, вспомогательная

uint  X=20;                                                // отклонение от ма, пунктов
int   i;                                                   // исходный счетчик ордеров
bool  dummy;                                               // для выхода функций в переменную
int   ticket;                                            // тикет открываемого ордера
int   Magic=444;                                           // Magic Number
int   lastlot,tp;
double price;
int    count;
int    otype;



int OnInit()
  {
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
  }
void OnTick()
  {
     {
      if(Bars<801) //--- Проверим достаточна ли в истории баров для анализа и разрешение торговли
         return;
     }
//+----------------------------------------------------------------Сборник параметров индикаторов

   double ma1=NormalizeDouble(iMA(NULL,0,Period1,0,MODE_SMA,PRICE1,1),5);  //+----6

   double ma2=NormalizeDouble(iMA(NULL,0,Period2,0,MODE_SMA,PRICE2,1),5);  //+----50

   double ma3=NormalizeDouble(iMA(NULL,0,Period3,0,MODE_SMA,PRICE3,1),5);  //+----800

   double ma31=NormalizeDouble(iMA(NULL,0,Period3,0,MODE_SMA,PRICE3,10),5);   //+----800
   double ma32=NormalizeDouble(iMA(NULL,0,Period3,0,MODE_SMA,PRICE3,20),5);  //+----800
   double ma33=NormalizeDouble(iMA(NULL,0,Period3,0,MODE_SMA,PRICE3,30),5);  //+----800

   double ma4=NormalizeDouble(iMA(NULL,0,Period4,0,MODE_SMA,PRICE4,0),5);  //+----25
//+-----------------------------------------------------------------  Открытие ордеров по 25-50 ма

//+-------------------------------------------------- открыть ордер

   if(Counts()==0)               //+-------------если количество ордеров равно 0
     {
      if((MathAbs(ma2-ma4)>30*_Point)
         && (MathAbs(Bid-ma3)>100*Point())
         && (ma31>ma32>ma33)) //+-----покупка по 6+50
        {
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,0,0,0,"",Magic,0,clrAzure);//+-------------отправка 1 ордера
        }
      if((MathAbs(ma2-ma3)>30*_Point))//+-------------условие продажи
        {
         ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,0,0,0,"",Magic,0,clrAzure);//+-------------отправка 1 ордера
        }
        if (ticket==0)
            {
            return;
            }
     }
    
      else      //+------------если уже есть
    
        {
         if(FindLastOType()==OP_BUY)
           {
          
            if(Ask<=FindLastOrderOpenPrice()-Step*Point())
              {
               ticket=OrderSend(Symbol(),OP_BUY,(FindLastLot()*Martin),Ask,0,0,0,"",Magic,0,clrAzure);
               ModifyOrders();
               myOrdersCloseTotal();
              }
           }

         if(FindLastOType()==OP_SELL)
           {
          
            if(Bid>=FindLastOrderOpenPrice()+Step*Point())
              {
               ticket=OrderSend(Symbol(),OP_SELL,(FindLastLot()*Martin),Bid,0,0,0,"",Magic,0,clrAzure);
               ModifyOrders();
               myOrdersCloseTotal();
              }
           }
        }
     }
  
//+-------------------------------------------------------------количество ордеров в рынке

int Counts()
  {
   count=0;
   for(i=OrdersTotal()-1; i>=0; i--) //   цикл будет работать пока не останется ордеров
     {
      if((OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) && (OrderSymbol()==Symbol()) && (OrderMagicNumber()==Magic))
        {
         if((OrderType()==OP_BUY || OrderType()==OP_SELL) && (OrderTicket()==ticket))
            count++;
        }
     }
   return(count);
  }
//+---------------------------------------------------------------найти тип последнего ордера
int FindLastOType()
  {
   for(i=OrdersTotal()-1; i>=0; i--) //   цикл будет работать пока не останется ордеров
     {
      if((OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) && OrderSymbol()==Symbol() && (OrderMagicNumber()==Magic))
        {
         if((OrderType()==OP_BUY || OrderType()==OP_SELL) && (OrderTicket()==ticket))
            return(OrderType());
        }
     }
   return(-1);
  }
//+--------------------------------------------------------------вернуть цену последнего открытого ордера

double FindLastOrderOpenPrice()

  {
   int    oldticket;
   ticket=0;
   double oldorderopenprice=0;
   for(i=OrdersTotal()-1; i>=0; i--) //   цикл будет работать пока не останется ордеров
     {
      if((OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) && OrderSymbol()==Symbol() && (OrderMagicNumber()==Magic) && (OrderType()<2))
        {

         oldticket=OrderTicket();
         if(oldticket>ticket)
           {
            ticket=oldticket;
            oldorderopenprice=OrderOpenPrice();
           }
        }

     }
   return(oldorderopenprice);
  }
//+--------------------------------------------------------------вернуть объем последнего ордера
double FindLastLot()
  {
   int oldticket;
   ticket=0;
   double oldlots=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;
            oldlots=OrderLots();
           }

        }

     }
   return(oldlots);
  }
  //+---------------------------------------------------------закрыть все если хоть один из серии закрылся
  
  int myOrdersCloseTotal()


  {
  int myOrderS=0;
   for(i=OrdersTotal()-1; i>0; i--)
     {
      if(((OrderSelect(i,SELECT_BY_POS,MODE_TRADES))==true) && OrderSymbol()==Symbol() && (OrderType()<2))
        {
         myOrderS=OrdersTotal();
        }
        else
        dummy=(OrderClose(OrderTicket(),OrderLots(),Bid,0,White));
     }

   return (myOrderS);
  }

  
  
  
//+------------------------------------------------модификация существующих расчет тейка по средней цене
void ModifyOrders()
  {
   bool   z=true;
   double avg_price=0;
   price=0;
   double orderlots=0;
   for(i=OrdersTotal()-1; i>=0; i--)
     {
      if((OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) && (OrderSymbol()==Symbol())
      && (OrderMagicNumber()==Magic) && (FindLastOType()==OP_BUY))
        {
         price=(OrderOpenPrice()*OrderLots());
         orderlots=FindLastLot();
         avg_price=NormalizeDouble(price/orderlots,Digits);
         tp=(avg_price+TakeProfit*Point()); //+------------------------------------тут деление на 0 второго ордера
         z=OrderModify(OrderTicket(),OrderOpenPrice(),0,tp,0);
         if (!z)
         Print("Ошибка функции модифицирования");
        }
     }

   for(i=OrdersTotal()-1; i>=0; i--)
     {
      if((OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) && (OrderSymbol()==Symbol())
      && (OrderMagicNumber()==Magic) &&(FindLastOType()==OP_SELL))
       {
         price=(OrderOpenPrice()*OrderLots());
         orderlots=FindLastLot();
         avg_price=NormalizeDouble(price/orderlots,Digits);
         tp=(avg_price-TakeProfit*Point());   //+------------------------------------тут деление на 0 второго ордера
         z=OrderModify(OrderTicket(),OrderOpenPrice(),0,tp,0);
         if (!z)
         Print("Ошибка функции модифицирования");
       }
  
  
     }
    

  }







/*    
      
*/

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

There, well done.

And now the lines that the compiler is swearing at.

 
trader781:

I don't want to sound intrusive in this society, but no one has ever explained to me where 0 comes from in the calculations?

post 413

possible loss of data due to type conversion count.mq4 231 12

possible loss of data due to type conversion count.mq4 246 12

Are you unable to understand that TP and lots should not be written to an integer variable? Why is this so?
 
Vitalie Postolache:
Are you unable to understand that TAs and lots should not be written to an integer variable? Why is this the case?


Can we see how to write such things correctly?

 
Artyom Trishkin:
Once again, do you want to know what was on the indicator on H1 last hour, or do you want to know what is happening on the indicator on H1 at this moment in time?

You need the values of the indicator, on the first closed bar H1.

 
trader781:


Can we see how to record things like this properly?

Elementary.
int   lastlot,tp;
double   lastlot,tp;
 
trader781:


Can we see how to record things like this properly?

double tp;
Declare the variable tpto be of type double
 
Vitalie Postolache:
.
Alekseu Fedotov:

Thank you, the errors have disappeared. But the bot still dies on startup, along with the terminal, but for no apparent reason

TestGenerator: unmatched data error (volume limit 262 at 2016.12.02 12:45 exceeded)

TestGenerator: unmatched data error (high value 1.10131 at 2016.10.13 10:05 is not reached from the lowest timeframe, high price 1.10123 mismatches)

 
trader781:

Thank you, the errors are gone. But bot still dies on startup together with terminal, but without any apparent reason

TestGenerator: unmatched data error (volume limit 262 at 2016.12.02 12:45 exceeded)

TestGenerator: unmatched data error (high value 1.10131 at 2016.10.13 10:05 is not reached from the lowest timeframe, high price 1.10123 mismatches)

It's not the bot that is "dead", it's the story. Learn English, at least with a dictionary.
 
Vitalie Postolache:
It's not the bot "dying", it's the story. Learn English, at least with a dictionary.

And on all fumes all at once a shitty story? Coincidence?

 
trader781:

And on all fumes all at once a shitty story? Coincidence?

What's the big deal? It's always been like that.
Reason: