EA com ordem buy stop

Para adicionar comentários, por favor Faça o login ou registrar
jrds03
16
jrds03  

Oi, Estou com dificuldade para enviar ordens buy stop ou sell stop. Montei um EA somente para buy stop mas não estou conseguindo comprar no preço desejado.

Copiei o código de um artigo e fui melhorando conforme as recomendações nos fóruns mas não consegui fazer rodar. 

Segue abaixo meu código:

//+------------------------------------------------------------------+
//|                                                  My_First_EA.mq5 |
//|                        Copyright 2010, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2010, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"

#include <trade/trade.mqh>

//--- input parameters
input int      StopLoss=500;      // Stop Loss
input int      TakeProfit=500;   // Take Profit
input int      EA_Magic=12345;   // EA Magic Number
input double   Lot=5;          // Lots to Trade
//--- Other parameters
int maxima;
int minima;
int gainCompra;
double max[],min[],gain[];
double p_high;
int STP, TKP;  
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   maxima=iCustom(Symbol(),0,"maximaPrimBarra");
   minima=iCustom(Symbol(),0,"minimaPrimBarra");
   gainCompra=iCustom(Symbol(),0,"gainPrimBarra");
//--- What if handle returns Invalid Handle
   if(maxima<0 || minima<0 || gainCompra<0)
     {
      Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!!");
      return(-1);
     }
  
//--- Let us handle currency pairs with 5 or 3 digit prices instead of 4
   STP = StopLoss;
   TKP = TakeProfit;
   if(_Digits==5 || _Digits==3)
     {
      STP = STP*10;
      TKP = TKP*10;
     }
   return(0);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- Release our indicator handles
   IndicatorRelease(maxima);
   IndicatorRelease(minima);
   IndicatorRelease(gainCompra);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- Do we have enough bars to work with
   if(Bars(_Symbol,_Period)<60) // if total bars is less than 60 bars
     {
      Alert("We have less than 60 bars, EA will now exit!!");
      return;
     }

   static datetime Old_Time;
   datetime New_Time[1];
   bool IsNewBar=false;

// copying the last bar time to the element New_Time[0]
   int copied=CopyTime(_Symbol,_Period,0,1,New_Time);
   if(copied>0) // ok, the data has been copied successfully
     {
      if(Old_Time!=New_Time[0]) // if old time isn't equal to new bar time
        {
         IsNewBar=true;   // if it isn't a first call, the new bar has appeared
         if(MQL5InfoInteger(MQL5_DEBUGGING)) Print("We have new bar here ",New_Time[0]," old time was ",Old_Time);
         Old_Time=New_Time[0];            // saving bar time
        }
     }
   else
     {
      Alert("Error in copying historical times data, error =",GetLastError());
      ResetLastError();
      return;
     }

//--- EA should only check for new trade if we have a new bar
   if(IsNewBar==false)
     {
      return;
     }

//--- Do we have enough bars to work with
   int Mybars=Bars(_Symbol,_Period);
   if(Mybars<60) // if total bars is less than 60 bars
     {
      Alert("We have less than 60 bars, EA will now exit!!");
      return;
     }

//--- Define some MQL5 Structures we will use for our trade
   MqlTick latest_price;      // To be used for getting recent/latest price quotes
   MqlTradeRequest mrequest;  // To be used for sending our trade requests
   MqlTradeResult mresult;    // To be used to get our trade results
   MqlRates mrate[];          // To be used to store the prices, volumes and spread of each bar
   ZeroMemory(mrequest);      // Initialization of mrequest structure
/*
     Let's make sure our arrays values
     is store serially similar to the timeseries array
*/

// the rates arrays
   ArraySetAsSeries(mrate,true);
   ArraySetAsSeries(max,true);
   ArraySetAsSeries(min,true);
   ArraySetAsSeries(gain,true);
//--- Get the last price quote using the MQL5 MqlTick Structure
   if(!SymbolInfoTick(_Symbol,latest_price))
     {
      Alert("Error getting the latest price quote - error:",GetLastError(),"!!");
      return;
     }

//--- Get the details of the latest 3 bars
   if(CopyRates(_Symbol,_Period,0,3,mrate)<0)
     {
      Alert("Error copying rates/history data - error:",GetLastError(),"!!");
      ResetLastError();
      return;
     }

//--- Copy the new values of our indicators to buffers (arrays) using the handle
   if(CopyBuffer(maxima,0,0,3,max)<0 || CopyBuffer(minima,0,0,3,min)<0
      || CopyBuffer(gainCompra,0,0,3,gain)<0)
     {
      Alert("Error copying indicator Buffers - error:",GetLastError(),"!!");
      ResetLastError();
      return;
     }
//--- we have no errors, so continue
//--- Do we have positions opened already?
   bool Buy_opened=false;  // variable to hold the result of Buy opened position
   bool Sell_opened=false; // variables to hold the result of Sell opened position

   if(PositionSelect(_Symbol)==true) // we have an opened position
     {
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
        {
         Buy_opened=true;  //It is a Buy
        }
      else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
        {
         Sell_opened=true; // It is a Sell
        }
     }

// Copy the bar high price for the previous bar prior to the current bar, that is Bar 1
   p_high=mrate[1].high;  // bar 1 high price

//--- Declare bool type variables to hold our Buy Conditions
   bool Buy_Condition_1=(latest_price.last>=max[0] && gain[0]!=0); // MA-8 Increasing upwards
   MqlDateTime tstruct;
   TimeToStruct(latest_price.time,tstruct);
   datetime hourBuffer[1];
   hourBuffer[0]=tstruct.hour;
    
   if(Buy_opened)
        {
         if(hourBuffer[0]>=1750)
            {
            CTrade trade;
            int i=PositionsTotal()-1;
            trade.PositionClose(PositionGetSymbol(i));
            }
         }
//--- Putting all together  
   //if(Buy_Condition_1 && hourBuffer[0]<1750)
   if(max[0]!=max[1] && hourBuffer[0]<1750)
     {
      // any opened Buy position?
      if(Buy_opened)
        {
         Alert("We already have a Buy Position!!!");
         return;    // Don't open a new Buy Position
        }
            int digits = SymbolInfoInteger(_Symbol,SYMBOL_DIGITS);
            ZeroMemory(mrequest);
            mrequest.action = TRADE_ACTION_PENDING;                                  
            mrequest.symbol = _Symbol;                                            
            mrequest.volume = 5;                                                  
            //mrequest.magic = EA_Magic;                                          
            mrequest.type = ORDER_TYPE_BUY_STOP;                                  
            mrequest.deviation = 10;
            mrequest.price = NormalizeDouble(max[1],digits);
            //mrequest.stoplimit = NormalizeDouble(max[1],digits);
            mrequest.type_time = ORDER_TIME_DAY;
            mrequest.sl = NormalizeDouble(min[1],digits);                        
            mrequest.tp = NormalizeDouble(gain[0],digits);                      
            mrequest.type_filling = ORDER_FILLING_FOK;                          
            //--- send order
            ZeroMemory(mresult);
            OrderSend(mrequest,mresult);
            // get the result code
            //}
            if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
               {
               Alert("A Buy order has been successfully placed with Ticket#:",mresult.order,"!!");
               }
            else
               {
               Alert("The Buy order request could not be completed -error:",GetLastError());
               ResetLastError();
               PrintFormat("retcode=%u  deal=%I64u  order=%I64u",mresult.retcode,mresult.deal,mresult.order);
               Alert(SymbolInfoInteger(_Symbol,SYMBOL_TRADE_MODE));
               return;
               }
         }
    
/*
    2. Check for a Short/Sell Setup : MA-8 decreasing downwards,
    previous price close below it, ADX > 22, -DI > +DI

//--- Declare bool type variables to hold our Sell Conditions
   bool Sell_Condition_1 = (maVal[0]<maVal[1]) && (maVal[1]<maVal[2]);  // MA-8 decreasing downwards
   bool Sell_Condition_2 = (p_close <maVal[1]);                         // Previous price closed below MA-8
   bool Sell_Condition_3 = (adxVal[0]>Adx_Min);                         // Current ADX value greater than minimum (22)
   bool Sell_Condition_4 = (plsDI[0]<minDI[0]);                         // -DI greater than +DI

//--- Putting all together
   if(Sell_Condition_1 && Sell_Condition_2)
     {
      if(Sell_Condition_3 && Sell_Condition_4)
        {
         // any opened Sell position?
         if(Sell_opened)
           {
            Alert("We already have a Sell position!!!");
            return;    // Don't open a new Sell Position
           }
         ZeroMemory(mrequest);
         ZeroMemory(mresult);
         mrequest.action=TRADE_ACTION_DEAL;                                // immediate order execution
         mrequest.price = NormalizeDouble(latest_price.bid,_Digits);           // latest Bid price
         mrequest.sl = NormalizeDouble(latest_price.bid + STP*_Point,_Digits); // Stop Loss
         mrequest.tp = NormalizeDouble(latest_price.bid - TKP*_Point,_Digits); // Take Profit
         mrequest.symbol = _Symbol;                                          // currency pair
         mrequest.volume = Lot;                                              // number of lots to trade
         mrequest.magic = EA_Magic;                                          // Order Magic Number
         mrequest.type= ORDER_TYPE_SELL;                                     // Sell Order
         mrequest.type_filling = ORDER_FILLING_FOK;                          // Order execution type
         mrequest.deviation=100;                                             // Deviation from current price
         //--- send order
         OrderSend(mrequest,mresult);
         // get the result code
         if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
           {
            Alert("A Sell order has been successfully placed with Ticket#:",mresult.order,"!!");
           }
         else
           {
            Alert("The Sell order request could not be completed -error:",GetLastError());
            ResetLastError();
            return;
           }
        }
     }
   return;*/

  }
Negociação Automatizada e Análise de Estratégia
Negociação Automatizada e Análise de Estratégia
  • www.mql5.com
MQL5: linguagem de estratégias de negociação inseridas no Terminal do Cliente MetaTrader 5. A linguagem permite escrever seus próprios sistemas automáticos de negócios, indicadores técnicos, scripts e bibliotecas de funções
Rodrigo Malacarne
Moderador
8089
Rodrigo Malacarne  
jrds03:

Oi, Estou com dificuldade para enviar ordens buy stop ou sell stop. Montei um EA somente para buy stop mas não estou conseguindo comprar no preço desejado.

Copiei o código de um artigo e fui melhorando conforme as recomendações nos fóruns mas não consegui fazer rodar. 

Segue abaixo meu código:

Olá jrds03,

Sempre que postar partes de código aqui no fórum MQL5.com, por favor utilize o botão SRC na parte superior do editor.

Caso você faça isso, o teu código postado ficará automaticamente postado com o formato correto, o que facilita o entendimento por parte de outros usuários.

Abraços,
Malacarne 

jrds03
16
jrds03  
Rodrigo Malacarne:

Olá jrds03,

Sempre que postar partes de código aqui no fórum MQL5.com, por favor utilize o botão SRC na parte superior do editor.

Caso você faça isso, o teu código postado ficará automaticamente postado com o formato correto, o que facilita o entendimento por parte de outros usuários.

Abraços,
Malacarne 

Bom dia Rodrigo,

Fiz um novo post conforme suas recomendações, mas o código não apareceu no mesmo.

Preciso muito de sua ajuda, será que tem como fazer funcionar este meu código? Não consigo encontrar o erro...

Abração

José Ricardo 

jrds03
16
jrds03  
Já fiz todas as combinações possíveis de entrada para mrequest e ainda assim não funcionou...
Dimi
5
Dimi  

jrds03, você já conseguiu resolver o problema? Se não, qual a mensagem exibida na guia Experts da caixa de ferramentas, quando seu EA executa uma operação?

Para adicionar comentários, por favor Faça o login ou registrar