why this EA can’t buy and sell automatically when I backtest it , is there anyone know why?

 
Hi, I want to know the reason of why this EA can’t buy and sell automatically? what the problem is ? it there any solution for it? if someone know please help, I have no one to get help from and really unable to hire freelancer to solve my issues. I post this issue multiple time but no one helped me. Here is the code: //+------------------------------------------------------------------+
//| Property                                                         |
//+------------------------------------------------------------------+
#property strict
//+------------------------------------------------------------------+
//| Global variables                                                 |
//+------------------------------------------------------------------+
input int MA_Period = 50; // Period for the moving average
input double Risk_Percentage = 1.5; // Adjusted risk percentage per trade
input double Stop_Loss = 100.0; // Initial stop loss in points
input double Take_Profit = 200.0; // Take profit level in points
double LotSize; // Position size based on risk
int Digits; // Number of decimal places for the symbol
double AccountBalance = 10000.0; // Account balance in USD

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   Digits = int(SymbolInfoInteger(_Symbol, SYMBOL_DIGITS)); // Get the number of decimal places for the symbol
   LotSize = CalculatePositionSize(); // Calculate initial lot size
   
   Print("Expert Advisor initialized successfully.");
   
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   Print("Expert Advisor deinitialized successfully.");
}
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   double closePrice[]; // Declare 'closePrice' as an array

   if (Bars(_Symbol, 0) < MA_Period + 2) // Check if there is enough historical data
      return;

   if (!CopyClose(_Symbol, 0, 1, 1, closePrice))
   {
      Print("Error copying Close price: ", GetLastError());
      return;
   }

   double ma = iMA(_Symbol, 0, MA_Period, 0, MODE_SMA, PRICE_CLOSE);
   
   if (closePrice[1] < ma && closePrice[0] > ma && closePrice[1] < closePrice[0] - 10) // Add condition to check price trend and other sophisticated entry conditions
   {
      MqlTradeRequest request;
      request.action = TRADE_ACTION_DEAL;
      request.magic = 123456;
      request.symbol = _Symbol;
      request.volume = LotSize; // Use calculated lot size
      request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      request.type = ORDER_TYPE_BUY;
      request.type_filling = ORDER_FILLING_FOK;
      
      double Point = SymbolInfoDouble(_Symbol, SYMBOL_POINT); // Define Point
      
      request.tp = NormalizeDouble(closePrice[0] + CalculateTakeProfit() * Point, Digits); // Set dynamic take profit level
      request.sl = NormalizeDouble(closePrice[0] - CalculateStopLoss() * Point, Digits); // Set dynamic stop loss level

      MqlTradeResult result;

      if (!OrderSend(request, result))
      {
         Print("Buy OrderSend error: ", GetLastError());
         return;
      }
   }
   else if (closePrice[1] > ma && closePrice[0] < ma && closePrice[1] > closePrice[0] + 10) // Add condition to check price trend and other sophisticated entry conditions
   {  
      MqlTradeRequest request;
      request.action = TRADE_ACTION_DEAL;
      request.magic = 123456;
      request.symbol = _Symbol;
      request.volume = LotSize; // Use calculated lot size
      request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      request.type = ORDER_TYPE_SELL;
      request.type_filling = ORDER_FILLING_FOK;

      double Point = SymbolInfoDouble(_Symbol, SYMBOL_POINT); // Define Point
      
      request.tp = NormalizeDouble(closePrice[0] - CalculateTakeProfit() * Point, Digits); // Set dynamic take profit level
      request.sl = NormalizeDouble(closePrice[0] + CalculateStopLoss() * Point, Digits); // Set dynamic stop loss level

      MqlTradeResult result;

      if (!OrderSend(request, result))
      {
         Print("Sell OrderSend error: ", GetLastError());
         return;
      }
   }
}

//+------------------------------------------------------------------+
//| Calculate dynamic stop loss based on market conditions           |
//+------------------------------------------------------------------+
double CalculateStopLoss()
{
    double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
    double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
    
    return ((AccountBalance * Risk_Percentage / (LotSize * Stop_Loss)) / (tick_value * tick_size));
}

//+------------------------------------------------------------------+
//| Calculate dynamic take profit based on market conditions         |
//+------------------------------------------------------------------+
double CalculateTakeProfit()
{
    double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
    double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);

    return ((AccountBalance * Risk_Percentage / (LotSize * Take_Profit)) / (tick_value * tick_size));
}

//+------------------------------------------------------------------+
//| Calculate dynamic position size based on risk percentage and stop loss|
//+------------------------------------------------------------------+
double CalculatePositionSize()
{
    double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
    double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
    
    double riskAmount = AccountBalance * Risk_Percentage;
    double maxLoss = riskAmount * LotSize * Stop_Loss;
    
    return NormalizeDouble(maxLoss / (tick_value * tick_size), 2);
}
 

my guess is this line needs to be changed to an array? then fill the array with CopyBuffer. See any ma expert advisor on codebase for further info.

   double ma = iMA(_Symbol, 0, MA_Period, 0, MODE_SMA, PRICE_CLOSE);
 
Michael Charles Schefe #: my guess is this line needs to be changed to an array?

OP has been told that he needs to get the handle in OnInit at least five (5) times. 1 2

 
William Roeder #:

OP has been told that he needs to get the handle in OnInit at least five (5) times. 1 2

I did these modification but the issue persists, Look please:

Improperly formatted code removed by moderator
MQL5.community - User Memo
MQL5.community - User Memo
  • www.mql5.com
You have just registered and most likely you have questions such as, "How do I insert a picture to my a message?" "How do I format my MQL5 source code?" "Where are my personal messages kept?" You may have many other questions. In this article, we have prepared some hands-on tips that will help you get accustomed in MQL5.community and take full advantage of its available features.
 
محمد دهقانی #: I did these modification but the issue persists, Look please:
  1. You have been told, multiple times to use the CODE button
  2. 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?
              Code debugging - Developing programs - MetaEditor Help
              Error Handling and Logging in MQL5 - MQL5 Articles (2015)
              Tracing, Debugging and Structural Analysis of Source Code - MQL5 Articles (2011)
              Introduction to MQL5: How to write simple Expert Advisor and Custom Indicator - MQL5 Articles (2010)

Reason: