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

 
MakarFX, lo probó - no hay cambio, sólo se abre en la compra, y la venta se ignora por completo ...
 
artem artem #:
MakarFX, lo probó - no hay cambio, sólo se abre en la compra, y la venta se ignora por completo ...
De ahí la conclusión de que no hay condiciones para cambiar de bools
 
¿Qué hay que añadir entonces a las condiciones?
 
artem artem #:
¿Qué debemos añadir a estas condiciones?

Explica la lógica...

La primera es clara: hay una señal y no hay órdenes abiertas...

... y luego no entiendo en qué condiciones se deben abrir o cerrar las órdenes

 
artem artem #:
¿Qué hay que añadir entonces para que se den las condiciones?

Prueba esto

//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+
void start()
{
   StopLevel = MarketInfo(Symbol(), MODE_STOPLEVEL); 
   
   // Определение направления пересечения мувингов
   if (Init) InitMetod(); 
   
   // Трейлинг стоп открытых позиций
   if (Trailing != 0 ) RealTrailOrder(TrailStop, TrailStep, StopLevel, MagicNumber);
   
   // Ожидание нового бара на графике
   if(timeprev == Time[0]) return;
   timeprev = Time[0];
   
   // Открытие ордера по методу Пуриа
   if(CheckForOpen()==0) // Если сигнал для покупок 
     {
      if(OrderSend(Symbol(),OP_BUY,Lots(),Ask,Slip,Bid-StopLoss*Point,Ask+TakeProfit*Point,"",MagicNumber,0,Blue))
         { Order=false; OrderBuy=true; OrderSell=false; Print("BUY OK"); } 
     } 
   if(CheckForOpen()==1) // Если сигнал для продаж 
     {
      if(OrderSend(Symbol(),OP_SELL,Lots(),Bid,Slip,Ask+StopLoss*Point,Bid-TakeProfit*Point,"",MagicNumber,0,Red))
        { Order=false; OrderBuy=false; OrderSell=true; Print("SELL OK");} 
     }
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
int CheckForOpen() // Открытие ордера по методу Пуриа
  {
   double malw,mas1,mas2,macd;
   int    res=-1, buy=0, sell=0;
   // Считывание параметров индикаторов 3 свечи (4ой)
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,3);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,3);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,3);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,3);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   // Считывание параметров индикаторов 2 свечи (3ей)
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,2);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,2);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,2);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,2);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   // Считывание параметров индикаторов 1 свечи (2ой)
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,1);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,1);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,1);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,1);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   // Считывание параметров индикаторов 0 свечи (1ой)
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,0);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,0);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,0);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,0);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   
   if(buy ==4 && OrderSell) res=0;
   if(sell==4 && OrderBuy)  res=1;
   return(res);
  }
//+------------------------------------------------------------------+
 

Vale, lo explicaré todo por orden, intentando ser específico y no desbordar...

Se basa en una estrategia de trading de tendencia llamada "Método Puria". Se basa en el cruce de tres medias móviles y en la apertura de la barra del MACD. Dos lentos con periodos (75) y (85), método lineal ponderado aplicado a Low. Una media rápida con un periodo (5), método exponencial, se aplica a Close. Indicador MACD con los parámetros 15/26/1. El punto de entrada se forma al cruzar dos medias móviles lentas y la apertura de la barra MACD en la zona correspondiente con la rápida (la barra rápida y la MACD deben estar en la misma zona):

  • Señal de COMPRA - La MA(5) cruzó y está por encima de la MA(75) y la MA(85) con la barra del MACD abierta en la zona positiva.
  • Señal de VENTA - La MA(5) cruzó y está por debajo de la MA(75) y la MA(85), el MACD tiene una barra abierta en la zona negativa.

El EA coloca un beneficio y un stop loss fijos. El tamaño del beneficio y el stop se fijan en los parámetros iniciales. Las órdenes se cierran sólo cuando alcanzan el Take Profit o el Stop Loss.

Esto es lo que había en los asesores expertos originales de Puria. Además, en la última versión, también hay un trailing stop y la opción de operar por horas. Las funciones son útiles, pero ahora no me interesan mucho.

Ahora, en realidad, qué adiciones he hecho/quiero hacer:

1. Para realizar una apertura de la operación y comprobar todas las condiciones de los indicadores(cruce de un rápido (5) de dos lentos (75) (85) y apertura de una barra MACD en la misma dirección con un rápido (5)), se realizó sólo en el precio de apertura de una nueva vela (el primer tick de cada vela de 30 minutos). Esto ya ha sido tratado;
  1. Crear condiciones para la "puesta a cero" de los indicadores. Por ejemplo, para un movimiento rápido (5) Si es más alta que la lenta, es una señal de compra. Si entonces baja y toca uno de ellos, o se encuentra entre los lentos (75) y (85)- entonces la señal del indicador rápido "se pone a cero" por así decirlo, y permanecerá en esta posición "cero" mientras toque o se mantenga entre los lentos. Si, después de eso, la rápida cruza las dos lentas hacia un lado(incluso si volvió al lado del que venía antes de tocar las lentas) - entonces será una señal de este indicador. Con el MACD la situación es similar- Sólo el MACD=0 se considerará como "puesta a cero" (si en la primera vela el MACD, por ejemplo, abrió con 0,0043, y en la segunda vela con -0,0010, significa que el MACD en la segunda vela se ha "puesto a cero" y ha dado una nueva señal). Sin embargo, hay un momento en el que el rápido (5) y el MACD deben estar como "en igualdad de condiciones" - si (5) no cambia su posición en relación con el lento, y el MACD ha abierto en la vela anterior en la zona equivocada (sin entrada), y en la siguiente - en la misma zona que el rápido, entonces todas las condiciones han convergido y una entrada a la orden debe ocurrir. Tenga en cuenta que todo esto debe ser sólo en los precios de apertura de las velas - sólo en esta garrapata;
  1. Y la última, hacer que el Asesor Experto espere 4 aperturas de velas consecutivas:

    1. 1er precio de apertura - (5) por encima de (75) y (85) + barra MACD abierta por encima de 0 - 1 de 4 confirmaciones;
    2.2. El precio de apertura de la 2ª vela - (5) sobre (75) y (85) + barra MACD abierta sobre 0- 2 de 4 confirmaciones es;
    3. El precio de apertura de la 3ª vela - (5) sobre (75) y (85) + barra MACD abierta sobre 0- 3 de 4 confirmaciones es;
    4.Precio de apertura de la 4ª vela - (5) por encima de (75) y (85) + barra MACD abierta por encima de 0- 4 de 4 confirmaciones- Abrir operación de compra en la misma vela (4ª).
La misma situación con las órdenes de venta, sólo que en la otra dirección deben abrirse los indicadores. Y hay un punto importante - si en, digamos, cualquier etapa desde la 1ª vela hasta la 4ª, los indicadores cambian su posición (por ejemplo, en la 3ª vela de apertura, la barra del MACD se abre por debajo de 0, o =0) - entonces todo se reinicia, porque las señales no han pasado la prueba en la apertura de la 4ª vela consecu tiva.


De alguna manera, si algo no está claro, o hay preguntas, por favor pregunte.

 
artem artem #:

Vale, lo explicaré todo por orden, intentaré ser concreto y no desbordar...


  1. Crear condiciones para "poner a cero" los indicadores.

Esto es la puesta a cero.

   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}

Tal vez no te entiendo bien...

intente hacer una captura de pantalla

 
He adjuntado una captura de pantalla, si no entiendes algo, pregunta
Archivos adjuntos:
 
artem artem #:
He adjuntado una captura de pantalla, si no entiendes algo, pregúntame.
Lo tengo, lo pensaré.
 
artem artem #:
Adjunto una captura de pantalla, si algo no está claro - sólo pregunte

Pruebe éste: ¿se abrirá en esos lugares?

//+------------------------------------------------------------------+
//|                                                  artem artem.mq4 |
//|                        Copyright 2021, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
//---
#define  MagicNumber  122122
//---
#include <stdlib.mqh> // Стандартная библиотека
//---
input string s0 = "Баланс";            // 1
input string Template       = "ADX";   // Имя шаблона(without '.tpl')
input double TargetProfit   = 1000000; // Баланс + Прибыль(прибавить к балансу)
input double TargetLoss     = 0;       // Баланс - Убыток(отнять от баланса)
input string s1 = "Размер лота";       // 2
input double Lot            = 0.01;    // размер лота 0 - авт.расчет
input string s2 = "TP SL";             // 3
input double InpTProfit     = 1000;    // Exchange TP
input double InpStopLoss    = 1000000; // Exchange SL
input string s3 = "Индикатор";         // 4
input int    MovingPeriodLw = 13;      // MovingPeriodLw
input int    MovingPeriodS1 = 89;      // MovingPeriodS1
input int    MovingPeriodS2 = 144;     // MovingPeriodS2
input string s4 = "Day & Hour";        // 5
input int    HrStart        = 0;       // время начала торговли
input int    HrEnd          = 23;      // время окончания торговли
//+------------------------------------------------------------------+
int    Monday         = 1;      // Понедельник 1 вкд. 0 выкл.
int    Tuesday        = 1;      // Вторник
int    Wednesday      = 1;      // Среда
int    Thursday       = 1;      // Четверг
int    Friday         = 1;      // Пятница
//+------------------------------------------------------------------+
uint SLEEPTIME=1;
double Price[2];
datetime timeprev=0;
ENUM_TIMEFRAMES TimeFrame= PERIOD_CURRENT;
bool OrderBuy=false,OrderSell=false,Order=false,Init=true,ClOp=true;
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- Закрыть Общий профит или профит на паре
   if(ProfitTarget())
     {
      return;
     }
//--- Закрыть профит BUY или SELL на паре
   ProfitOnTick();
// Определение направления пересечения мувингов
   if(Init)
      InitMetod();
// Ожидание нового бара на графике
   if(timeprev == Time[0])
      return;
   timeprev = Time[0];
// Открытие ордера по методу Пуриа
   CheckForOpen();
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen() // Открытие ордера по методу Пуриа
  {
   double malw,mas1,mas2,macd;
   int    res;
// Считывание параметров индикаторов
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,0);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,0);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,0);
   macd=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
// Проверяем положение мувмнгов
   if(malw>mas1 && malw>mas2  && OrderSell)
     {
      OrderBuy=true;
      OrderSell=false;
      Order=true;
     }
   if(malw<mas1 && malw<mas2  && OrderBuy)
     {
      OrderBuy=false;
      OrderSell=true;
      Order=true;
     }
// Открываем ордер Buy
   if(macd>0 && OrderBuy && Order)
     {
      res=OrderSend(Symbol(),OP_BUY,Lots(),Ask,3,0,0,"",MagicNumber,0,Blue);
      Order=false;
      return;
     }
// Открываем ордер Sell
   if(macd<0 && OrderSell && Order)
     {
      res=OrderSend(Symbol(),OP_SELL,Lots(),Bid,3,0,0,"",MagicNumber,0,Red);
      Order=false;
      return;
     }
  }
//+------------------------------------------------------------------+
//| Init metod Puria function                                        |
//+------------------------------------------------------------------+
void InitMetod()  // Опредеоение начального пересечения мувингов
  {
   double malw,mas1,mas2;
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,0);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,0);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,0);
   if((malw<=mas1 && malw>=mas2) || (malw>=mas1 && malw<=mas2))
     {
      Init=false;
      OrderBuy=true;
      OrderSell=true;
     }
   return;
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double Lots()  // Расчет объема лота
  {
   double Lots;
   if(Lot > 0)
      return(Lot);
   Lots=AccountFreeMargin()/5000;
   Lots=MathMin(15,MathMax(0.01,Lots));
   if(Lots<0.1)
      Lots=NormalizeDouble(Lots,2);
   else
     {
      if(Lots<1)
         Lots=NormalizeDouble(Lots,1);
      else
         Lots=NormalizeDouble(Lots,0);
     }
   return(Lots);
  }
//+------------------------------------------------------------------+
// Permission to trade in this day                                   |
//+------------------------------------------------------------------+
bool TradingDay(int hmin, int hmax) // Определение времени и дня разрешения торговли
  {
   bool dtrade = false;
   switch(DayOfWeek())
     {
      case 1: // Monday
         if(Monday == 1)
            dtrade = true;
         break;
      case 2: // Tuesday
         if(Tuesday == 1)
            dtrade = true;
         break;
      case 3: // Wednesday
         if(Wednesday == 1)
            dtrade = true;
         break;
      case 4: // Thursday
         if(Thursday == 1)
            dtrade = true;
         break;
      case 5: // Friday
         if(Friday == 1)
            dtrade = true;
         break;
      default: //
         dtrade = false;
         break;
     }
   if(dtrade && !(Hour() >= hmin && Hour() <= hmax))
      dtrade = true;
   return dtrade;
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool ProfitTarget(void)
  {
   bool res=false;
   if(AccountInfoDouble(ACCOUNT_EQUITY)<=TargetLoss ||
      AccountInfoDouble(ACCOUNT_EQUITY)>=TargetProfit)
     {
      CloseAllOrders();
      Sleep(SLEEPTIME*1000);
      CloseAllOrders();
      ExpertRemove();
      DeleteChart();
      PlaySound("expert.wav");
      res=true;
     }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool ProfitOnTick(void)
  {
   bool res=false;
   double PROFIT_BUY=0.00;
   double PROFIT_SELL=0.00;
   for(int i=OrdersTotal()-1; i>=0; i--) // returns the number of open positions
     {
      if(OrderSelect(i,SELECT_BY_POS) && OrderSymbol()==Symbol())
        {
         if(OrderSymbol()==Symbol() && OrderType()==OP_BUY)
           {
            PROFIT_BUY=PROFIT_BUY+NormalizeDouble(OrderProfit(),2);
           }
         if(OrderSymbol()==Symbol() && OrderType()==OP_SELL)
           {
            PROFIT_SELL=PROFIT_SELL+NormalizeDouble(OrderProfit(),2);
           }
        }
     }
   int Close_ticketb=0;
   int totalb=OrdersTotal();
   int b = 0;
   for(b = totalb; b >=0; b--)
     {
      if(OrderSelect(b,SELECT_BY_POS) && OrderSymbol()==Symbol())
        {
         //OrderSelect(i,SELECT_BY_POS);
         if(OrderSymbol()==Symbol() && OrderType()==OP_BUY)
           {
            if(PROFIT_BUY<-InpStopLoss || PROFIT_BUY>=InpTProfit)
              {
               Close_ticketb = OrderClose(OrderTicket(),OrderLots(),MarketInfo(Symbol(),MODE_BID),5);
               PlaySound("ok.wav");
              }
           }
        }
      res=true;
     }
   int Close_tickets=0;
   int totals=OrdersTotal();
   int s = 0;
   for(s = totals; s >=0; s--)
     {
      if(OrderSelect(s,SELECT_BY_POS) && OrderSymbol()==Symbol())
        {
         if(OrderSymbol()==Symbol() && OrderType()==OP_SELL)
           {
            if(PROFIT_SELL<-InpStopLoss || PROFIT_SELL>=InpTProfit)
              {
               Close_tickets = OrderClose(OrderTicket(),OrderLots(),MarketInfo(Symbol(),MODE_ASK),5);
               PlaySound("ok.wav");
              }
           }
        }
      res=true;
     }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
void CloseAllOrders(void)
  {
   int iOrders=OrdersTotal()-1, i;
   if(ClOp)
     {
      for(i=iOrders; i>=0; i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && (OrderType()<=OP_SELL) && GetMarketInfo() &&
            !OrderClose(OrderTicket(),OrderLots(),Price[1-OrderType()],0))
            Print(OrderError());
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
           {
            if(OrderDelete(OrderTicket()))
               Print(OrderError());
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Function..: OrderError                                           |
//+------------------------------------------------------------------+
string OrderError(void)
  {
   int iError=GetLastError();
   return(StringConcatenate("Order:",OrderTicket()," GetLastError()=",iError," ",ErrorDescription(iError)));
  }
//+------------------------------------------------------------------+
//| Function..: GetMarketInfo                                        |
//+------------------------------------------------------------------+
bool GetMarketInfo(void)
  {
   RefreshRates();
   Price[0]=MarketInfo(OrderSymbol(),MODE_ASK);
   Price[1]=MarketInfo(OrderSymbol(),MODE_BID);
   double dPoint=MarketInfo(OrderSymbol(),MODE_POINT);
   if(dPoint==0)
      return(false);
   return(Price[0]>0.0 && Price[1]>0.0);
  }
//+------------------------------------------------------------------+
//| start function                                                   |
//+------------------------------------------------------------------+
void DeleteChart(void)
  {
   long currChart,prevChart=ChartFirst();
   int i=0,limit=100;
   bool errTemplate;
   while(i<limit)
     {
      currChart=ChartNext(prevChart);
      if(TimeFrame!=PERIOD_CURRENT)
        {
         ChartSetSymbolPeriod(prevChart,ChartSymbol(prevChart),TimeFrame);
        }
      errTemplate=ChartApplyTemplate(prevChart,Template+".tpl");
      if(!errTemplate)
        {
         Print("Error ",ChartSymbol(prevChart),"-> ",GetLastError());
        }
      if(currChart<0)
         break;
      Print(i,ChartSymbol(currChart)," ID =",currChart);
      prevChart=currChart;
      i++;
     }
  }
//+------------------------------------------------------------------+
Razón de la queja: