Orders being deleted after orders opened.

 

Okay so I have created my first expert advisor and whenever my order is being send it gets deleted automatically. Like in this screenshot I provided. 

Okay so this is the expert advisor. I'll also include the file of the CustomFunctions01.mqh

//+------------------------------------------------------------------+
//|                                                 New Strategy.mq4 |
//|                                   Copyright 2020, Wout Verheesen |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, Wout Verheesen"
#property link      ""
#property version   "1.00"
#property strict
#property show_inputs
#include  <CustomFunctions01.mqh>

int magicNB = 55555;
int stochasticLowerLevel = 20;
int stochasticUpperLevel = 80;
double riskPerTrade = 0.02;
int openOrderID;

int bandStdEntry = 2;
int bbPeriod = 20;

//+------------------------------------------------------------------+
int OnInit()
  {
   Alert("");
   Alert("Starting New Test Strategy");

   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   Alert("Stopping New Test Strategy");
  }
//+------------------------------------------------------------------+

void OnTick()
  {
  
   double stochastic = iStochastic(NULL, PERIOD_M5, 5, 3, 3, MODE_SMMA, 0, 0, 0);
   double stochasticValue = iStochastic(NULL, PERIOD_M5, 5, 3, 3, MODE_SMMA, 0, 0, 0);
   double bbUpperBand = iBands(NULL, PERIOD_M5, bbPeriod, bandStdEntry, 0, PRICE_CLOSE, MODE_UPPER, 0);
   double bbLowerBand = iBands(NULL, PERIOD_M5, bbPeriod, bandStdEntry, 0, PRICE_CLOSE, MODE_LOWER, 0); 
   double bbMidBand = iBands(NULL, PERIOD_M5, bbPeriod, bandStdEntry, 0, PRICE_CLOSE, 0, 0); 

   
   if(!CheckIfOpenOrdersByMagicNB(magicNB))//if no open orders try to enter new position
   {
      if(Ask < bbLowerBand && Open[0] > bbLowerBand && stochasticValue < stochasticLowerLevel)//buying
      {
         Print("Price is below bbLowerBand and iStochastic is lower than " + stochasticLowerLevel+ " , Sending buy order");
         double stopLossPrice = Ask - 0.0002;
         double takeProfitPrice = Ask + 0.0001;
         Print("Entry Price = " + Ask);
         Print("Stop Loss Price = 20 pips");
         Print("Take Profit Price = 10 pips");
         
         double lotSize = OptimalLotSize(riskPerTrade,Ask,stopLossPrice);
         
         openOrderID = OrderSend(NULL,OP_BUYLIMIT,lotSize,Ask,10,stopLossPrice,takeProfitPrice,NULL,magicNB); 
         if(openOrderID < 0) Alert("order rejected. Order error: " + GetLastError());
      }
      else if(Bid > bbUpperBand && Open[0] < bbUpperBand && stochasticValue > stochasticUpperLevel)//shorting
      {
         Print("Price is above bbUpperBand and iStochastic is above " + stochasticUpperLevel + " Sending short order");
         double stopLossPrice = Ask + 0.0002;
         double takeProfitPrice = Ask - 0.0001;
         Print("Entry Price = " + Bid);
         Print("Stop Loss Price = 20 pips");
         Print("Take Profit Price = 10 pips");
          
          double lotSize = OptimalLotSize(riskPerTrade,Bid,stopLossPrice);

          openOrderID = OrderSend(NULL,OP_SELLLIMIT,lotSize,Bid,10,stopLossPrice,takeProfitPrice,NULL,magicNB);
          if(openOrderID < 0) Alert("order rejected. Order error: " + GetLastError());
          
      }
   
    else //else if you already have a position, update orders if need too.
   {
      if(OrderSelect(openOrderID,SELECT_BY_TICKET)==true)
      {
            int orderType = OrderType();// Short = 1, Long = 0

            double optimalTakeProfit;
            
            if(orderType == 0)//long position
            {
               optimalTakeProfit = NormalizeDouble(Ask + 0.0001,Digits);
               
            }
            else //if short
            {
               optimalTakeProfit = NormalizeDouble(Ask - 0.0001,Digits);
            }

            double TP = OrderTakeProfit();
            double TPdistance = MathAbs(TP - optimalTakeProfit);
            if(TP != optimalTakeProfit && TPdistance > 0.0001)
            {
               bool Ans = OrderModify(openOrderID,OrderOpenPrice(),OrderStopLoss(),optimalTakeProfit,0);
            
               if (Ans==true)                     
               {
                  Print("Order modified: ",openOrderID);
                  return;                           
               }else
               {
                  Print("Unable to modify order: ",openOrderID);
               }   
            }
         }
      }
   }
   }
   
   

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

CustomFunctions01.mqh: 

//+------------------------------------------------------------------+
//|                                            CustomFunctions01.mqh |
//|                                                    Mohsen Hassan |
//|                             https://www.MontrealTradingGroup.com |
//+------------------------------------------------------------------+
#property copyright "Mohsen Hassan"
#property link      "https://www.MontrealTradingGroup.com"
#property strict
//+------------------------------------------------------------------+
//| defines                                                          |
//+------------------------------------------------------------------+
// #define MacrosHello   "Hello, world!"
// #define MacrosYear    2010
//+------------------------------------------------------------------+
//| DLL imports                                                      |
//+------------------------------------------------------------------+
// #import "user32.dll"
//   int      SendMessageA(int hWnd,int Msg,int wParam,int lParam);
// #import "my_expert.dll"
//   int      ExpertRecalculate(int wParam,int lParam);
// #import
//+------------------------------------------------------------------+
//| EX5 imports                                                      |
//+------------------------------------------------------------------+
// #import "stdlib.ex5"
//   string ErrorDescription(int error_code);
// #import
//+------------------------------------------------------------------+


double CalculateTakeProfit(bool isLong, double entryPrice, int pips)
{
   double takeProfit;
   if(isLong)
   {
      takeProfit = entryPrice + pips * GetPipValue();
   }
   else
   {
      takeProfit = entryPrice - pips * GetPipValue();
   }
   
   return takeProfit;
}

double CalculateStopLoss(bool isLong, double entryPrice, int pips)
{
   double stopLoss;
   if(isLong)
   {
      stopLoss = entryPrice - pips * GetPipValue();
   }
   else
   {
      stopLoss = entryPrice + pips * GetPipValue();
   }
   return stopLoss;
}




double GetPipValue()
{
   if(_Digits >=4)
   {
      return 0.0001;
   }
   else
   {
      return 0.01;
   }
}


void DayOfWeekAlert()
{

   Alert("");
   
   int dayOfWeek = DayOfWeek();
   
   switch (dayOfWeek)
   {
      case 1 : Alert("We are Monday. Let's try to enter new trades"); break;
      case 2 : Alert("We are tuesday. Let's try to enter new trades or close existing trades");break;
      case 3 : Alert("We are wednesday. Let's try to enter new trades or close existing trades");break;
      case 4 : Alert("We are thursday. Let's try to enter new trades or close existing trades");break;
      case 5 : Alert("We are friday. Close existing trades");break;
      case 6 : Alert("It's the weekend. No Trading.");break;
      case 0 : Alert("It's the weekend. No Trading.");break;
      default : Alert("Error. No such day in the week.");
   }
}


double GetStopLossPrice(bool bIsLongPosition, double entryPrice, int maxLossInPips)
{
   double stopLossPrice;
   if (bIsLongPosition)
   {
      stopLossPrice = entryPrice - maxLossInPips * 0.0001;
   }
   else
   {
      stopLossPrice = entryPrice + maxLossInPips * 0.0001;
   }
   return stopLossPrice;
}


bool IsTradingAllowed()
{
   if(!IsTradeAllowed())
   {
      Print("Expert Advisor is NOT Allowed to Trade. Check AutoTrading.");
      return false;
   }
   
   if(!IsTradeAllowed(Symbol(), TimeCurrent()))
   {
      Print("Trading NOT Allowed for specific Symbol and Time");
      return false;
   }
   
   return true;
}
  
  
double OptimalLotSize(double maxRiskPrc, int maxLossInPips)
{

  double accEquity = AccountEquity();
  Print("accEquity: " + accEquity);
  
  double lotSize = MarketInfo(NULL,MODE_LOTSIZE);
  Print("lotSize: " + lotSize);
  
  double tickValue = MarketInfo(NULL,MODE_TICKVALUE);
  
  if(Digits <= 3)
  {
   tickValue = tickValue /100;
  }
  
  Print("tickValue: " + tickValue);
  
  double maxLossDollar = accEquity * maxRiskPrc;
  Print("maxLossDollar: " + maxLossDollar);
  
  double maxLossInQuoteCurr = maxLossDollar / tickValue;
  Print("maxLossInQuoteCurr: " + maxLossInQuoteCurr);
  
  double optimalLotSize = NormalizeDouble(maxLossInQuoteCurr /(maxLossInPips * GetPipValue())/lotSize,2);
  
  return optimalLotSize;
 
}


double OptimalLotSize(double maxRiskPrc, double entryPrice, double stopLoss)
{
   int maxLossInPips = MathAbs(entryPrice - stopLoss)/GetPipValue();
   return OptimalLotSize(maxRiskPrc,maxLossInPips);
}



bool CheckIfOpenOrdersByMagicNB(int magicNB)
{
   int openOrders = OrdersTotal();
   
   for(int i = 0; i < openOrders; i++)
   {
      if(OrderSelect(i,SELECT_BY_POS)==true)
      {
         if(OrderMagicNumber() == magicNB) 
         {
            return true;
         }  
      }
   }
   return false;
}

I hope someone can help because I dont know how to fix this. Thanks in advance!

 
  1. wout_753: I dont know how to fix this.
    Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?

  2.       if(OrderSelect(openOrderID,SELECT_BY_TICKET)==true){
    You select by ticket. What happens if the ticket has already closed?
  3. EAs must be coded to recover. If the power fails, OS crashes, terminal or chart is accidentally closed, on the next tick, any static/global ticket variables will have been lost. You will have an open order but don't know it, so the EA will never try to close it, trail SL, etc. How are you going to recover? Use a OrderSelect loop to recover, or persistent storage (GV+flush or files) of ticket numbers required.

  4.       stopLossPrice = entryPrice - maxLossInPips * 0.0001;
    You buy at the Ask and sell at the Bid. So for buy orders you pay the spread on open. For sell orders you pay the spread on close.
    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid reaches it. Not the Ask. Your SL is shorter by the spread and your TP would be longer. Don't you want the same/specified amount for either direction?
    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask reaches it. To trigger at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25
    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

  5. PIP, Point, or Tick are all different in general.
              What is a TICK? - MQL4 programming forum

    Unless you manually adjust your SL/TP for each separate symbol, using Point means code breaks on JPY pairs, exotics (e.g. USDZAR where spread is over 500 points,) and metals. Compute what a PIP is and use it, not points.
              How to manage JPY pairs with parameters? - MQL4 programming forum
              Slippage defined in index points - Currency Pairs - Expert Advisors and Automated Trading - MQL5 programming forum