¿Cómo encontrar el momento de la barra donde se cruzaron las medias móviles? (código interior)

 

¡Hola a todos!

Esperaba que me ayudaran con mi código, ya que estoy atascado en esta maldita parte.


Este es el proceso que estoy tratando de escribir en el código de abajo:

1) Si todos los MA's están "abanicados" y cruzados de manera que el precio está por encima de todos los promedios móviles y están indicando un potencial largo.

2) Luego quiero saber la barra exacta (usando el tiempo) en la que las medias móviles se "separan" en el cruce de las medias móviles.

3) Si 1 y 2 son ciertos, entonces espero a que cualquier barra vuelva a bajar (en el caso para una posición larga) y toque la EMA 21.

4) Desde la primera barra (donde las MA's se cruzaron y se abrieron en abanico) hasta la barra que ahora ha tocado la 21 EMA - quiero una orden pendiente O en la operación de mercado colocada POR ENCIMA de los máximos de este rango (1 y 3).

5) Si el precio en CUALQUIER momento CIERRA por debajo de la 60 EMA, ANTES de activar la orden - entonces la orden debe ser cancelada.

Obviamente este no es todo el código, pero es la parte principal con la que me estoy tirando de los pelos. Por favor, compruebe el código con el "<<<<<<<<<<<<<". Estos son los puntos en los que estoy confundido.

Me vendría muy bien que alguien me ayudara, se lo agradecería mucho.

Muchas gracias de antemano.

datetime          triggerBarTime;   <<<<< Global settings.
datetime          triggerBarTime1;  <<<<< Global settings.	



void CheckForMaTrade()
{

//+-----------------------------------------------------------------------------------------------------------------------+ 
    //Small and Big Fish on the H1 Time Frame.                                                                           |
//+-----------------------------------------------------------------------------------------------------------------------+              

   {
   double PreviousSmallFish1  =  iMA(NULL,60,3,0,1,0,2); 
   double CurrentSmallFish1   =  iMA(NULL,60,3,0,1,0,1);
   double PreviousSmallFish2  =  iMA(NULL,60,5,0,1,0,2);
   double CurrentSmallFish2   =  iMA(NULL,60,5,0,1,0,1);
   double PreviousSmallFish3  =  iMA(NULL,60,8,0,1,0,2);
   double CurrentSmallFish3   =  iMA(NULL,60,8,0,1,0,1);
   double PreviousSmallFish4  =  iMA(NULL,60,10,0,1,0,2);
   double CurrentSmallFish4   =  iMA(NULL,60,10,0,1,0,1);  
   double PreviousSmallFish5  =  iMA(NULL,60,12,0,1,0,2);
   double CurrentSmallFish5   =  iMA(NULL,60,12,0,1,0,1);
   double PreviousSmallFish6  =  iMA(NULL,60,15,0,1,0,2);
   double CurrentSmallFish6   =  iMA(NULL,60,15,0,1,0,1);  
   
      double PreviousBigFish1  =  iMA(NULL,60,30,0,1,0,2); 
      double CurrentBigFish1   =  iMA(NULL,60,30,0,1,0,1);
      double PreviousBigFish2  =  iMA(NULL,60,35,0,1,0,2);
      double CurrentBigFish2   =  iMA(NULL,60,35,0,1,0,1);
      double PreviousBigFish3  =  iMA(NULL,60,40,0,1,0,2);
      double CurrentBigFish3   =  iMA(NULL,60,40,0,1,0,1);
      double PreviousBigFish4  =  iMA(NULL,60,45,0,1,0,2);
      double CurrentBigFish4   =  iMA(NULL,60,45,0,1,0,1);
      double PreviousBigFish5  =  iMA(NULL,60,50,0,1,0,2);
      double CurrentBigFish5   =  iMA(NULL,60,50,0,1,0,1);
      double PreviousBigFish6  =  iMA(NULL,60,60,0,1,0,2);
      double CurrentBigFish6   =  iMA(NULL,60,60,0,1,0,1); 
      
            if(PreviousBigFish1<CurrentBigFish2 && CurrentBigFish1>PreviousBigFish2)
               if(PreviousBigFish2<CurrentBigFish3 && CurrentBigFish2>PreviousBigFish3)
                  if(PreviousBigFish3<CurrentBigFish4 && CurrentBigFish3>PreviousBigFish4)
                     if(PreviousBigFish4<CurrentBigFish5 && CurrentBigFish4>PreviousBigFish5)
                        if(PreviousBigFish5<CurrentBigFish6 && CurrentBigFish5>PreviousBigFish6)  
                           
                           if(PreviousSmallFish1<CurrentSmallFish2 && CurrentSmallFish1>PreviousSmallFish2)
                        if(PreviousSmallFish2<CurrentSmallFish3 && CurrentSmallFish2>PreviousSmallFish3)
                     if(PreviousSmallFish3<CurrentSmallFish4 && CurrentSmallFish3>PreviousSmallFish4)
                  if(PreviousSmallFish4<CurrentSmallFish5 && CurrentSmallFish4>PreviousSmallFish5)
                if(PreviousSmallFish5<CurrentSmallFish6 && CurrentSmallFish5>PreviousSmallFish6)triggerBarTime = Time[1];  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
      
      
      double ema21 = iMA(NULL,60,21,0,1,0,1); 
       
        
         if (Low[1]<ema21)
         {
         
           OrderEntry(0); // BUY 
            }     
      
      
                
     if(PreviousBigFish1>CurrentBigFish2 && CurrentBigFish1<PreviousBigFish2)
      if(PreviousBigFish2>CurrentBigFish3 && CurrentBigFish2<PreviousBigFish3)
         if(PreviousBigFish3>CurrentBigFish4 && CurrentBigFish3<PreviousBigFish4)
            if(PreviousBigFish4>CurrentBigFish5 && CurrentBigFish4<PreviousBigFish5)
               if(PreviousBigFish5>CurrentBigFish6 && CurrentBigFish5<PreviousBigFish6)
               
               if(PreviousSmallFish1>CurrentSmallFish2 && CurrentSmallFish1<PreviousSmallFish2)
            if(PreviousSmallFish2>CurrentSmallFish3 && CurrentSmallFish2<PreviousSmallFish3)
         if(PreviousSmallFish3>CurrentSmallFish4 && CurrentSmallFish3<PreviousSmallFish4)
       if(PreviousSmallFish4>CurrentSmallFish5 && CurrentSmallFish4<PreviousSmallFish5)
     if(PreviousSmallFish5>CurrentSmallFish6 && CurrentSmallFish5<PreviousSmallFish6)triggerBarTime = Time[1]; <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   
    double ema21_2 = iMA(NULL,60,21,0,1,0,1); 
  
            if(High[1]>ema21_2)
            {
             
              OrderEntry(1); // SELL
             }  
   
       }

}


//+------------------------------------------------------------------+  
//+------------------------------------------------------------------+
//| Order Enter Function                                             |
//+------------------------------------------------------------------+

void OrderEntry (int direction)
{    
   double LotSize=0;
   double Equity=AccountEquity();
   double RiskedAmount=Equity*RiskPercent*0.01;
   int buyStopCandle = iLowest(NULL,0,1,CandlesBack,1); 
   int sellStopCandle = iHighest(NULL,0,2,CandlesBack,1);
   
   double buyPrice = iHighest(Symbol(), 0, MODE_HIGH, iBarShift(Symbol(), 0, triggerBarTime, true), 0);    <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< 
   double sellPrice = iLowest(Symbol(), 0, MODE_LOW, iBarShift(Symbol(), 0, triggerBarTime1, true), 0);   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   
   double buy_stop_price = iMA(NULL,60,60,0,1,0,1)-PadAmount*pips; 
   double pips_to_bsl = Ask-buy_stop_price;         //double pips_to_bsl = Ask-buy_stop_price;   --- Old code
   double buy_takeprofit_price = Ask+pips_to_bsl*RewardRatio;   
   double sell_stop_price = iMA(NULL,60,60,0,1,0,1)+PadAmount*pips; //- Greyed out, this is an old code line.
   double pips_to_ssl = sell_stop_price-Bid;     ////double pips_to_ssl = sell_stop_price-Bid;   --- Old code
   double sell_takeprofit_price = Bid-pips_to_ssl*RewardRatio;   
   
  
   if (direction==0)//<< "0" pushes out a Buy direction
   {
      //double buyPrice = iHighest(Symbol(), 60, MODE_HIGH, iBarShift(Symbol(), 0, triggerBarTime, true), 0);//-PadAmount*pips; // new line
      int Buy_Price = buyPrice;
      
      double bsl=buy_stop_price;
      double btp=buy_takeprofit_price;
      //LotSize = (100/(0.00500/0.00010))/10
      LotSize = (RiskedAmount/(pips_to_bsl/pips))/10;
      if(OpenOrdersThisPair(Symbol())==0) //--- This means that it will not open a new order if there is one already open!If greyed out, it will take everything.
      int buyticket = OrderSend(Symbol(),Buy_Price,LotSize,Ask,3,0,0,NULL,MagicNumber,0,Green); //ask
      if(buyticket>0)OrderModify(buyticket,OrderOpenPrice(),bsl,btp,0,CLR_NONE);
   }
            
   if (direction==1) //<< "1" pushes out a Sell direction
   {
      
      //double sellPrice = iLowest(Symbol(), 60, MODE_LOW, iBarShift(Symbol(), 0, triggerBarTime1, true), 0);//+PadAmount*pips;   // new line.
      int Sell_Price = sellPrice;
      
      double ssl=sell_stop_price;
      double stp=sell_takeprofit_price; 
      //LotSize = (100/(0.00500/0.00010))/10;
      LotSize = (RiskedAmount/(pips_to_ssl/pips))/10;    
      if(OpenOrdersThisPair(Symbol())==0)  //--- This means that it will not open a new order if there is one already open! If greyed out, it will take everything.
      int sellticket = OrderSend(Symbol(),Sell_Price,LotSize,Bid,3,ssl,stp,NULL,MagicNumber,0,Red); //bid
      if(sellticket>0)OrderModify(sellticket,OrderOpenPrice(),ssl,stp,0,CLR_NONE);
   }
   
}

return(0);

 
DomGilberto:

¡Hola a todos!

Obviamente este no es todo el código, pero esta es la parte principal con la que me estoy tirando de los pelos. Por favor, compruebe el código con el "<<<<<<<<<<<<<". Estos son los puntos en los que estoy confundido.

Por favor, lea la documentación de las funciones que está utilizando...iHighest() no devuelve un precio... devuelve un int"Devuelve el desplazamiento del valor máximo sobre un número específico de períodos dependiendo del tipo".
 

Gracias RaptorUK - De la manera más amable posible, eso no me explica nada? ¿En términos sencillos?

¿Es este un foro en el que alguien puede ayudarme de verdad, aparte de repetir las definiciones de las funciones (que he leído cientos de veces en la sección de "ayuda"...)?

Después de todo, no creo que lo que estoy pidiendo (en comparación con algunos de los hilos de aquí) sea suficiente para justificar que alguien cobre por su tiempo...

 

Traducir a términos legos te ayudará... una vez, hoy, con este tema en particular.. y tomar un poco de tiempo para el explicador.

Si dices cuales de las definiciones no entiendes, tal vez la próxima vez puedas resolver tus propios problemas, y después de un tiempo, podrás ser uno de los que resuelvan los problemas de los demás.

Si intentas investigar el problema tú mismo, también aprenderás mucho más. Por ejemplo, prueba esto:

Alert(iHighest(Symbol(), 0, MODE_HIGH, iBarShift(Symbol(), 0, triggerBarTime, true), 0));

y verás qué valor está devolviendo la función... (como dice Raptor, no es un precio).. y probablemente entenderás más fácilmente la definición de la función.

Cosas como esta te ayudarán más que esperar que alguien en el foro tenga tiempo para probar tu código y hacer la misma resolución de problemas que deberías estar aprendiendo a hacer por ti mismo.

 

¿Eh? Estoy tan confundido - ¿Estoy pidiendo demasiado para un poco de ayuda?

Después de todo, he construido todo mi EA desde el principio (que he enseñado a mí mismo ...) Sólo quería un poco de orientación de alguien que tiene más conocimientos que yo ... :s

 

"Cosas como esta te ayudarán más que esperar que alguien en la junta tenga tiempo para probar tu código y hacer la misma resolución de problemas que deberías aprender a hacer por ti mismo".

Qué demonios... No esperaba eso de nadie.

Tu post ha arrojado más luz sobre la situación - Te lo agradezco.

Este foro es realmente divertido... No estaba planeando descargarme de nadie. Simplemente quería alguna aclaración sobre cómo identificar correctamente la barra que se cruza con las EMA's...

Jeez....

 

cuando leo la respuesta de raptor te está diciendo el problema exacto que has hecho.

los precios se almacenan como variables dobles por ejemplo 1.12345

las funciones iHighest devuelven un entero (int) por ejemplo 1 o 2 o -100 .... claramente no un precio.

No sé lo que estás tratando de lograr, pero la función iHighest probablemente no es la que quieres utilizar.

Lo habrías descubierto por ti mismo si en el metaeditor, haces clic en iHighest en tu código, y luego pulsas F1... verás que devuelve un entero (lo que también te dijo Raptor)

No sé el origen de tu confusión. Si no sabes la diferencia entre las variables int y double te faltan algunos conocimientos básicos vitales, es decir, estás intentando correr antes de saber andar, y quieres que otro te lleve :/

EDIT: ¿No esperabas que tuvieras que hacer tu propia resolución de problemas antes de preguntar a otra persona?

 

Las medias móviles múltiples no se cruzan al mismo tiempo.

¿Por qué estás publicando dos veces? Tu pregunta fue respondida anteriormente.

Encuentre la primera barra en la que todos estaban en el orden correcto.

int DIR = 0;
for(int iBar = 0; iBar < Bar; iBar++){
   double MA20 = ... iBar), 
           MA5 = ... iBar);
          :
   if(     MA20 > MA5 && MA5 > ...) DIR = -1;
   else if(MA20 < MA5 && MA5 < ...) DIR = +1; // All fanning up.
   else if (DIR != 0){ iBar--; break; }       // Last one was cross.
}
 

Entiendo la diferencia entre int y double...

después de que las declaraciones If sean verdaderas, estoy queriendo encontrar la barra que cruzó en el punto donde las MA's están espaciadas. Pensé que si usaba

"triggerBarTime = Time[1];" - después de las declaraciones "If" entonces triggerBarTime podría ser utilizado en conjunto con iBarShift para bloquear la primera barra del rango que me interesa?

Entonces, utilizando el iHighest, me permitiría convertir esta información en un int y utilizarlo en mi función de orden? (Buy_Price)?

 

Puede que entiendas la diferencia entre int y double pero no entiendes la diferencia entre un número de barra (int) y un precio (double).

iHighest le permitiría convertir su fecha en un número de barra (int.) Pero OrderSend sólo toma un precio (un doble) no tiene sentido abrir una orden a 9

 

¡Ah! ¡Tengo a la gente!

Muchas gracias :) ¡Realmente lo aprecio!

Gracias por ser paciente conmigo - no quise decir que esperara que alguien hiciera algo por mí; sólo quería que me aclararan la ayuda (pulsar F1 en todo no siempre es tan claro para mí).

Razón de la queja: