two order send

 
My EA execute two ordersend. If I run EA in Debug mod step to step all is Ok. If I trie to run may EA in normal mode this stop on the second ordersend. If I run it in Debug mode via F5 my EA stop on that second order send. Someone can hel me? tanks. Fabio Crippa
 
Help you with what? There are no mind readers here. We can't see your code. Do you check to see if an order has already been opened?
 

Yes for my code, yes the first order is already opened.

MY code:

 //+------------------------------------------------------------------+

//|                                                   EAStraddle.mq4 |

//|                                                     Fabio Crippa |

//|                                             https://www.mql5.com |

//+------------------------------------------------------------------+

#property copyright "Fabio Crippa"

#property link      "https://www.mql5.com"

#property version   "1.00"

#property strict

//--- input parameters

input string   Cross="EURUSDecn,M1";

input string   data_corrente="2016.10.19 00:30"; // data ed ora di attivazione script

input int      Minuti=3;                        // Durata massima di attivazione dello script

input int      Distanza=50;                      // distanza degli ordini dal prezzo corrente

input int      TakeProfit=50;

input int      StopLoss =50;

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

//---

    double Prots=0.01;                           // Percentage of free margin

   string Symb=Symbol();                        // Symbol

//-------------------------------------------------------------------------- 2 --

int continua=0;   

double Min_Dist=MarketInfo(Symb,MODE_STOPLEVEL);// Min. distance

double Min_Lot=MarketInfo(Symb,MODE_MINLOT);// Min. volume

double Step   =MarketInfo(Symb,MODE_LOTSTEP);//Step to change lots

double Free   =AccountFreeMargin();       // Free Margin

double One_Lot=MarketInfo(Symb,MODE_MARGINREQUIRED);//Costo per 1 lotto

double Lot=1;             //MathFloor(Free*Prots/One_Lot)/2;// Lotti associati al singolo ordine

double prezzo_buy;  // prezzo di apertura ordine Buy

double prezzo_sell;  // prezzo di apertura ordine sell

double SL_buy;     // Stop loss buy

double SL_sell;    // stop loss sell

//double Tp;         // takeprofit modificabile

//double Dis;         // distanza modificabile

double Dis=Distanza;    // distanza dalla quotazione attuale alla quale aprire l'ordine pendente

double TP=TakeProfit;   // take profit da inserire nell'ordine pendente

double SL=StopLoss;     // Stop loss   da inserire nell'ordine pendente

int Ticket_Buy;         // numero ordine Buy assegnato dal server

int Ticket_Sell;        // numero ordine Sell assegnato dal server

int PrimoCiclo=0;       // indicatore primo ciclo questo indicatore è quello che abilita l'esecuzione del ciclo inserimento straddle

int Minuti_Ordini;      // Minuti nei quali sono stati inseriti gli ordini

int Ora_Ordini;         // ora nella quale sono stati inseriti gli ordini

int Minuti_Local;       // Minuti attuali del terminale (PC)

int Ora_Local;          // Ora attuale del terminale (PC)

double Lot_Close;       // Lotto con il quale procedere alla chiusura dell'ordine a mercato

int Minuti_Dep;         // Minuti da confrontare con i minuti locali per decidere sul tempo max di esecuzione dell'EA

double Lot_Buy;         // lotto residuo nell'ordine Buy

double Lot_Sell;        // Lotto residuo nell'ordine Sell

int Ordine_Buy;         // N.Ordine buy

int Ordine_Sell;        // n.ordine sell

int Type_Buy;           // tipo ordine Buy

int Type_Sell;          // tipo ordine sell

int Ticket_Close = 20;  // numero ordine da chiudere 

                        //viene posto a 20 poichè se restasse zero darebbe  errore  

int Type_Close;         // tipo ordine da chiudere

bool Ans;               // valore booleano utilizzato per verificare la conlcusione corretta dell'ordine pendente

int Eop = 0;            // non utilizzato

double TotOrdini;       // numero totale degli ordini in archivio

int Opc = 0;            // Questo indicatore viene posto a 1 dopo che è stato cancellato un primo ordine pendente, in occasione 

                        // del passaggio a mercato dell'ordine opposto

int Ora_Dep = 0;        // Deposito ora non utilizzato

datetime Secondi_prova=0; // numero di secondi dei tempo locale aumentati dei minuti di esercizio dell'EA

bool Fine=false;

//const int reason = 0;


//+-----------------------------------------------------------------

//     INIT -------------------------------------------------------|

//+-----------------------------------------------------------------

int OnInit()  

  {

   Alert("One_lot ", One_Lot);

//---

   return(INIT_SUCCEEDED);

  }

//+-------------------------------------------------------------------

//   Fine INIT  -----------------------------------------------------|

//+-------------------------------------------------------------------

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

//---

   Alert("La funzione Deinit viene eseguta quando chiude la finestra che contiene l'EA"); 

        // allert inserita solo per verificare l'utilizzo della funzione deinit

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void OnTick()

{

 if(PrimoCiclo == 0)    

  {

    Inserisci_straddle();   // ciclo di inserimento dello straddle

    PrimoCiclo=1;

  }  

 Gestione_ordini();      // ciclo di gestione degli ordini dopo che lo straddle è stato inserito

   if (Fine=true)

     { 

     //TerminalClose(reason);

     //break;

     PrimoCiclo = 0;

     Fine = false;

    //OnDeinit(reason);

     return;

     }

 //return;

//+------------------------------------------------------

//Fine OnTick  -----------------------------------------|

//+------------------------------------------------------

//+------------------------------------------------------

// inserisci straddle ----------------------------------|

//+------------------------------------------------------

void Inserisci_straddle()

{

 while(true)   // questo ciclo viene effettuato sino al raggiungimento della data ed ora di attivazione script

  {

    //int YY=TimeYear(TimeLocal());     // anno server

    //int MM=TimeMonth(TimeLocal());    //Mese server

    //int GG=TimeDay(TimeLocal());       // Giorno server

    //int Ora_cor = Hour();

    //double Minuti_cor = Minute();

    //double Ora_Min_cor = Ora_cor + Minuti_cor/100;

    string data_ora=TimeToStr(TimeLocal(),TIME_DATE)+ " " + TimeToStr(TimeLocal(),TIME_MINUTES);

    Alert("data_ora ", data_ora, " data_corrente ", data_corrente);

    if(data_ora >= data_corrente)

      {

       Alert("data corrente", data_ora,"");

       break;

      }

  } 

while(true)   //questo ciclo viene effettuato sino a quando non viene rilevato alcun messaggio di errore

              // ed è quello che inserisce un ordine dello straddle

  {

   if (Lot < Min_Lot)                        // If it is less than allowed

        {

         Alert(" Not enough money for ", Min_Lot," lots");

         Fine = true;

         break;          // Exit cycle si esce dal ciclo perchè non vi sono abbastanza soldi sul conto

        }

//-------------------------------------------------------------------- 4 --

   if (Dis < Min_Dist)                   // If it is less than allowed

        {

         Dis=Min_Dist;                      // Set the allowed

         Alert(" Increased the distance of SL = ",Min_Dist," pt");

        }

   prezzo_buy=Ask + Dis*Point;  // calcolo il prezzo di apertura per l'ordine buy

   prezzo_sell=Bid - Dis*Point;  // calcolo il prezzo di apertura dell'ordine sell  

   SL_buy=Ask - SL*Point; // calcolo stop loss ordine Buy

   SL_sell=Bid + SL*Point; // calcolo stop loss sell 

//-------------------------------------------------------------------- 5 --

   if (TP < Min_Dist)                   // If it is less than allowed

        {

         TP=Min_Dist;                      // Set the allowed

         Alert(" Increased the distance of TP = ",TP," pt");

        }

double TP_buy=prezzo_buy + TP*Point;            // Calcolo takeprofit per ordine buy

double TP_sell=prezzo_sell - TP*Point;  // calcolo takeprofit per ordine sell

//------------------------------------------------------------------ 6 --

Alert("The request was sent to the server. Waiting for reply..");

      Ticket_Buy=OrderSend(Symb, 4, Lot, prezzo_buy, 2, SL_buy, TP_buy); //invio ordine buy al server

      //Ticket_Buy=ticket;

      Alert("OrdineBuy ", Ticket_Buy);

if (Ticket_Buy>0)                             // Got it!:)

        {

         Alert ("Opened order Buy ",Ticket_Buy);

        } 

gest_errore();

if(continua == 1)

 continua = 0;

 continue;

}               

       Alert("The request was sent to the server. Waiting for reply..");

       Alert("Sleep prima");

       Sleep(2000);

       Alert("Seep dopo");

       Ticket_Sell=OrderSend(Symb, 5, Lot, prezzo_sell, 2, SL_sell, TP_sell);

       //Ticket_Sell=OrderSend(Symb, 5, Lot, prezzo_sell, 2, SL_sell, TP_sell); //invio ordine sell al server

       //Ticket_Sell=ticket;

       //Minuti_Ordini = TimeMinute(TimeLocal());

       //Ora_Ordini = TimeHour(TimeLocal());

       Alert("OrdineSell ", Ticket_Sell);

if (Ticket_Sell>0)                             // Got it!:)

        {

         Alert ("Opened order sell ",Ticket_Sell);

         break;

        }

gest_errore(); 

if(continua == 1)

 continua = 0;

 continue;

break;

}


//-----------------------------------------------------

Alert("Lo straddle è stato inserito ---------------------------");

 TotOrdini = OrdersTotal();

 Alert("Totale Ordini ", TotOrdini);

 Secondi_prova = TimeLocal();

 Secondi_prova = Secondi_prova + (Minuti *60);

 Alert("prima di secondi prova ");

//return;

}

//+--------------------------------------------------------------

//  Fine inserisci straddle-------------------------------------|

//+--------------------------------------------------------------

//+--------------------------------------------------------------

//   Gestione ordini--------------------------------------------|

//+--------------------------------------------------------------

void Gestione_ordini()//ciclo gestione ordini, dopo che lo straddle è stato inserito come ordini pendenti,

                      // si controlla  se uno dei due ordini sia passato a mercato

while(TotOrdini>0)   //questo ciclo si esegue sino a quando vi sono ordini caricati.

     

{

      //Alert("prima di secondi prova ");

     // Secondi_prova = TimeLocal();

     // Secondi_prova = Secondi_prova + (Minuti *60);

       

       Alert("secondi prova ", Secondi_prova);

       

      if (OrderSelect(Ticket_Buy, SELECT_BY_TICKET)==true)

        {

         Lot_Buy = OrderLots();

         Type_Buy = OrderType();

        } 

      if (OrderSelect(Ticket_Sell, SELECT_BY_TICKET)== true)

        {

         Lot_Sell = OrderLots();

         Type_Sell = OrderType();

        }

        Alert("time local ", TimeLocal(), " secondi prova ", Secondi_prova); 

      if (TimeLocal() >= Secondi_prova) 

        {  

         Chiudi_Ordini_ALL();

          TotOrdini = OrdersTotal();

          Alert(" Totale Ordini ",TotOrdini, OrdersTotal());

          Fine = true;

          //TerminalClose(reason);

          break;

        }  

      if (Type_Sell == 1)

        {

          Ticket_Close = Ticket_Buy;

        }

      if (Type_Buy == 0)

        {

          Ticket_Close = Ticket_Sell;

        }

      if (Type_Sell == 1 || Type_Buy == 0)

        {

      if (Opc == 0)

        {

            Chiudi_Ordine_Pendente();

            Opc = 1; // questo indicatore a 1 significa che è stato chiuso un ordine pendente

        }

     }

         

       //Alert("in fondo alla gestione ordini, prima del return");

           

//return;   

}

}

//+----------------------------------------------------------------------

//  Fine Gestione_ordini------------------------------------------------|

//+----------------------------------------------------------------------

//+----------------------------------------------------------------------

// chiudi ordine pendente-----------------------------------------------|

//+----------------------------------------------------------------------

void Chiudi_Ordine_Pendente() // ciclo di chiusura ordine pendente

while(true)                                  // Pending Order closing cycle

     {

      //-------------------------------------------------------------------------- 7 --

           Ans=OrderDelete(Ticket_Close);             // Deletion of the order

      //-------------------------------------------------------------------------- 8 --

      if (Ans==true)                            // Got it! :)

        {

         Alert ("Deleted order ", Ticket_Close," ", Type_Close);

         break;                                 // Exit Pending order closing cycle

        }

      //-------------------------------------------------------------------------- 9 --

      int Error=GetLastError();                 // Failed :(

      switch(Error)                             // Overcomable errors

        {

         case  4: Alert("Trade server is busy. Retrying..");

            Sleep(3000);                        // Simple solution

            continue;                           // At the next iteration

         case 137:Alert("Broker is busy. Retrying..");

            Sleep(3000);                        // Simple solution

            continue;                           // At the next iteration

         case 146:Alert("Trading subsystem is busy. Retrying..");

            Sleep(500);                         // Simple solution

            continue;                           // At the next iteration

        }

      switch(Error)                             // Critical errors

        {

         case 2 : Alert("Common error.");

            break;                              // Exit 'switch'

         case 64: Alert("Account is blocked.");

            break;                              // Exit 'switch'

         case 133:Alert("Trading is prohibited");

            break;                              // Exit 'switch'

         case 139:Alert("The order is blocked and is being processed");

            break;                              // Exit 'switch'

         case 145:Alert("Modification is prohibited. ",

                              "The order is too close to the market");

            break;                              // Exit 'switch'

         default: Alert("Occurred error ",Error);//Other alternatives   

        }

      break;                                    // Exit closing cycle

     }


}

//+----------------------------------------------------------------------

// fine chiusura ordine pendente ---------------------------------------|

//+----------------------------------------------------------------------

//+----------------------------------------------------------------------

// chiudi ordini All ---------------------------------------------------|

//+----------------------------------------------------------------------

void Chiudi_Ordini_ALL() // ciclo di chiusura di tutti gli ordini presenti sia nella versione due ordini pendenti

                         // sia nella versione un ordine a mercato

 if (Type_Sell > 1 && Opc == 0) //controllo se è un ordine pendente e se non è stato chiuso uno in precedenza

   {

   Ticket_Close = Ticket_Sell;

   Chiudi_Ordine_Pendente();

   }  

 if (Type_Buy > 1 && Opc == 0)  //controllo se è un ordine pendente e se non è stato chiuso uno in precedenza

   {

   Ticket_Close = Ticket_Buy;

   Chiudi_Ordine_Pendente();

   Eop = 1;

   }   

 if (Type_Sell == 1)            // controllo se è un ordine a mercato

   {

   Lot_Close = Lot_Sell;

   Ticket_Close = Ticket_Sell;

   Eop = 1;

   Chiudi_Ordine_A_Mercato();

   }

 if (Type_Buy == 0)           // controllo se è un ordine a mercato

   {

   Lot_Close = Lot_Buy;

   Ticket_Close = Ticket_Buy;

   Eop = 1;

   Chiudi_Ordine_A_Mercato();

   }

}   

//+-------------------------------------------------------------------

// fine Chiudi ordini All -------------------------------------------|

//+-------------------------------------------------------------------

//+-------------------------------------------------------------------

// Chiudi Ordine a Mercato-------------------------------------------|

//+-------------------------------------------------------------------

void Chiudi_Ordine_A_Mercato() // chiusura ordine a mercato  il ciclo while si esegue sino a quando l'ordine è stato chiuso correttamente

{

   while(true)                                  // Order closing cycle

                                                //il ciclo while si esegue sino a quando l'ordine è stato chiuso correttamente

     {

      

      Alert("Attempt to close ",Ticket_Close," ", Type_Close, " Awaiting response..");

      if (Type_Close == 1)

      {

         Ans=OrderClose(Ticket_Close, Lot_Close, Ask, 0);// Order closing

      }   else

      {

         Ans=OrderClose(Ticket_Close, Lot_Close, Bid, 0);// Order closing

      }

      //-------------------------------------------------------------------------- 8 --

      if (Ans==true)                            // Got it! :)

        {

         Alert ("Closed order ", Ticket_Close, " ", Type_Close);

         break;                                 // Exit closing cycle

        }

      //-------------------------------------------------------------------------- 9 --

      int Error=GetLastError();                 // Failed :(

      switch(Error)                             // Overcomable errors

        {

         case 135:Alert("The price has changed. Retrying..");

            RefreshRates();                     // Update data

            continue;                           // At the next iteration

         case 136:Alert("No prices. Waiting for a new tick..");

            while(RefreshRates()==false)        // To the new tick

               Sleep(1);                        // Cycle sleep

            continue;                           // At the next iteration

         case 146:Alert("Trading subsystem is busy. Retrying..");

            Sleep(500);                         // Simple solution

            RefreshRates();                     // Update data

            continue;                           // At the next iteration

        }

      switch(Error)                             // Critical errors

        {

         case 2 : Alert("Common error.");

            break;                              // Exit 'switch'

         case 5 : Alert("Old version of the client terminal.");

            break;                              // Exit 'switch'

         case 64: Alert("Account is blocked.");

            break;                              // Exit 'switch'

         case 133:Alert("Trading is prohibited");

            break;                              // Exit 'switch'

         default: Alert("Occurred error ",Error);//Other alternatives   

        }

      break;                                    // Exit closing cycle

     }


}

//+-------------------------------------------------------------

// Fine Chiudi Ordine A Mercato -------------------------------|

//+-------------------------------------------------------------

//+-------------------------------------------------------------

// Gestione errore --------------------------------------------|

//+-------------------------------------------------------------

void gest_errore()

{

int Error=GetLastError();                 // Failed 

      switch(Error)                             // Overcomable errors

        {

         case 135:Alert("The price has changed. Retrying..");

            RefreshRates();                     // Update data

            continua=1;                           // At the next iteration

         case 136:Alert("No prices. Waiting for a new tick..");

            while(RefreshRates()==false)        // Up to a new tick

               Sleep(1);                        // Cycle delay

            continua=1;                           // At the next iteration

         case 146:Alert("Trading subsystem is busy. Retrying..");

            Sleep(500);                         // Simple solution

            RefreshRates();                     // Update data

            continua=1;                           // At the next iteration

        }

      switch(Error)                             // Critical errors

        {

         case 2 : Alert("Common error.");

            break;                              // Exit 'switch'

         case 5 : Alert("Outdated version of the client terminal.");

            break;                              // Exit 'switch'

         case 64: Alert("The account is blocked.");

            break;                              // Exit 'switch'

         case 133:Alert("Trading forbidden");

            break;                              // Exit 'switch'

         default: Alert("OCCURRED error ",Error);// Other alternatives   

            break;

        } 

return;

//+----------------------------------------------------------------------

//  fine gestione_errore  ----------------------------------------------|

//+----------------------------------------------------------------------

Tanks. 

 
  1. Don't paste code
    Play video
    Please edit your post.
    For large amounts of code, attach it.

  2. void Inserisci_straddle(){
    
    while(true):  //questo ciclo viene effettuato sino a quando non viene ...
       :
          Ticket_Buy=OrderSend(Symb, 4, Lot, prezzo_buy, 2, SL_buy, TP_buy);
    gest_errore();
           Ticket_Sell=OrderSend(Symb, 5, Lot, prezzo_sell, 2, SL_sell, TP_sell);
    if (Ticket_Sell>0){..}                            // Got it!:)
    gest_errore(); 
    if(continua == 1){ continua = 0; continue; } 
    
    break;
    
    }  //while
    
    If you open a pending buy order, then you try to open a pending sell order. If that requires a retry, you go back, and try to open another buy. You do not check to see if there is already one open.
  3. Do not look for errors (gest_errore,) unless the OrderSend returns a failure (-1) What are Function return values ? How do I use them ? - MQL4 forum and Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles
 

I have midified my Ea  with your advises but my proble is the same. If I run the ea in Debug mode all is ok. If I run ea in normal mode ea seize up at line of second 'ordersend' and I must disconnect Window User and internet connection before to restart my operations.

Tanks for help. 

Reason: