Necesito ayuda con un código - página 4

 
diamstar:
Vi el nombre de d e a en la esquina superior derecha con una x delante de él no un smiley después de adjuntar el e a . Hice la entrada de la hora en gmt.


Hola diamstar,

En primer lugar, debes entender que el código que obtienes aquí es para fines de aprendizaje.

Eso significa que usted prueba, modifica o utiliza el código de la manera que quiera bajo su propio riesgo.

Volviendo a tu problema, si no te aparece una cara sonriente, comprueba el botón de Asesores Expertos.

Si está en rojo, púlsalo.

Además, es posible que tengas que comprobar la configuración en MT4 .

Ve a Herramientas y selecciona Opciones (la última en la parte inferior).

Si no se ve así :

haz que se vea así.

Ahora debería funcionar. Recuerda que si quieres parar el EA, sólo tienes que pulsar el botón de Asesor Experto.

¿Ya has hecho alguna prueba de retroceso?

La hora debe estar en tiempo del servidor.

 
Gracias. Ahora veo el smiley. Lo actualizaré después de probarlo esta semana. Gracias una vez más.
 
diamstar:
Gracias. Ahora veo el smiley. Os pondré al día después de probarlo esta semana. Gracias una vez más.


¿Sabe usted cómo ejecutar una prueba de espalda en el probador de la estrategia, visual o no, y la función de optimización?

¿O simplemente te conformas con probar en la demo? Encontrar la mejor configuración puede ser más rápido y fácil con el probador de estrategias.

Buena suerte

 
Veo el smiley pero la orden sigue sin activarse. He comprobado el diario del probador de la estrategia y estoy viendo error ordersend 130
 
diamstar :
Veo el emoticón pero el pedido aún no está activado. Revisé el diario del probador de estrategias y estoy viendo el error de envío de pedidos 130


¿Puede publicar su configuración y el marco de tiempo del gráfico que está utilizando?

Si necesita aclaraciones para la configuración, solo pregunte, no hay problema.

Aquí hay una versión ligeramente mejorada, nuevamente con fines de aprendizaje, como de costumbre.

 //+------------------------------------------------------------------+
//|                                               News_Trader_v1.mq4 |
//|                                            Copyright © 2013 _3DE |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2013 _3DE"
#property link        "http://www.metaquotes.net"
extern string   Note1       = "Set parameters in Pips not points !" ;
extern string   Note5       = "Set PeriodSignal in minutes!" ;
extern string   Note6       = "1=M1;5=M5;15=M15;30=M30;60=H1;240=H4;1440=D1!" ;
extern int      PeriodForSignal= 15 ;
extern int      TakeProfit  = 25 ; // Take profit pips
extern int      StopLoss    = 0 ; // Stop loss pips (manual trading)
extern string   Note4       = "Leave SetDistance to zero if trading news !" ;
extern int      SetDistance= 10 ; // Distance for BuyStop and SellStop from price at news time
extern string   Note2       = "Set day of the month for the news !" ;
extern string   Note3       = "Set to zero to trade every day at the same time !" ;
extern int      DayOfNews   = 0 ; // Day of the month of news
extern int      NewsHour    = 0 ; // Hour of news
extern int      NewsMin     = 1 ; // Minute of news
extern int      Expiration= 600 ; // Expiration of pending orderes
extern int      BEPips      = 0 ; // Move to break even after BEPips
extern int      TrailingStop= 0 ; // What distance to keep trailing
extern int      Slip        = 5 ; // Slippage
extern int      MagicNumber= 2210 ; // Must be unique for every chart
extern double   Lots= 0.1 ;
extern bool     WriteLog= false ; // Write a log file 
extern string   TradeLog    = "MI_Log" ;
input    string   EaComment   = "NewsTrader_EA" ;

double high_M1,low_M1,openPriceBuyStop,openPriceSellStop,slOpenBuyStop,slSellStop,tpOpenBuyStop,tpSellStop,spread,price;

string filename;
int pointMultiply= 10 ;
double minDist= 0 ;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
   if (SetDistance== 0 )pointMultiply= 10 ;
   else {pointMultiply=SetDistance;}
   if ( Digits == 3 || Digits == 5 )
     {
      pointMultiply  *= 10 ;
      TakeProfit     *= 10 ;
      StopLoss       *= 10 ;
      BEPips         *= 10 ;
      TrailingStop   *= 10 ;
      SetDistance    *= 10 ;
     }
   minDist= MarketInfo ( NULL , MODE_STOPLEVEL )* Point ;
//----
   return ( 0 );
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----

//----
   return ( 0 );
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
   int i;
   int OrdersCondition,minofday,minofnews;

   filename= Symbol ()+TradeLog+ "-" + Month ()+ "-" + Day ()+ ".txt" ;

   if (BEPips> 0 ) DoBE(BEPips);

   if (TrailingStop> 0 ) DoTrail();

   OrdersCondition=CheckOrdersCondition();
   if ( Day ()==DayOfNews || DayOfNews== 0 )
     {
      minofday= Hour ()* 60 + Minute ();
      minofnews=NewsHour* 60 +NewsMin;

       if ((minofday==minofnews- 2 ) || (minofday==minofnews- 1 ))
        {
         high_M1= iHigh ( NULL ,PeriodForSignal, 0 );
         low_M1= iLow ( NULL ,PeriodForSignal, 0 );
         //--- Get the highest high and lowest low for the last 3 bars on 1 minute

         for (i= 1 ;i<= 3 ;i++) if ( iHigh ( NULL ,PeriodForSignal,i)>high_M1) high_M1= iHigh ( NULL ,PeriodForSignal,i);
         for (i= 1 ;i<= 3 ;i++) if ( iLow ( NULL ,PeriodForSignal,i)<low_M1) low_M1= iLow ( NULL ,PeriodForSignal,i);

         spread= Ask - Bid ;
         openPriceBuyStop= NormalizeDouble ((high_M1+spread+(pointMultiply* Point )), Digits );
         slOpenBuyStop= NormalizeDouble (high_M1, Digits );
         tpOpenBuyStop= NormalizeDouble ((openPriceBuyStop+(TakeProfit* Point )+spread), Digits );
         if ((openPriceBuyStop-slOpenBuyStop)<minDist)
           {
            slOpenBuyStop= NormalizeDouble (openPriceBuyStop-minDist-spread, Digits );
           }
         //---
         openPriceSellStop= NormalizeDouble (low_M1-(pointMultiply* Point ), Digits );
         slSellStop= NormalizeDouble (low_M1, Digits );
         tpSellStop= NormalizeDouble ((openPriceSellStop-(TakeProfit* Point )-spread), Digits );
         if ((slSellStop-openPriceSellStop)<minDist)
           {
            slSellStop= NormalizeDouble (openPriceSellStop+minDist+spread, Digits );
           }
         //---
         if (StopLoss> 0 &&SetDistance> 0 )
           {
            price=( Ask + Bid )/ 2 ;
            high_M1=price+(SetDistance* Point );
            low_M1=price-(SetDistance* Point );
            openPriceBuyStop= NormalizeDouble (high_M1+spread, Digits );
            slOpenBuyStop= NormalizeDouble (openPriceBuyStop-(StopLoss* Point ), Digits );
            tpOpenBuyStop= NormalizeDouble (openPriceBuyStop+(TakeProfit* Point ), Digits );

             if ((openPriceBuyStop-slOpenBuyStop)<minDist)
              {
               slOpenBuyStop= NormalizeDouble (openPriceBuyStop-minDist-(StopLoss* Point ), Digits );
               Alert ( "Stop too close ! Check your StopLoss settitngs !!!" );
              }
            openPriceSellStop= NormalizeDouble (low_M1-spread, Digits );
            slSellStop= NormalizeDouble (openPriceSellStop+(StopLoss* Point ), Digits );

             if ((slSellStop-openPriceSellStop)<minDist)
              {
               slSellStop= NormalizeDouble (openPriceSellStop+minDist+(StopLoss* Point ), Digits );
               Alert ( "Stop too close ! Check your StopLoss settitngs !!!" );
              }
            tpSellStop= NormalizeDouble (openPriceSellStop-(TakeProfit* Point ), Digits );
           }
         if (OrdersCondition== 0 )
           {
             if (WriteLog)Write( "Opening BuyStop & SellStop, OrdersCondition=" +OrdersCondition+ " MinOfDay=" +minofday);
            OpenBuyStop();
            OpenSellStop();
           }

         if (OrdersCondition== 10 )
           {
             if (WriteLog)Write( "Opening SellStop, OrdersCondition=" +OrdersCondition+ " MinOfDay=" +minofday);
            OpenSellStop();
           }

         if (OrdersCondition== 1 )
           {
             if (WriteLog)Write( "Opening BuyStop , OrdersCondition=" +OrdersCondition+ " MinOfDay=" +minofday);
            OpenBuyStop();
           }
        }
     }
   if ((minofday>=minofnews) && (minofday<=minofnews+Expiration- 1 ))
     {

       if (OrdersCondition== 1001 )
        {
         if (WriteLog)Write( "Deleting SellStop Because of BuyStop Hit, OrdersCondition=" +OrdersCondition+ " MinOfDay=" +minofday);
         DeleteSellStop();
        }

       if (OrdersCondition== 110 )
        {
         if (WriteLog)Write( "Deleting BuyStop Because of SellStop Hit, OrdersCondition=" +OrdersCondition+ " MinOfDay=" +minofday);
         DeleteBuyStop();
        }
     }

   if (minofday>=minofnews+Expiration)
     {
       if (OrdersCondition== 11 )
        {
         if (WriteLog)Write( "Deleting BuyStop and SellStop Because 5 min expired, OrdersCondition=" +OrdersCondition+ " MinOfDay=" +minofday);
         DeleteBuyStop();
         DeleteSellStop();
        }

       if ((OrdersCondition== 10 ) || (OrdersCondition== 110 ))
        {
         if (WriteLog)Write( "Deleting BuyStop Because 5 min expired, OrdersCondition=" +OrdersCondition+ " MinOfDay=" +minofday);
         DeleteBuyStop();
        }

       if ((OrdersCondition== 1 ) || (OrdersCondition== 1001 ))
        {
         if (WriteLog)Write( "Deleting SellStop Because 5 min expired, OrdersCondition=" +OrdersCondition+ " MinOfDay=" +minofday);
         DeleteSellStop();
        }
     }

//----
   return ( 0 );
  }
//+------------------------------------------------------------------+
//| int CheckOrdersCondition()                                       |
//+------------------------------------------------------------------+

int CheckOrdersCondition()
  {
   int result= 0 ;
   for ( int i= 0 ;i< OrdersTotal ();i++)
     {
       OrderSelect (i, SELECT_BY_POS , MODE_TRADES );
       if (( OrderType ()== OP_BUY ) && ( OrderSymbol ()== Symbol ()) && ( OrderMagicNumber ()==MagicNumber))
        {
         result+= 1000 ;
        }
       if (( OrderType ()== OP_SELL ) && ( OrderSymbol ()== Symbol ()) && ( OrderMagicNumber ()==MagicNumber))
        {
         result+= 100 ;
        }
       if (( OrderType ()== OP_BUYSTOP ) && ( OrderSymbol ()== Symbol ()) && ( OrderMagicNumber ()==MagicNumber))
        {
         result+= 10 ;
        }
       if (( OrderType ()== OP_SELLSTOP ) && ( OrderSymbol ()== Symbol ()) && ( OrderMagicNumber ()==MagicNumber))
        {
         result+= 1 ;
        }

     }
   return (result); // 0 means we have no trades
  }
// OrdersCondition Result Pattern
//    1    1    1    1
//    b    s    bs   ss
//  
//+------------------------------------------------------------------+
//|void OpenBuyStop()                                                |
//+------------------------------------------------------------------+

void OpenBuyStop()
  {
   int ticket,tries;
   tries= 0 ;
   if (! GlobalVariableCheck ( "InTrade" ))
     {
       while (tries< 3 )
        {
         GlobalVariableSet ( "InTrade" , TimeCurrent ());   // set lock indicator
         ticket= OrderSend ( Symbol (), OP_BUYSTOP ,Lots,openPriceBuyStop,Slip,slOpenBuyStop,tpOpenBuyStop,EaComment,MagicNumber, 0 ,Red);
         if (WriteLog)Write( "in function OpenBuyStop OrderSend Executed , ticket =" +ticket);
         GlobalVariableDel ( "InTrade" );   // clear lock indicator
         if (ticket<= 0 )
           {
            tries++;
           }
         else tries= 3 ;
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OpenSellStop()
  {
   int ticket,tries;
   tries= 0 ;
   if (! GlobalVariableCheck ( "InTrade" ))
     {
       while (tries< 3 )
        {
         GlobalVariableSet ( "InTrade" , TimeCurrent ());   // set lock indicator
         ticket= OrderSend ( Symbol (), OP_SELLSTOP ,Lots,openPriceSellStop,Slip,slSellStop,tpSellStop,EaComment,MagicNumber, 0 ,Red);
         if (WriteLog)Write( "in function OpenSellStop OrderSend Executed , ticket =" +ticket);
         GlobalVariableDel ( "InTrade" );   // clear lock indicator
         if (ticket<= 0 )
           {
            tries++;
           }
         else tries= 3 ;
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DoBE( int byPips)
  {
   for ( int i= 0 ; i< OrdersTotal (); i++)
     {
       OrderSelect (i, SELECT_BY_POS , MODE_TRADES );
       if ( OrderSymbol ()== Symbol () && ( OrderMagicNumber ()==MagicNumber)) // only look if mygrid and symbol...
        {
         if ( OrderType ()== OP_BUY ) if ( Bid - OrderOpenPrice ()>byPips* Point ) if ( OrderStopLoss ()< OrderOpenPrice ())
           {
             if (WriteLog)Write( "Movine StopLoss of Buy Order to BE+1" );
             OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice ()+ Point , OrderTakeProfit (),Red);
           }
         if ( OrderType ()== OP_SELL ) if ( OrderOpenPrice ()- Ask >byPips* Point ) if ( OrderStopLoss ()> OrderOpenPrice ())
           {
             if (WriteLog)Write( "Movine StopLoss of Buy Order to BE+1" );
             OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice ()- Point , OrderTakeProfit (),Red);
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DoTrail()
  {
   for ( int i= 0 ; i< OrdersTotal (); i++)
     {
       OrderSelect (i, SELECT_BY_POS , MODE_TRADES );
       if ( OrderSymbol ()== Symbol () && ( OrderMagicNumber ()==MagicNumber)) // only look if mygrid and symbol...
        {

         if ( OrderType ()== OP_BUY )
           {
             if ( Bid - OrderOpenPrice ()> Point *TrailingStop)
              {
               if ( OrderStopLoss ()< Bid - Point *TrailingStop)
                 {
                   OrderModify ( OrderTicket (), OrderOpenPrice (), Bid - Point *TrailingStop, OrderTakeProfit (), 0 ,Green);
                   return ;
                 }
              }
           }

         if ( OrderType ()== OP_SELL )
           {
             if (( OrderOpenPrice ()- Ask )>( Point *TrailingStop))
              {
               if (( OrderStopLoss ()>( Ask + Point *TrailingStop)) || ( OrderStopLoss ()== 0 ))
                 {
                   OrderModify ( OrderTicket (), OrderOpenPrice (), Ask + Point *TrailingStop, OrderTakeProfit (), 0 ,Red);
                   return ;
                 }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DeleteBuyStop()
  {
   for ( int i= 0 ; i< OrdersTotal (); i++)
     {
       OrderSelect (i, SELECT_BY_POS , MODE_TRADES );
       if ( OrderSymbol ()== Symbol () && ( OrderMagicNumber ()==MagicNumber) && ( OrderType ()== OP_BUYSTOP ))
        {
         OrderDelete ( OrderTicket ());
         if (WriteLog)Write( "in function DeleteBuyStopOrderDelete Executed" );
        }

     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DeleteSellStop()
  {
   for ( int i= 0 ; i< OrdersTotal (); i++)
     {
       OrderSelect (i, SELECT_BY_POS , MODE_TRADES );
       if ( OrderSymbol ()== Symbol () && ( OrderMagicNumber ()==MagicNumber) && ( OrderType ()== OP_SELLSTOP ))
        {
         OrderDelete ( OrderTicket ());
         if (WriteLog)Write( "in function DeleteSellStopOrderDelete Executed" );
        }

     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Write( string str)
  {
   int handle;

   handle= FileOpen (filename, FILE_READ | FILE_WRITE | FILE_CSV , "/t" );
   FileSeek (handle, 0 , SEEK_END );
   FileWrite(handle,str+ " Time " + TimeToStr ( CurTime (), TIME_DATE | TIME_SECONDS ));
   FileClose (handle);
  }
//+------------------------------------------------------------------+

Agregué el parámetro PeriodForSgnal ya que el anterior estaba tomando señales solo de un marco de tiempo de 1 minuto, ahora puede configurarlo en 5, 15, 60 minutos, lo que quiera si intercambia noticias.

Cuando StopLoss=0 calculará un stop loss para usted. Si SetDistance=0, calculará una distancia para pedidos pendientes .

 
¡¡¡Ha funcionado!!! Hoy he podido hacer algunas pruebas de espalda, me he equivocado en una de las entradas. Igual voy a hacer algunas pruebas en una cuenta demo. Gracias un millón de veces.
 
diamstar:
¡¡¡Funcionó!!! Hoy he podido hacer algunas pruebas de espalda, me he equivocado en una de las entradas. Igual voy a hacer algunas pruebas en una cuenta demo. Gracias un millón de veces.


De nada.

Me alegro de que estés aprendiendo.

Y eres bienvenido a preguntar si tienes alguna otra duda.

 
hola el e a funciona bien en backtesting pero no funciona en demo. Los artículos que he visto en Internet muestran algo así como que la orden de envío y la orden de modificación deben enviarse de forma diferente. No entiendo muy bien esto. Gracias
 
diamstar:
hola el e a esta funcionando bien en back testing pero no funciona en demo. Los artículos que he visto en Internet muestran algo así como que el envío de la orden y la modificación de la orden tendrían que ser enviados de manera diferente. No entiendo muy bien esto. Gracias


Hola diamstar,

Me alegra saber que estás aprendiendo. Ahora, ¿estás seguro de que estás hablando de demo y no cuenta real?

Soy consciente de que algunos brokers no permiten que los EAs coloquen órdenes con stop loss y take profit en las cuentas reales por lo que

el trabajo alrededor es para modificar la EA para enviar las órdenes con cero stop loss y cero tomar ganancias y luego utilizar otra función para modificar

el stop loss y el take profit a cualquier valor que desee, pero de nuevo, que es para las cuentas reales no demo.

Si lo que dices ocurre en demo, tienes que pulsar el botón de Terminal y comprobar la pestaña de Expertos y la pestaña de Diario y ver si te sale algún error ahí.

Si te sale algún mensaje de error, hazme saber cuál es.

Es difícil adivinar con tan pocos detalles lo que se intenta hacer y lo que sale mal. Hazme saber cómo lo usas, cuál es tu stop, take profit, etc.

Estoy trabajando en mejorar este EA ya que muestra potencial para obtener buenos resultados con los parámetros adecuados y el tiempo correcto para las órdenes.

Os mantendré informados mientras estéis interesados.

 
Gracias, el libro ha sido de gran ayuda para entender el código. Incluso ha funcionado perfectamente en una demo cuando he cambiado los valores de entrada. Y por supuesto estoy más que dispuesto a aprender.