Eu preciso de ajuda com um código - página 4

 
diamstar:
Eu vi d nome de d e a no canto superior direito com um x na frente e não um smiley depois de anexar o e a . Eu inseri o tempo em gmt.


Olá, Diamstar,

Antes de tudo, você precisa entender que o código que você recebe aqui é para fins de aprendizagem.

Isso significa que você testa, modifica ou usa o código da maneira que quiser, por sua própria conta e risco.

De volta ao seu problema, se você não tiver uma cara sorridente, verifique o botão Expert Advisers.

Se estiver vermelho, aperte-o.

Além disso, você pode precisar verificar as configurações no MT4 .

Vá até Ferramentas e selecione Opções (última opção na parte inferior).

Se não for parecido com isto :

faça com que pareça assim.

Deve funcionar agora. Lembre-se, se você quiser parar a EA, basta pressionar o botão Expert Adviser.

Você já realizou algum teste de retorno?

O tempo deve ser em tempo de servidor.

 
Obrigado. Agora eu estou vendo o sorriso. Eu o atualizarei depois de testá-lo esta semana. Mais uma vez, obrigado.
 
diamstar:
Obrigado. Agora eu estou vendo o sorriso. Eu o atualizarei depois de testá-lo esta semana. Mais uma vez, obrigado.


Você sabe como fazer um back test em test de estratégia, visual ou não, e o recurso de otimização?

Ou você está apenas feliz em testar em demonstração? Encontrar as melhores configurações pode ser mais rápido e fácil com o testador de estratégia.

Boa sorte.

 
Estou vendo o sorriso, mas a ordem ainda não está ativada. Verifiquei o diário do testador de estratégia e estou vendo o erro de envio do pedido 130
 
diamstar :
Estou vendo o smiley, mas o pedido ainda não está ativado. Verifiquei o diário do testador de estratégia e estou vendo o erro de envio de pedidos 130


Você pode postar suas configurações e período de tempo do gráfico que você está usando?

Se precisar de esclarecimentos para configurações, é só perguntar, sem problemas.

Aqui está uma versão ligeiramente melhorada, novamente para fins de aprendizado, como de costume.

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

Eu adicionei o parâmetro PeriodForSgnal já que o anterior estava recebendo sinais de apenas 1 minuto, agora você pode configurá-lo para 5, 15, 60 minutos, o que quiser se estiver negociando notícias.

Quando StopLoss=0, ele calculará um stop loss para você. Se SetDistance=0, calculará uma distância para pedidos pendentes .

 
Funcionou!!! Hoje eu sou capaz de fazer alguns testes de retorno, cometi um erro em uma das entradas. Ainda vou experimentar alguns testes em uma conta demo. Obrigado um milhão de vezes.
 
diamstar:
Funcionou!!! Hoje eu sou capaz de fazer alguns testes de retorno, eu cometi um erro em uma das entradas. Ainda vou experimentar alguns testes em uma conta demo. Obrigado um milhão de vezes.


Seja bem-vindo.

Fico feliz por aqui você estar aprendendo.

E você é bem-vindo a perguntar se tiver qualquer outra pergunta.

 
olá, o e a está funcionando bem nos testes de retaguarda, mas não está funcionando na demonstração. Os artigos que vi online estão mostrando algo como o envio do pedido e a modificação do pedido teria de ser enviada de forma diferente. Eu realmente não entendo isto. Obrigado
 
diamstar:
olá, o e a está funcionando bem nos testes posteriores, mas não está funcionando na demonstração. Os artigos que vi online estão mostrando algo como o envio do pedido e a modificação do pedido teria de ser enviada de forma diferente. Eu realmente não entendo isto. Obrigado


Olá, Diamstar,

Fico feliz em saber que você está aprendendo . Agora, você tem certeza de que está falando de demonstração e não de conta ao vivo?

Estou ciente de que alguns corretores não permitem que as EA's façam pedidos com stop loss e tenham lucro em contas ao vivo, então

o trabalho é modificar a EA para enviar os pedidos com zero stop loss e zero take profit e depois usar outra função para modificar

o stop loss e levar o lucro ao valor que você quiser, mas novamente, isto é, para contas ao vivo e não para contas demo.

Se o que você diz acontecer na demonstração, você precisa pressionar o botão Terminal e verificar a guia Especialistas e a guia Diário e ver se você recebe algum erro lá dentro.

Se você receber alguma mensagem de erro, diga-me quais são elas.

É difícil adivinhar em tão pequenos detalhes o que você está tentando fazer e o que dá errado. Informe-me como você o usa, qual é a sua parada, tire proveito, etc.

Estou trabalhando para melhorar esta EA, pois ela mostra potencial para bons resultados com os parâmetros certos e o tempo certo para os pedidos.

Eu o manterei atualizado enquanto você estiver interessado.

 
Obrigado, o livro tem sido uma grande ajuda na compreensão do código. Ele até funcionou perfeitamente em uma demonstração quando mudei os valores de entrada. E, é claro, estou mais do que disposto a aprender.
Razão: