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

 
Vitalie Postolache:

Ya está, eso es diferente, ahora está claro a qué se refiere el 1% ;)

if(Open[x] > Close[x]+Open[x]*0.01) {code}
No puedes entender el lenguaje. Necesitas 10 líneas para escribir dos palabras, luego necesitas sólo dos para escribir 10 palabras... Pensarías que la programación estaría bien y al final sería un lío).
 
spoiltboy:
El Asesor Experto considera los valores mínimos y máximos de las últimas X barras y coloca las órdenes por ellos. Entonces, cuando el máximo o el mínimo disminuyan, deberá eliminar la orden correspondiente y abrir por nuevos datos.


No entendí exactamente cuando se modifican las pausas, pero lo hice de manera que si el precio mínimo es mayor que el precio de ajuste de BuyLimit existente, entonces hay que modificarlo al nuevo precio Min.

Para SellLimit - reflejado.

Yo sólo he escrito el código, pero no lo he comprobado en absoluto. Os dejo a vosotros la tarea de modificar y comprobar la corrección del algoritmo y del código en general.

//--- input variables
input    double   LotB=0.1;      // Лот Buy
input    double   LotS=0.1;      // Лот Sell
input    int      Pointsl=100;   // StopLoss в пунктах
input    int      Pointtp=100;   // TakeProfit в пунктах
input    int      NumBars=10;    // Количество баров для поиска Max/Min
input    int      Magic=100500;  // Magic

//--- global variables
struct DataPendingOrder
  {
   int      number;     // Количество
   double   price_set;  // Цена установки
  };

struct DataPending
  {
   DataPendingOrder  buy_limit;  // BuyLimit
   DataPendingOrder  buy_stop;   // BuyStop
   DataPendingOrder  sell_limit; // SellLimit
   DataPendingOrder  sell_stop;  // SellStop
  };

struct DataOrders
  {
   int         buy;     // Количество позиций Buy
   int         sell;    // Количество позиций Sell
   DataPending order;   // Данные отложенного ордера
  };
DataOrders getData;   // Данные ордеров и позиций
double lotB, lotS;
int    pointsl, pointtp, numBars;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   numBars=(NumBars<1?1:NumBars>Bars?Bars:NumBars);
   pointsl=(Pointsl<0?0:Pointsl);
   pointtp=(Pointtp<0?0:Pointtp);
   double minLot=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);
   double maxLot=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
   lotB=(LotB<minLot?minLot:LotB>maxLot?maxLot:LotB);
   lotS=(LotS<minLot?minLot:LotS>maxLot?maxLot:LotS);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   //--- заполним структуру количеством ордеров и позиций
   GetNumOrders(Symbol(),Magic,getData);
  
   //--- найдём максимальную и минимальную цены за bars свечей
   double maxPrice=0.0, minPrice=DBL_MAX;
   for(int i=0; i<numBars; i++) {
      double max_i=iHigh(Symbol(),PERIOD_CURRENT,i);
      if(max_i>maxPrice) maxPrice=max_i;
      double min_i=iLow(Symbol(),PERIOD_CURRENT,i);
      if(min_i<minPrice) minPrice=min_i;
      }

   //--- если нету рыночных Buy
   if(getData.buy==0) {
      //--- если нет отложенного BuyLimit
      if(getData.order.buy_limit.number==0) {
         double slB=(pointsl==0?0:NormalizeDouble(minPrice-pointsl*Point(),Digits()));
         double tpB=(pointtp==0?0:NormalizeDouble(minPrice+pointtp*Point(),Digits()));
         ResetLastError();
         int ticketUP=OrderSend(Symbol(), OP_BUYLIMIT, lotB, minPrice, 3, slB, tpB, "", Magic, 0, clrRed);
         if(ticketUP==-1) Print("ERROR SETTING OP_BUYLIMIT :",GetLastError());
         else Print("OP_BUYLIMIT OK");
         }
      //--- если есть BuyLimit
      else {
         //--- если цена Min больше цены установки BuyLimit
         if(minPrice>getData.order.buy_limit.price_set) {
            // модифицировать BuyLimit - поставить его на цену minPrice ...
            //--- ... и сместить его стоп-уровни относительно новой цены установки
            }
         }
      }
  
   //--- если нету рыночных Sell
   if(getData.sell==0) {
      //--- если нет отложенного SellLimit
      if(getData.order.sell_limit.number==0) {
         double slS=(pointsl==0?0:NormalizeDouble(maxPrice+pointsl*Point(),Digits()));
         double tpS=(pointtp==0?0:NormalizeDouble(maxPrice-pointtp*Point(),Digits()));
         ResetLastError();
         int ticketD=OrderSend(Symbol(), OP_SELLLIMIT, lotS, maxPrice, 3, slS, tpS, "", Magic, 0, clrBlue);
         if(ticketD==-1) Print("ERROR SETTING OP_SELLLIMIT :",GetLastError());
         else Print("OP_SELLLIMIT OK");
         }
      //--- если есть SellLimit
      else {
         //--- если цена Max меньше цены установки SellLimit
         if(maxPrice<getData.order.sell_limit.price_set) {
            // модифицировать SellLimit - поставить его на цену maxPrice ...
            //--- ... и сместить его стоп-уровни относительно новой цены установки
            }
         }
      }

   //---
   string a=(numBars==1)?"bar: ":IntegerToString(numBars,1)+" bar's: ";
   Comment("Last ", a, "max ", DoubleToStr(maxPrice, Digits()), ", min ", DoubleToStr(minPrice, Digits()),".");
  }
//+------------------------------------------------------------------+
//| Записывает в структуру количество позиций и отложенных ордеров   |
//+------------------------------------------------------------------+
void GetNumOrders(string symbol_name, int magic_number, DataOrders &data_of) {
   ZeroMemory(data_of);
   for(int i=OrdersTotal()-1; i>=0; i--) {
      if(OrderSelect(i,SELECT_BY_POS)) {
         if(OrderMagicNumber()!=magic_number) continue;
         if(OrderSymbol()!=symbol_name)       continue;
         //--- рыночные позиции
         if(OrderType()==OP_BUY)    data_of.buy++;
         if(OrderType()==OP_SELL)   data_of.sell++;
         //--- отложенные ордера
         if(OrderType()==OP_BUYLIMIT)  {  data_of.order.buy_limit.number++;   data_of.order.buy_limit.price_set=OrderOpenPrice();   }
         if(OrderType()==OP_BUYSTOP)   {  data_of.order.buy_stop.number++;    data_of.order.buy_stop.price_set=OrderOpenPrice();    }
         if(OrderType()==OP_SELLLIMIT) {  data_of.order.sell_limit.number++;  data_of.order.sell_limit.price_set=OrderOpenPrice();  }
         if(OrderType()==OP_SELLSTOP)  {  data_of.order.sell_stop.number++;   data_of.order.sell_stop.price_set=OrderOpenPrice();   }
         }
      }
}
//+------------------------------------------------------------------+

Espero que lo descubras

 
Artyom Trishkin:

¿Por qué borrar cuando se puede modificar el precio de ajuste y el stop y takeout en relación con el nuevo nivel?

Acabo de empezar a estudiar y la opción de borrado era para estudiar la aplicación de la función, me preguntaba por qué no funcionaba.

Gracias a todos por sus comentarios.

 

¿Alguien quiere saber cómo debería ser el comando de reinicio externo?

cómo debería ser

1) Seleccione un conjunto de condiciones necesarias de la lista para que el comando se active, por ejemplo, abrir una orden

2) La orden se abre y el comando no funciona bajo ninguna otra condición. El filtrado por cantidad de billetes y de pedidos no es una opción, ya que el propio principio debe estar repartido por toda la lista.

 
if (MA1>GrossMA1 && MA2<GrossMA2 && Bid>MA1+Distanse*Point() ) ¿Cuál es el error aquí si GrossMA1[0], MA1[0] GrossMA2[1] MA2[1] utilizan la intersección en movimiento + filtro en la distancia después de la intersección en movimiento. ¿Cuál es la precisión de esta condición?
 
Movlat Baghiyev:
if (MA1>GrossMA1 && MA2<GrossMA2 && Bid>MA1+Distanse*Point() ) Cuál es el error aquí si GrossMA1[0], MA1[0] GrossMA2[1] MA2[1] utilizan la intersección móvil + filtran por la distancia después de la intersección móvil. ¿Cuál es la precisión de esta condición?

Lo que te devuelvenGrossMA1 yGrossMA2, lo más probable es que haya una diferencia allí, terminas con algo así

MA1= 1,0050

if (MA1 > 0.0052) // no es el precio en sí, sino su diferencia, por lo que no es una comparación incorrecta

 
Vitaly Muzichenko:

Lo que te devuelvenGrossMA1 yGrossMA2, probablemente hay una diferencia allí, terminas con algo así

MA1= 1,0050

if (MA1 > 0.0052) // es decir, no el precio en sí, sino su diferencia, por lo que es una comparación incorrecta

¿Puede decirme cómo hacerlo correctamente?
 
Vitaly Muzichenko:

Lo que te devuelvenGrossMA1 yGrossMA2, lo más probable es que haya una diferencia allí, terminas con algo así

MA1= 1,0050

if (MA1 > 0.0052) // es decir, no el precio en sí, sino su diferencia, por lo que es una comparación incorrecta

FRMA1=iMA(Symbol(), 0, Faster_MA_Period, Faster_MA_Shift, Faster_MA_method, Faster_MA_Apply_to, 0);
    FRMA2=iMA(Symbol(), 0, Faster_MA_Period, Faster_MA_Shift, Faster_MA_method, Faster_MA_Apply_to, 1);

    FMA1=iMA(Symbol(), 0, Fast_MA_Period, Fast_MA_Shift, Fast_MA_method, Fast_MA_Apply_to, 0);
    FMA2=iMA(Symbol(), 0, Fast_MA_Period, Fast_MA_Shift, Fast_MA_method, Fast_MA_Apply_to, 1);

    GrossMA1=iMA(Symbol(), 0, Gross_MA_Period, Gross_MA_Shift, Gross_MA_method, Gross_MA_Apply_to, 0);
    GrossMA2=iMA(Symbol(), 0, Gross_MA_Period, Gross_MA_Shift, Gross_MA_method, Gross_MA_Apply_to, 1);
 
Vitaly Muzichenko:

Lo que te devuelvenGrossMA1 yGrossMA2, probablemente hay una diferencia allí, terminas con algo así

MA1= 1,0050

if (MA1 > 0.0052) // es decir, no el precio en sí, sino su diferencia, por lo que es una comparación incorrecta

La intersección es correcta. La pregunta está más relacionada con esta condiciónOferta>MA1+Distanse*Punto()
 

Buenas tardes. ¿Puede decirme dónde está el error?

extern int pointsl=100, pointtp=100, MagicB=1111, MagicS=2222, bars=10;  extern double lotB=0.1, lotS=0.1;
double slB, tpB, slS, tpS;  double x=0, z=0; int ticketUP, ticketD;

void OnTick()
  {
double maxpr1=-9999; double minpr1=9999;

for(int shift1=0; shift1<bars; shift1++)
{double i=iHigh(Symbol(), PERIOD_CURRENT, shift1);
if (i>maxpr1){maxpr1=i;}}

for(int shiftA1=0; shiftA1<bars; shiftA1++)
{double y=iLow(Symbol(), PERIOD_CURRENT, shiftA1);
if (y<minpr1) {minpr1=y;}}



slS=NormalizeDouble(maxpr1+pointsl*Point,5);
tpS=NormalizeDouble(maxpr1-pointtp*Point,5);
ticketD=OrderSend(Symbol(), OP_SELLLIMIT, lotS, maxpr1, 3, slS, tpS, "", MagicS, 0, Blue);
if (ticketD==-1) Print("ERROR OP_SELL"); else Print("OP_SELL OK");
  } 

Todo funciona, hace un pedido al precio de maxpr1.

Entonces quiero hacer lo mismo, pero a precio de minpr1:

extern int pointsl=100, pointtp=100, MagicB=1111, MagicS=2222, bars=10;  extern double lotB=0.1, lotS=0.1;
double slB, tpB, slS, tpS;  double x=0, z=0; int ticketUP, ticketD;

void OnTick()
  {
double maxpr1=-9999; double minpr1=9999;

for(int shift1=0; shift1<bars; shift1++)
{double i=iHigh(Symbol(), PERIOD_CURRENT, shift1);
if (i>maxpr1){maxpr1=i;}}

for(int shiftA1=0; shiftA1<bars; shiftA1++)
{double y=iLow(Symbol(), PERIOD_CURRENT, shiftA1);
if (y<minpr1) {minpr1=y;}}



slS=NormalizeDouble(minpr1+pointsl*Point,5);
tpS=NormalizeDouble(minpr1-pointtp*Point,5);
ticketD=OrderSend(Symbol(), OP_SELLLIMIT, lotS, minpr1, 3, slS, tpS, "", MagicS, 0, Blue);
if (ticketD==-1) Print("ERROR OP_SELL"); else Print("OP_SELL OK");
  }

Error 130 (paradas erróneas). ¿Qué estoy haciendo mal?

Razón de la queja: