Problem with backtesting after ordersend

 

Hello

I have written an expert adviser and I'm using C-Trade to execute buy and sell commands.

Unfortunately the program stops after executing the buy or sell command. Would someone please help me and explain what is wrong with my code?

I have uninstalled MT5 completely and deleted Metaquote data then reinstalled it again to make sure that there's no problem with cache or something but the result remained the same.


//+------------------------------------------------------------------+
//|                                                CCI-Simple.mq5    |
//|                                  Copyright 2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, Younes Khademian."
#property link      "https://www.mql5.com"
#property version   "1.00"
#include <Trade\Trade.mqh>
CTrade trade;
//+------------------------------------------------------------------+
//| Input Variables                                                  |
//+------------------------------------------------------------------+
input int      InpSlippage = 50;                      //    Slippage points
input double   InpRiskPercentage = 0.2;               //    Risk Percentage
input int      InpBarNumAver = 10;                    //    Number of bars for Volume and Size average
input string   InpStartTime = "05:00";                //    Start Time
input string   InpFinishTime = "23:30";               //    Finish Time
input ENUM_TIMEFRAMES InpTimeframe = PERIOD_CURRENT;  //    Time Frame of EA
//+------------------------------------------------------------------+
//| Glocal Variables                                                 |
//+------------------------------------------------------------------+
int   handleCCI;
int   totalbars;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   handleCCI = iCCI(_Symbol,InpTimeframe,14,PRICE_TYPICAL);
   totalbars = iBars(_Symbol,InpTimeframe);
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- Local Variables
   double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits); // Get the Ask Price
   double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits); // Get the Bid Price
   int            RobotBuy =0;
   double         LotSizeBuy;
   double         BuySL;
   double         TPBuy;
   double         BuyPrice;
   double         ModifiedBuySL;
   bool           NoOtherBuyFlag;
   bool           BullishCondition;
   datetime       BuyTime;
   int            RobotSell = 0;
   double         LotSizeSell;
   double         SellSL;
   double         TPSell;
   double         SellPrice;
   double         ModifiedSellSL;
   bool           NoOtherSellFlag;
   bool           BearishCondition;
   datetime       SellTime;
//+******************************************************************+
//| This part of program will be executed for new bars only          |
//+******************************************************************+
   int currentbars = iBars(_Symbol,InpTimeframe);
   if (totalbars < currentbars)
   {
   totalbars = currentbars;
   
   datetime     StartTime = StringToTime(InpStartTime);
   datetime     FinishTime = StringToTime(InpFinishTime);
   datetime     CurrentTime = TimeCurrent();
   double   CandleSizeAverage = 0;
   for (int i=1;i<=InpBarNumAver;i++)
      {
      CandleSizeAverage += MathAbs(iHigh(_Symbol,InpTimeframe,i)-iLow(_Symbol,InpTimeframe,i));
      }
   CandleSizeAverage = NormalizeDouble(CandleSizeAverage/InpBarNumAver,_Digits);
   double   CCI[];   
   ArraySetAsSeries(CCI,true);
   CopyBuffer(handleCCI,0,0,3,CCI);
   bool           WorkingTimeFlag;
   
   // Check for Start Time and Finish Time of EA
   WorkingTimeFlag = (CurrentTime > StartTime && CurrentTime < FinishTime) ? true : false;
//*******************************************************************+
//+------------------------------------------------------------------+
//| Check for Bullish (Buy) Conditions in selected timeframe         |
//+------------------------------------------------------------------+
//*******************************************************************+
   BullishCondition = CCI[0] > 0
                      && CCI[1] < 0
                      ;
   // Check for other Robot Buys
   NoOtherBuyFlag = (RobotBuy<1) ? true : false;
      
   // Execute Buy Command for Strategy[0] (CCI) Buy
   if(WorkingTimeFlag == true && NoOtherBuyFlag == true
      && BullishCondition == true) 
         {
         BuySL = NormalizeDouble(MathMin(iLow(_Symbol,InpTimeframe,0),iLow(_Symbol,InpTimeframe,1))-(Ask-Bid),_Digits);
         LotSizeBuy = GetlotSize(InpRiskPercentage,(Ask-BuySL),_Symbol);
         TPBuy = NormalizeDouble((Ask-BuySL),_Digits);
         trade.Buy(LotSizeBuy,_Symbol,0,BuySL,0,"RobotBuy");
         BuyPrice = Ask;
         BuyTime = TimeCurrent();
         MqlDateTime BuyTimeStruc;
         TimeToStruct(TimeCurrent()-BuyTime, BuyTimeStruc);
         }
//*******************************************************************+
//+------------------------------------------------------------------+
//| Check for Bearish (Sell) Conditions in selected timeframe        |
//+------------------------------------------------------------------+
//*******************************************************************+
   BearishCondition = CCI[0] < 0
                      && CCI[1] > 0
                      ;
   // Check for other Robot Buys
   NoOtherSellFlag = (RobotSell < 1) ? true : false;
      
   // Execute Sell Command for Strategy[0]
   if(WorkingTimeFlag == true && NoOtherSellFlag == true
      && BearishCondition == true) 
         {
         SellSL = NormalizeDouble(MathMax(iHigh(_Symbol,PERIOD_M5,0),iHigh(_Symbol,PERIOD_M5,1))+(Ask-Bid),_Digits);
         LotSizeSell = GetlotSize(InpRiskPercentage,(SellSL-Bid),_Symbol);
         TPSell = NormalizeDouble((SellSL-Bid),_Digits);
         trade.Sell(LotSizeSell,_Symbol,0,SellSL,0,"RobotSell");
         SellPrice = Bid;
         SellTime = TimeCurrent();
         MqlDateTime SellTimeStruc;
         TimeToStruct(TimeCurrent()-SellTime, SellTimeStruc);
         }
Comment("WorkingTimeFlag = ",WorkingTimeFlag,"\n",
        "BullishCondition = ",BullishCondition,"\n",
        "BearishCondition = ",BearishCondition,"\n",
        "CandleSizeAverage = ",CandleSizeAverage,"\n",
        "CCI[0] = ",CCI[0],"\n",
        "CCI[1] = ",CCI[1],"\n",
        "Is Symbol Currect? ", _Symbol == _Symbol,"\n"
        );
  }
//+******************************************************************+
//| End of checking new bars                                         |
//+******************************************************************+
// The rest of program will be executed on every tick  
//+------------------------------------------------------------------+
//| Check Buy Positions                                              |
//+------------------------------------------------------------------+
   RobotBuy = 0;
   
   if (PositionSelect(_Symbol) == true)
   for (int i=PositionsTotal()-1; i>=0; i++)
      {
      if(PositionSelectByTicket(PositionGetTicket(i)))
      {
      if((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY 
         && PositionGetString(POSITION_SYMBOL) == _Symbol 
         && PositionGetString(POSITION_COMMENT) == "RobotBuy")
         {
         RobotBuy++;
         //// Partially Close (25%) of position if TP1 is hit for Buy Strategy 0
         //if (Ask >= PositionGetDouble(POSITION_PRICE_OPEN) + TPBuy[0] && PositionGetDouble(POSITION_VOLUME) == LotSizeBuy[0])
         //   {
         //   trade.PositionClosePartial(PositionSelectByTicket(PositionGetTicket(i)),NormalizeDouble(0.25*LotSizeBuy[0],2));
         //   }
         // Modify Buy SL if price is j TP higher than open position for Buy Strategy 0
         TPBuy = NormalizeDouble(PositionGetDouble(POSITION_PRICE_OPEN)-PositionGetDouble(POSITION_SL),_Digits);
         for (int j=0;j<=30;j++)
            {
            if (Bid >= PositionGetDouble(POSITION_PRICE_OPEN) + (j+1)*TPBuy)
               {
               ModifiedBuySL = NormalizeDouble(PositionGetDouble(POSITION_PRICE_OPEN)+j*TPBuy+Ask-Bid,_Digits);
               if (ModifiedBuySL>PositionGetDouble(POSITION_SL))
                  trade.PositionModify(PositionGetTicket(i),ModifiedBuySL,0);
               }
            }
         }
      }
      }    
//+------------------------------------------------------------------+
//| Check Sell Positions                                             |
//+------------------------------------------------------------------+
   RobotSell = 0;
   
   if (PositionSelect(_Symbol) == true)
   for (int i=PositionsTotal()-1; i>=0; i++)
      {
      if(PositionSelectByTicket(PositionGetTicket(i)))
      {
      // Sell Strategy 0
      if((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL
       && PositionGetString(POSITION_SYMBOL) == _Symbol
       && PositionGetString(POSITION_COMMENT) == "RobotSell")
         {
         RobotSell++;
         // Close position for Opposite Signal Sell Strategy 0
         //if (CCI[0]<80)
         //   {
         //   trade.PositionClose(PositionSelectByTicket(PositionGetTicket(i)));
         //   }
         // Partially Close (25%) of position if TP1 is hit for Sell Strategy 0
         //if (Bid <= PositionGetDouble(POSITION_PRICE_OPEN) - TPSell[0] && PositionGetDouble(POSITION_VOLUME) == LotSizeSell[0])
         //   {
         //   trade.PositionClosePartial(PositionSelectByTicket(PositionGetTicket(i)),NormalizeDouble(0.25*LotSizeSell[0],2));
         //   }
         // Modify Sell SL if price is j TP Lower than open position for Sell Strategy 0
         TPSell = NormalizeDouble(PositionGetDouble(POSITION_SL)-PositionGetDouble(POSITION_PRICE_OPEN),_Digits);
         for (int j=0;j<=30;j++)
            {
            if (Ask <= PositionGetDouble(POSITION_PRICE_OPEN) - (j+1)*TPSell)
               {
               ModifiedSellSL = PositionGetDouble(POSITION_PRICE_OPEN)-j*TPSell;
               if (ModifiedSellSL<PositionGetDouble(POSITION_SL))
                  trade.PositionModify(PositionGetTicket(i),ModifiedSellSL,0);
               }
            }
         }
         }
      }
  }
//+------------------------------------------------------------------+
// end of ontick function
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Calculate LotSize Based o risk percentage and stoploss           |
//+------------------------------------------------------------------+
double GetlotSize(double RiskPercent,double SLDistance,string barsymbol)
   {
   SLDistance = MathAbs(SLDistance);
   double ticksize = SymbolInfoDouble(barsymbol,SYMBOL_TRADE_TICK_SIZE);
   double tickvalue = SymbolInfoDouble(barsymbol,SYMBOL_TRADE_TICK_VALUE);
   double volstep = SymbolInfoDouble(barsymbol,SYMBOL_VOLUME_STEP);
   
   double RiskMoney = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent /100;
   double MoneyLotStep = (SLDistance/ticksize) * tickvalue * volstep;
   
   if (ticksize==0 || tickvalue==0 || volstep==0 || MoneyLotStep==0) return 0;
   double lotsize = NormalizeDouble((RiskMoney / MoneyLotStep) * volstep,2);
   
   if (lotsize > SymbolInfoDouble(barsymbol,SYMBOL_VOLUME_MAX))
      lotsize = SymbolInfoDouble(barsymbol,SYMBOL_VOLUME_MAX);
   
   if (lotsize < SymbolInfoDouble(barsymbol,SYMBOL_VOLUME_MIN))
      lotsize = SymbolInfoDouble(barsymbol,SYMBOL_VOLUME_MIN);   
   
   return lotsize;
  
   }
Discover new MetaTrader 5 opportunities with MQL5 community and services
Discover new MetaTrader 5 opportunities with MQL5 community and services
  • 2025.01.25
  • www.mql5.com
MQL5: language of trade strategies built-in the MetaTrader 5 Trading Platform, allows writing your own trading robots, technical indicators, scripts and libraries of functions