Cualquier pregunta de los recién llegados sobre MQL4 y MQL5, ayuda y discusión sobre algoritmos y códigos - página 1779

 

¡Hola !

Por favor, compruebe dónde he cometido un error (no quiere funcionar)

Quiero que la señal de compra se desplace por ladesviación * _Point (establecida en la configuración)if(GetLotSize()>LotControl)

LotControl - también se establece en la configuración

GetLotSize() - como se recomienda:

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);
  }

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

Gracias. Por alguna razón no tuvo ningún efecto.

//+----------------------------------------------------------------------------+
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;
  }
//+----------------------------------------------------------------------------+
 
законопослушный гражданин #:

Gracias. Por alguna razón no tuvo ningún efecto.

Yo escribí:

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

Pero, ¿aún así abre dos posiciones dirigidas de forma diferente en el mismo tick? ¡No puede ser!

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;
  }

Sobre este código, es posible que no haya cambiado nada. Ya que las órdenes se ejecutan en el orden de cierre.

Ordene su algoritmo lo mejor posible.

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));
  }

Deberías revisar tu algoritmo, aquí estás entrando por las señales de compra y venta y nada más. ¿Qué puede no funcionar aquí? No hay funciones de entrada, ni de salida del mercado...

 

Foro sobre comercio, sistemas de comercio automatizados y pruebas de estrategias

Cualquier pregunta de los novatos en MQL4 y MQL5, ayuda y discusión sobre algoritmos y códigos

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;
  }
//+----------------------------------------------------------------------------+

¿Qué hay aquí? No ha cambiado nada en esencia. Acabas de hacer más llamadas a OrderCloseTime. El código se estiró en una línea. Y se volvió menos legible. Pero el resultado sigue siendo el mismo.

 
Mihail Matkovskij #:

¿Y aquí? No has cambiado nada en esencia. Acabas de hacer más llamadas a OrderCloseTime. Pero el resultado es el mismo.

Abre los ojos
 
MakarFX #:
abre los ojos

Discusiones en el estudio, por favor

 
Mihail Matkovskij #:

Discusiones en el estudio, por favor.

Ahora abre los ojos

 
Mihail Matkovskij #:

¿Y aquí? No has cambiado nada en esencia. Acabas de hacer más llamadas a OrderCloseTime. Y hemos estirado el código en una sola línea. Y se volvió menos legible. Pero el resultado es el mismo.

Por lo que veo, la diferencia está en lo siguiente:

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 #:

Ahora abre los ojos.

(De acuerdo. Me perdí ese momento. Lo admito.

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

Por lo que veo, la diferencia es la siguiente:

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;
  }
Razón de la queja: