why my ea close orders immediately after it opened orders?

 

It's my first mt5 ea. why my ea close orders  immediately after  it opened orders?

#property copyright ""
#property link      ""
#property version   "1.00"
//--- input parameters
input ENUM_TIMEFRAMES   TrendTimeFrame=PERIOD_H4;
input ENUM_TIMEFRAMES  TradeTimeFrame=PERIOD_H1;

input int TrendTimeFrameEMAPeriodSmall = 15;
input int TrendTimeFrameEMAPeriodBig = 60;

input int TradeTimeFrameEMASmallPeriod = 60;
input int TradeTimeFrameEMABigPeriod = 120;

input bool useBlauErgodicOscillator = false;
input bool useBlauStochasticMomentum = false;
input bool useBlauErgodicCSIOscillator = false;
input bool useBlauErgodicMACDoscillator = false;
input double Lot = 0.1;
input int    EA_Magic=12345; 
input int      StopLoss=30;      // Stop Loss
input int      TakeProfit=100;   // Take Profit
int STP, TKP; 

int trend_EMA_small_Handle;
int trend_EMA_big_Handle;
int trade_EMA_small_Handle;
int trade_EMA_big_Handle;
int Blau_Ergodic_handle;
int Blau_SMI_handle;
int Blau_Ergodic_CSI_handle;
int Blau_Ergodic_MACD_handle;

int bar_count = 4;

double trend_EMA_small_buffer[]; 
double trend_EMA_big_buffer[]; 

double trade_EMA_small_buffer[]; 
double trade_EMA_big_buffer[]; 

double histogram_Blau_Ergodic_buffer[];
double histogram_Blau_SMI_buffer[];
double histogram_Blau_Ergodic_CSI_buffer[];
double histogram_Blau_Ergodic_MACD_buffer[];

double signal_Blau_Ergodic_buffer[];
double signal_Blau_SMI_buffer[];
double signal_Blau_Ergodic_CSI_buffer[];
double signal_Blau_Ergodic_MACD_buffer[];

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
    trend_EMA_small_Handle=iMA(_Symbol,TrendTimeFrame,TrendTimeFrameEMAPeriodSmall,0,MODE_EMA,PRICE_CLOSE);
    trend_EMA_big_Handle=iMA(_Symbol,TrendTimeFrame,TrendTimeFrameEMAPeriodBig,0,MODE_EMA,PRICE_CLOSE);
    
    trade_EMA_small_Handle=iMA(_Symbol,TradeTimeFrame,TradeTimeFrameEMASmallPeriod,0,MODE_EMA,PRICE_CLOSE);
    trade_EMA_big_Handle=iMA(_Symbol,TradeTimeFrame,TradeTimeFrameEMABigPeriod,0,MODE_EMA,PRICE_CLOSE);
    
    Blau_Ergodic_handle=iCustom(NULL,PERIOD_CURRENT,"Blau_Ergodic");
    Blau_SMI_handle=iCustom(NULL,PERIOD_CURRENT,"Blau_SMI");
    Blau_Ergodic_CSI_handle=iCustom(NULL,PERIOD_CURRENT,"Blau_Ergodic_CSI");
    Blau_Ergodic_MACD_handle=iCustom(NULL,PERIOD_CURRENT,"Blau_Ergodic_MACD");
    
    if(trend_EMA_small_Handle<0 
         || trend_EMA_big_Handle<0
         || Blau_Ergodic_handle < 0
         || Blau_SMI_handle < 0
         || Blau_Ergodic_CSI_handle < 0
         || Blau_Ergodic_MACD_handle < 0
         )
      {
      Print("handle=",INVALID_HANDLE);
      Print("Runtime error = ",GetLastError());
      //--- forced program termination
      //return(-1);
      }
      
   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)
  {
     IndicatorRelease(Blau_Ergodic_handle);
     IndicatorRelease(Blau_SMI_handle);
     IndicatorRelease(Blau_Ergodic_CSI_handle);
     IndicatorRelease(Blau_Ergodic_MACD_handle);
     IndicatorRelease(trend_EMA_small_Handle);
     IndicatorRelease(trend_EMA_big_Handle);
   
  }

void OnTick()
  {   
 /* 
  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;
     }*/
     
    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
    ArraySetAsSeries(mrate,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,bar_count,mrate)<0)
     {
      Alert("Error copying rates/history data - error:",GetLastError(),"!!");
      ResetLastError();
      return;
     }
         
    //int copy = CopyBuffer(trend_EMA_small_Handle,0,0,bar_count,trend_EMA_small_buffer);
    if(CopyBuffer(trend_EMA_small_Handle,0,0,bar_count,trend_EMA_small_buffer)<=0
      || CopyBuffer(trend_EMA_big_Handle,0,0,bar_count,trend_EMA_big_buffer)<=0      
      || CopyBuffer(trade_EMA_big_Handle,0,0,bar_count,trade_EMA_big_buffer)<=0 
      || CopyBuffer(trade_EMA_small_Handle,0,0,bar_count,trade_EMA_small_buffer)<=0 
      || CopyBuffer(Blau_Ergodic_handle,0,0,bar_count,histogram_Blau_Ergodic_buffer)<=0 
      || CopyBuffer(Blau_SMI_handle,0,0,bar_count,histogram_Blau_SMI_buffer)<=0 
      || CopyBuffer(Blau_Ergodic_CSI_handle,0,0,bar_count,histogram_Blau_Ergodic_CSI_buffer)<=0 
      || CopyBuffer(Blau_Ergodic_MACD_handle,0,0,bar_count,histogram_Blau_Ergodic_MACD_buffer)<=0 
      
      || CopyBuffer(Blau_Ergodic_handle,1,0,bar_count,signal_Blau_Ergodic_buffer)<=0 
      || CopyBuffer(Blau_Ergodic_CSI_handle,1,0,bar_count,signal_Blau_Ergodic_CSI_buffer)<=0 
      || CopyBuffer(Blau_Ergodic_MACD_handle,1,0,bar_count,signal_Blau_Ergodic_MACD_buffer)<=0       
      ) 
    {
      Print("CopyBuffer error: " + GetLastError());
      return;
    } 
        
   //--- set indexation of array MA[] as timeseries
   ArraySetAsSeries(trend_EMA_small_buffer,true);
   ArraySetAsSeries(trend_EMA_big_buffer,true);
   ArraySetAsSeries(trade_EMA_big_buffer,true);
   ArraySetAsSeries(trade_EMA_small_buffer,true);
   ArraySetAsSeries(histogram_Blau_Ergodic_buffer,true);
   ArraySetAsSeries(histogram_Blau_SMI_buffer,true);
   ArraySetAsSeries(histogram_Blau_Ergodic_CSI_buffer,true);
   ArraySetAsSeries(histogram_Blau_Ergodic_MACD_buffer,true);
   ArraySetAsSeries(signal_Blau_Ergodic_buffer,true);
   ArraySetAsSeries(signal_Blau_Ergodic_CSI_buffer,true);
   ArraySetAsSeries(signal_Blau_Ergodic_MACD_buffer,true);   
   
   //Print("signal_Blau_Ergodic_MACD_buffer " + signal_Blau_Ergodic_MACD_buffer[3]);
   //Print("signal_Blau_Ergodic_CSI_buffer " + signal_Blau_Ergodic_CSI_buffer[3]);
   //Print("signal_Blau_Ergodic_buffer " + signal_Blau_Ergodic_buffer[3]);
   //Print("histogram_Blau_Ergodic_MACD_buffer " + histogram_Blau_Ergodic_MACD_buffer[3]);
   //Print("histogram_Blau_Ergodic_CSI_buffer " + histogram_Blau_Ergodic_CSI_buffer[2]);
   //Print("histogram_Blau_SMI_buffer " + histogram_Blau_SMI_buffer[3]);
   //Print("histogram_Blau_Ergodic_buffer " + histogram_Blau_Ergodic_buffer[3]);
  //Print("trade_EMA_small_buffer " + trade_EMA_small_buffer[1]);   
   //Print("trade_EMA_big_buffer " + trade_EMA_big_buffer[1]);
   
   //double trend_EMA_small = trend_EMA_small_buffer[1];
   //Print("trend_EMA_small " + trend_EMA_small);
   //Print("trend_EMA_big " + trend_EMA_big_buffer[1]);
   //double trend_EMA_big = trend_EMA_big_buffer[1];      


   bool Buy_opened=false; 
   bool Sell_opened=false;

   if(PositionSelect(_Symbol)==true) // we have an opened position
     {
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
        {
         Buy_opened=true;  
        }
      else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
        {
         Sell_opened=true; 
        }
     }
    
  //dfsdfsfsfs
  
   if (Buy_opened) 
         {
            Alert("We already have a Buy Position!!!"); 
            return;    // Don't open a new Buy Position
         }
         
     if (Buy_opened==false)
     {
            ZeroMemory(mrequest);
            mrequest.action = TRADE_ACTION_DEAL;                                  // immediate order execution
            mrequest.price = NormalizeDouble(latest_price.ask,_Digits);           // latest ask price
            mrequest.sl = NormalizeDouble(latest_price.ask - STP*_Point,_Digits); // Stop Loss
            mrequest.tp = NormalizeDouble(latest_price.ask + 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_BUY;                                        // Buy 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 Buy order has been successfully placed with Ticket#:",mresult.order,"!!");
              }
            else
              {
               Alert("The Buy order request could not be completed -error:",GetLastError());
               ResetLastError();           
               return;
              }           
       }    
       
       
       if(Sell_opened==false)
       {
         ZeroMemory(mrequest);
         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;
   }    
//+------------------------------------------------------------------+
 

Let me guess, this EA open a buy first, when this buy gets opened, it immediately get closed, right ?.

Same thing like this, and do this please, open MT5, manually buy - say 1 lot EURUSD, when this EURUSD buy is opened, then manually sell another 1 lot EURUSD. There will be no opened order - no trades. :D

MT5 does not allow hedging, when you buy 1 lot EURUSD and then sell 1 lot EURUSD, you actually just sell what you just buy and vice versa. Do this, buy 1 lot EURUSD and then sell 2 lots EURUSD, you will have an open of 1 lot sell EURUSD.

Have fun, with hedging ;) 

:D 

Reason: