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

 

Hello !

Please check where I made a mistake (it does not want to work)

I want the buy signal to be shifted by thedeviation * _Point (set in settings)if(GetLotSize()>LotControl)

LotControl - also set in the settings

GetLotSize() - as recommended:

double GetLotSize()
  {
   double Ls=0;
   datetime last = 0, openTime;
   for (int pos=OrdersTotal()-1;pos>=0;pos--)
     {
      if (OrderSelect(pos, SELECT_BY_POS, MODE_TRADES))
        {
         if (OrderSymbol() == _Symbol && OrderMagicNumber() == Magic)
           {
             if(OrderType() == OP_BUY || OrderType() == OP_SELL) {
               if ((openTime = OrderOpenTime()) > last) {
                 last = openTime;
                 Ls = OrderLots();
               }
             }
           }
        }
     }
   return Ls;
  }
void OnTick()
  {
// Получим значение индикатора
   dMA = iMA(Symbol(), 0,PeriodMA, MovingShift, MODE_SMA, PRICE_CLOSE, 0); // MODE_SMA - простое усреднение , значение 0. PRICE_CLOSE- цена закрытия, значение 0.

// Если нет открытых ордеров, то входим в условие
      if(CountOrders()==0)
 {

  if(GetLotSize()>LotControl)  {openPrice = dMA + deviation * _Point;}
   
  else 
  openPrice = dMA;
   //Если появился сигнал на покупку, то откроем ордер на покупку
   if(bSignalBuy() == true)
   vOrderOpenBuy();
   
// Если появился сигнал на продажу, то откроем ордер на продажу
   if(bSignalSell() == true)
   vOrderOpenSell();
  
     }
// Проверяем, вышел ли текущий баланс по открытому ордеру за вилку из внешних переменных CountLoss и CountProfit

 // if(GetProfitFromStart()>CountProfit || GetProfitFromStart()<CountLoss*-1)
 //    {
// Если да, то закроем ордер по текущей цене, не дожидаясь стопа или тейка
 //     CloseOrder();
 //    }
DrawLABEL("lab_Take",1,5,0,Color(GetProfitFromStart()>0,Lime,Red),StringConcatenate("Profit: ",DoubleToStr(GetProfitFromStart(),2),AC));
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                             Функция проверки открытых оредров |
//+-----------------------------------------------------------------------------------------------+
int CountOrders() 
  {
   int cnt=0;
   int i=OrdersTotal()-1;
   for(int pos=i;pos>=0;pos--)
     {
      if(OrderSelect(pos, SELECT_BY_POS, MODE_TRADES))
        {
         if(OrderSymbol()==_Symbol)
           {
            if(OrderMagicNumber()==Magic) cnt++;
           }
        }
     }
   return(cnt);
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                             Функция поиска сигнала на покупку |
//+-----------------------------------------------------------------------------------------------+
bool bSignalBuy()
  {
   if (openPrice > Open[1] && openPrice < Close[1]) //Open[1] и Close[1]- цены открытия и закрытия каждого бара текущего графика.
   
  return(true);
   
  return(false);
  }
 
//+-----------------------------------------------------------------------------------------------+
//|                                                             Функция поиска сигнала на продажу |
//+-----------------------------------------------------------------------------------------------+
bool bSignalSell()
   
  {
   if(openPrice< Open[1] && openPrice > Close[1])

   return(true);

   return(false);
  }

 
законопослушный гражданин #:

Thank you. It didn't have any effect for some reason.

//+----------------------------------------------------------------------------+
if(bSignalBuy())
  {
   if(GetLotSize()>LotControl) vOrderOpenSell();
   else vOrderOpenBuy();
  }
//+----------------------------------------------------------------------------+
double GetLotSize()
  {
   double Ls=0;
   datetime t=0;
   int i=OrdersHistoryTotal();
   for(int pos=0; pos<i; pos++)
     {
      if(OrderSelect(pos, SELECT_BY_POS, MODE_HISTORY))
        {
         if(OrderSymbol()==_Symbol && OrderMagicNumber()==Magic)
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               if(t<OrderCloseTime()) {t=OrderCloseTime(); Ls=OrderLots();}
              }
           }
        }
     }
   return Ls;
  }
//+----------------------------------------------------------------------------+
 
законопослушный гражданин #:

Thank you. it didn't have any effect for some reason.

I wrote:

if (bSignalBuy()) {
  if (GetLotSize() > LotControl)
    vOrderOpenSell();
  else
    vOrderOpenBuy();
}

But still opens two differently directed positions on the same tick? That can't be right!

double GetLotSize()
  {
   double Ls=0;
   datetime last = 0, openTime;
   for (int pos=OrdersTotal()-1;pos>=0;pos--)
     {
      if (OrderSelect(pos, SELECT_BY_POS, MODE_TRADES))
        {
         if (OrderSymbol() == _Symbol && OrderMagicNumber() == Magic)
           {
             if(OrderType() == OP_BUY || OrderType() == OP_SELL) {
               if ((openTime = OrderOpenTime()) > last) {
                 last = openTime;
                 Ls = OrderLots();
               }
             }
           }
        }
     }
   return Ls;
  }

About this code, it may well be that nothing has changed. Since the orders are executed in the closing order.

Sort out your algorithm as well as possible.

void OnTick()
  {
// Получим значение индикатора
   dMA = iMA(Symbol(), 0,PeriodMA, MovingShift, MODE_SMA, PRICE_CLOSE, 0); // MODE_SMA - простое усреднение , значение 0. PRICE_CLOSE- цена закрытия, значение 0.

// Если нет открытых ордеров, то входим в условие
      if(CountOrders()==0)
 {

  if(GetLotSize()>LotControl)  {openPrice = dMA + deviation * _Point;}
   
  else 
  openPrice = dMA;
   //Если появился сигнал на покупку, то откроем ордер на покупку
   if(bSignalBuy() == true)
   vOrderOpenBuy();
   
// Если появился сигнал на продажу, то откроем ордер на продажу
   if(bSignalSell() == true)
   vOrderOpenSell();
  
     }
// Проверяем, вышел ли текущий баланс по открытому ордеру за вилку из внешних переменных CountLoss и CountProfit

 // if(GetProfitFromStart()>CountProfit || GetProfitFromStart()<CountLoss*-1)
 //    {
// Если да, то закроем ордер по текущей цене, не дожидаясь стопа или тейка
 //     CloseOrder();
 //    }
DrawLABEL("lab_Take",1,5,0,Color(GetProfitFromStart()>0,Lime,Red),StringConcatenate("Profit: ",DoubleToStr(GetProfitFromStart(),2),AC));
  }

You should check your algorithm. Here, you are entering by the Buy and Sell signals and nothing further. What may not work here? No entry or exit functions...

 

Forum on trading, automated trading systems & strategy testing

Any questions from newbies on MQL4 and MQL5, help and discussion on algorithms and codes

MakarFX, 2021.12.02 18:30

//+----------------------------------------------------------------------------+
if(bSignalBuy())
  {
   if(GetLotSize()>LotControl) vOrderOpenSell();
   else vOrderOpenBuy();
  }
//+----------------------------------------------------------------------------+
double GetLotSize()
  {
   double Ls=0;
   datetime t=0;
   int i=OrdersHistoryTotal();
   for(int pos=0; pos<i; pos++)
     {
      if(OrderSelect(pos, SELECT_BY_POS, MODE_HISTORY))
        {
         if(OrderSymbol()==_Symbol && OrderMagicNumber()==Magic)
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               if(t<OrderCloseTime()) {t=OrderCloseTime(); Ls=OrderLots();}
              }
           }
        }
     }
   return Ls;
  }
//+----------------------------------------------------------------------------+

What's in here? You have not changed anything in essence. You just made more calls to OrderCloseTime. The code was stretched into one line. And it became less readable. But the result is still the same.

 
Mihail Matkovskij #:

What about here? You haven't changed anything in essence. You just made more calls to OrderCloseTime. But the result is the same.

Open your eyes
 
MakarFX #:
open your eyes

Arguments in the studio, please

 
Mihail Matkovskij #:

Arguments in the studio, please.

Now open your eyes

 
Mihail Matkovskij #:

What about here? You haven't changed anything in essence. You just made more calls to OrderCloseTime. And we have stretched the code into one line. And it became less readable. But the result is the same.

As far as I can see, the difference is in the following:

double GetLotSize()
  {
   double Ls=0;
   datetime last = 0, openTime;
   for (int pos=OrdersTotal()-1;pos>=0;pos--)
     {
      if (OrderSelect(pos, SELECT_BY_POS, MODE_TRADES))
        {
         if (OrderSymbol() == _Symbol && OrderMagicNumber() == Magic)
           {
             if(OrderType() == OP_BUY || OrderType() == OP_SELL) {
               if ((openTime = OrderOpenTime()) > last) {
                 last = openTime;
                 Ls = OrderLots();
               }
             }
           }
        }
     }
   return Ls;
  }



double GetLotSize()
  {
   double Ls=0;
   datetime t=0;
   int i=OrdersHistoryTotal();
   for(int pos=0; pos<i; pos++)
     {
      if(OrderSelect(pos, SELECT_BY_POS, MODE_HISTORY))
        {
         if(OrderSymbol()==_Symbol && OrderMagicNumber()==Magic)
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               if(t<OrderCloseTime()) {t=OrderCloseTime(); Ls=OrderLots();}
              }
           }
        }
     }
   return Ls;
  }
мне как то объясняли, что один вариант считает с конца списка, а второй с начала.
 
MakarFX #:

Now open your eyes.

(sighs) Okay. I missed that moment. I admit it.

 
законопослушный гражданин #:

as far as I can see, the difference is as follows:

double GetLotSize()
  {
   double Ls=0;
   datetime last = 0, openTime;
   for (int pos=OrdersTotal()-1;pos>=0;pos--)
     {
      if (OrderSelect(pos, SELECT_BY_POS, MODE_TRADES))
        {
         if (OrderSymbol() == _Symbol && OrderMagicNumber() == Magic)
           {
             if(OrderType() == OP_BUY || OrderType() == OP_SELL) {
               if ((openTime = OrderOpenTime()) > last) {
                 last = openTime;
                 Ls = OrderLots();
               }
             }
           }
        }
     }
   return Ls;
  }




double GetLotSize()
  {
   double Ls=0;
   datetime t=0;
   int i=OrdersHistoryTotal();
   for(int pos=0; pos<i; pos++)
     {
      if(OrderSelect(pos, SELECT_BY_POS, MODE_HISTORY))
        {
         if(OrderSymbol()==_Symbol && OrderMagicNumber()==Magic)
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               if(t<OrderCloseTime()) {t=OrderCloseTime(); Ls=OrderLots();}
              }
           }
        }
     }
   return Ls;
  }
Reason: