Can someone help me fix this code?

 
I want the EA logic to start trading when 2 MA's cross and stop trading when a trade closes in profit or when there is X number of consecutives losses. But its not working that way, its just trading normally. I need some to help me out please?
//+------------------------------------------------------------------+
//|                                              Profit Maker V3.mq4 |
//|                                                 Ecsentric Trades |
//|                                                                  |
//+------------------------------------------------------------------+
#property strict



input string saperator_00 = " *\/*\/*\/*\/* Trade Managment *\/*\/*\/*\/* " ; // *\/*\/*\/*\/*
input int magic_number = 7460828 ; // Magic Number
input bool is_open_buy = true ; // Open BUY trades
input bool is_open_sel = true ; // Open SELL trades


input string saperator_01 = " *\/*\/*\/*\/* Lot Managment *\/*\/*\/*\/* " ; // *\/*\/*\/*\/*
input bool use_fix_lot = true; // Use Fix Lot Size
input double fix_lot_size = 0.01 ; // Fix Lot Size
input double risk_percent = 5 ; // % of Equity


input string saperator_02 = " *\/*\/*\/*\/* SL/TP *\/*\/*\/*\/* " ; // *\/*\/*\/*\/*
input double tp_points = 500 ; // TP in Points
input double sl_points = 500 ; // SL in Points
input bool is_trailing = true; // Use Trailing Stop
input double trailing_stop_points = 100 ; // Trailing Stop in Points
input int slippage_points = 100 ; // Slippage


input string saperator_03 = " *\/*\/*\/*\/* Stochi Settings *\/*\/*\/*\/* " ; // *\/*\/*\/*\/*
extern int FastEMA = 12;
extern int SlowEMA = 26;
extern int SignalSMA = 9;
input bool is_trade_on_candle_close = true ; // Trade on Candle Close
input bool is_close_opposit_signal = true ; // Close on Opposit Signal

extern string S1 = "||======== MA1 Indicator Setting ========||";
extern int MA1_Period = 200;
extern int MA1_Shift = 0;
extern ENUM_MA_METHOD MA1_Method = MODE_SMA;
extern ENUM_APPLIED_PRICE MA1_Apply = PRICE_CLOSE;

extern string S2 = "||======== MA2 Indicator Setting ========||";
extern int MA2_Period = 100;
extern int MA2_Shift = 0;
extern ENUM_MA_METHOD MA2_Method = MODE_SMA;
extern ENUM_APPLIED_PRICE MA2_Apply = PRICE_CLOSE;


input string saperator_04 = " *\/*\/*\/*\/* Trading Hours *\/*\/*\/*\/* " ; // *\/*\/*\/*\/*
input int start_hour = 0 ; // Start Hour
input int stop_hour = 23 ; // Stop Hour


bool tradingEnabled = false;
bool maCrossover = false;
int consecutiveLosses = 0;
extern int maxConsecutiveLosses = 3;

extern string CommentsOrders    = "EA";



//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+



bool CheckMACrossover()
{
    // Add your logic to check for MA crossover
    // Return true if MA crossover condition is met, false otherwise
    double MA1=0;
   double MA2=0;
    MA1=iMA(NULL,0,MA1_Period,MA1_Shift,MA1_Method,MA1_Apply,1);
   MA2=iMA(NULL,0,MA2_Period,MA2_Shift,MA2_Method,MA2_Apply,1);
       if (MA1 > MA2 || MA2 > MA1) 
       return true;
   else
       return false;
}

// Check the number of consecutive losses and disable trading if the limit is reached
void CheckConsecutiveLosses()
{
    if (consecutiveLosses >= maxConsecutiveLosses)
    {
        tradingEnabled = false;
        Print("Trading disabled due to reaching the maximum consecutive losses.");
    }
}

// Enable trading if MA crossover condition is met
void EnableTrading()
{
    tradingEnabled = true;
    Print("Trading enabled.");
}

// Disable trading after a trade closes in profit or consecutive losses occur
void DisableTrading()
{
    tradingEnabled = false;
    Print("Trading disabled.");
}

// Check for MA crossover, enable/disable trading accordingly
void CheckMAConditions()
{
    if (CheckMACrossover())
    {
        maCrossover = true;
        EnableTrading();
    }
    else
    {
        maCrossover = false;
        DisableTrading();
    }
}

// Check the result of each closed trade
// Check the result of each closed trade
void OnTrade()
{
    // Check if there are any closed trades
    if (OrdersHistoryTotal() > 0)
    {
        // Get the ticket of the last closed trade
        ulong lastClosedTradeTicket = OrderSelect(OrdersHistoryTotal() - 1, SELECT_BY_POS, MODE_HISTORY) ? OrderTicket() : 0;

        // Check if the last closed trade resulted in a profit
        if (lastClosedTradeTicket > 0 && OrderProfit() > 0)
        {
            DisableTrading();
        }
        else
        {
            consecutiveLosses++;
            CheckConsecutiveLosses();
        }
    }
}


void OnTick()
  {

   main_body();

  }
//+------------------------------------------------------------------+


//+------------------------------------------------------------------+
//|                                                                  | Main Body of EA
//+------------------------------------------------------------------+
void main_body()
  {


//+------------------------------------------------------------------+
//|                                                                  |  Trailing Stop
//+------------------------------------------------------------------+
   if(is_trailing && OrdersTotal() != 0)
     {
      for(int i=0; i<OrdersTotal(); i++)
        {
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);

         if(OrderType() == OP_BUY) //************************************************ for BUY
           {
            if((Ask - OrderOpenPrice()) > (trailing_stop_points * Point()))
              {
               if((Ask - (trailing_stop_points * Point())) > OrderStopLoss())
                 {
                  OrderModify(OrderTicket(),OrderOpenPrice(),Ask - (trailing_stop_points * Point()),OrderTakeProfit(),0,clrAqua);
                 }
              }
           }


         if(OrderType() == OP_SELL) //************************************************* for SELL
           {
            if((OrderOpenPrice() - Bid) > (trailing_stop_points * Point()))
              {
               if((Bid + (trailing_stop_points * Point())) < OrderStopLoss())
                 {
                  OrderModify(OrderTicket(),OrderOpenPrice(),Bid + (trailing_stop_points * Point()),OrderTakeProfit(),0,clrAqua);
                 }
              }
           }
        }
     }
{
    // Check MA conditions if trading is enabled
    if (tradingEnabled)
    {
        CheckMAConditions();
    }
}

string comment_str = " Ecsentric Trades ";
  double MA1=0;
   double MA2=0;
   double macdCurrent, macdPrevious, signalCurrent, signalPrevious;
   
   MA1=iMA(NULL,0,MA1_Period,MA1_Shift,MA1_Method,MA1_Apply,1);
   MA2=iMA(NULL,0,MA2_Period,MA2_Shift,MA2_Method,MA2_Apply,1);
   
   macdCurrent = iMACD(NULL, 0, FastEMA, SlowEMA, SignalSMA, PRICE_CLOSE, MODE_MAIN, 0);
   macdPrevious = iMACD(NULL, 0, FastEMA, SlowEMA, SignalSMA, PRICE_CLOSE, MODE_MAIN, 1);
   signalCurrent = iMACD(NULL, 0, FastEMA, SlowEMA, SignalSMA, PRICE_CLOSE, MODE_SIGNAL, 0);
   signalPrevious = iMACD(NULL, 0, FastEMA, SlowEMA, SignalSMA, PRICE_CLOSE, MODE_SIGNAL, 1);
   
   
    
    if(is_trade_on_candle_close && Volume[0] <= 1)
     {
      if(MA2>MA1 && macdCurrent > signalCurrent && macdPrevious < signalPrevious && macdCurrent < 0 && signalCurrent < 0 && (Hour() >= start_hour && Hour() <= stop_hour))
        {
         if(is_close_opposit_signal)
           {
            do
              {
               closeSell();
              }
            while(checkIfalreadyHaveSell());
           }

         if(is_open_buy)
            openBuy();
        }

      if(MA2<MA1 && macdCurrent < signalCurrent && macdPrevious > signalPrevious && macdCurrent > 0 && signalCurrent > 0 && (Hour() >= start_hour && Hour() <= stop_hour))
        {
         if(is_close_opposit_signal)
           {
            do
              {
               closeBuy();
              }
            while(checkIfalreadyHaveBuy());
           }

         if(is_open_sel)
            openSell();
        }
     }
   else
     {
      if(MA2>MA1 && macdCurrent > signalCurrent && macdPrevious < signalPrevious && macdCurrent < 0 && signalCurrent < 0 && (Hour() >= start_hour && Hour() <= stop_hour))
        {
         if(is_close_opposit_signal)
           {
            do
              {
               closeSell();
              }
            while(checkIfalreadyHaveSell());
           }

         if(is_open_buy)
            openBuy();
        }

      if(MA2<MA1 && macdCurrent < signalCurrent && macdPrevious > signalPrevious && macdCurrent > 0 && signalCurrent > 0 && (Hour() >= start_hour && Hour() <= stop_hour))
        {
         if(is_close_opposit_signal)
           {
            do
              {
               closeBuy();
              }
            while(checkIfalreadyHaveBuy());
           }


         if(is_open_sel)
            openSell();
        }
     }

   comment_str += "\n time = " + checkTime() + "\n current hour = " + Hour() + " ~Start hour = "+ start_hour + " ~Stop hour = " +stop_hour;

   Comment(comment_str);

   
   }
//+------------------------------------------------------------------+


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool checkTime()
  {
   datetime temp_datetime ;
   if(Hour() >= start_hour && Hour() <= stop_hour)
     {
      return true;
     }

   return false;
  }


//+------------------------------------------------------------------+
//|                                                                  |  Open BUY
//+------------------------------------------------------------------+
void openBuy()
  {
   if(checkIfalreadyHaveBuy())
     {
      return ;
     }

   double tempTP = Ask + (tp_points * Point());
   double tempSL = Ask - (sl_points * Point());
   double tempLotSize = lotCalculator(tempSL,Ask,11);
   
     
   int current_ticket = OrderSend(Symbol(),OP_BUY,tempLotSize,Ask,slippage_points,tempSL,tempTP,CommentsOrders,magic_number,0,clrGreen);
  }

//+------------------------------------------------------------------+
//|                                                                  |  Open SELL
//+------------------------------------------------------------------+
void openSell()
  {

   if(checkIfalreadyHaveSell())
     {
      return ;
     }

   double tempTP = Bid - (tp_points * Point());
   double tempSL = Bid + (sl_points * Point());
   double tempLotSize = lotCalculator(tempSL,Bid,22);
   
   

   int current_ticket = OrderSend(Symbol(),OP_SELL,tempLotSize,Bid,slippage_points,tempSL,tempTP,CommentsOrders,magic_number,0,clrRed);
  }



//+------------------------------------------------------------------+
//|                                                                  |  Lot Size Calculator
//+------------------------------------------------------------------+
double lotCalculator(double slPrice, double openPrice, int sellbuy)
  {

   if(use_fix_lot)
     {
      return fix_lot_size;
     }

   double current_sl_price = slPrice;
   double current_open_price = openPrice;
   int current_sellbuy = sellbuy;

   double current_risk_amount = (AccountInfoDouble(ACCOUNT_EQUITY) / 100) * risk_percent;

   double current_lot ;

   if(current_sellbuy == 11) // for BUY
     {
      current_lot = NormalizeDouble(current_risk_amount / ((current_open_price - current_sl_price)/Point()), 2);
      if(current_lot < 0.01)
        {
         return 0.01;
        }
     }
   if(current_sellbuy == 22) // for SELL
     {
      current_lot = NormalizeDouble(current_risk_amount / ((current_sl_price - current_open_price)/Point()), 2);
      if(current_lot < 0.01)
        {
         return 0.01;
        }
     }

   return current_lot;
  }
//+------------------------------------------------------------------+


//+------------------------------------------------------------------+
//|                                                                  |  close BUY
//+------------------------------------------------------------------+
void closeBuy()
  {
   if(OrdersTotal() != 0)
     {
      for(int i=0; i<=OrdersTotal()+2; i++)
        {
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderType() == OP_BUY && OrderSymbol() == Symbol())
           {
            OrderClose(OrderTicket(),OrderLots(),Bid,10,clrWhite);
           }
        }
     }
  }


//+------------------------------------------------------------------+
//|                                                                  |  close SELL
//+------------------------------------------------------------------+
void closeSell()
  {
   if(OrdersTotal() != 0)
     {
      for(int i=0; i<=OrdersTotal()+1; i++)
        {
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderType() == OP_SELL && OrderSymbol() == Symbol())
           {
            OrderClose(OrderTicket(),OrderLots(),Ask,10,clrWhite);
           }
        }
     }
  }

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


//+------------------------------------------------------------------+
//|                                                                  |  check if already have trade on current pair
//+------------------------------------------------------------------+
bool checkIfalreadyHaveTrade()
  {
   if(OrdersTotal() != 0)
     {
      for(int i = 0; i <= OrdersTotal() ; i++)
        {
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderSymbol() == Symbol())
           {
            return true;
           }
        }
     }
   return false;
  }
//+------------------------------------------------------------------+


//+------------------------------------------------------------------+
//|                                                                  |  check if already have buy trade on current pair
//+------------------------------------------------------------------+
bool checkIfalreadyHaveBuy()
  {
   if(OrdersTotal() != 0)
     {
      for(int i = 0; i <= OrdersTotal() ; i++)
        {
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderSymbol() == Symbol() && OrderType() == OP_BUY)
           {
            return true;

           }
        }
     }
   return false;
  }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//|                                                                  |   check if already have sell trade on current pair
//+------------------------------------------------------------------+
bool checkIfalreadyHaveSell()
  {
   if(OrdersTotal() != 0)
     {
      for(int i = 0; i <= OrdersTotal() ; i++)
        {
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderSymbol() == Symbol() && OrderType() == OP_SELL)
           {
            return true;

           }
        }
     }
   return false;
  }
//+------------------------------------------------------------------+


//+------------------------------------------------------------------+
 
  1. //|                                              Profit Maker V3.mq4 |

    Why did you post your MT4 question in the MT5 EA section instead of the MQL4 section, (bottom of the Root page)?
              General rules and best pratices of the Forum. - General - MQL5 programming forum? (2017)
    Next time, post in the correct place. The moderators will likely move this thread there soon.

  2. Your code
           if (MA1 > MA2 || MA2 > MA1) 
           return true;
       else
           return false;
    Simplified
    return MA1 > MA2 || MA2 > MA1;
  3.    double tempTP = Ask + (tp_points * Point());
       double tempSL = Ask - (sl_points * Point());

    You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close 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.)

      Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
      My GBPJPY shows average spread = 26 points, average maximum spread = 134.
      My EURCHF shows average spread = 18 points, average maximum spread = 106.
      (your broker will be similar).
                Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

  4.         ulong lastClosedTradeTicket = OrderSelect(OrdersHistoryTotal() - 1, SELECT_BY_POS, MODE_HISTORY) ? OrderTicket() : 0;
    
    1. Do not assume history has only closed orders.
                OrderType() == 6, 7 in the history pool? - MQL4 programming forum #4 and #5 (2017)

    2. Do not assume history is ordered by date, it's not.
                Could EA Really Live By Order_History Alone? (ubzen) - MQL4 programming forum (2012)
                Taking the last profit and storing it in a variable | MQL4 - MQL4 programming forum #3 (2020)

    3. Magic number only allows an EA to identify its trades from all others. Using OrdersTotal/OrdersHistoryTotal (MT4) or PositionsTotal (MT5), directly and/or no Magic number/symbol filtering on your OrderSelect / Position select loop means your code is incompatible with every EA (including itself on other charts and manual trading.)
                Symbol Doesn't equal Ordersymbol when another currency is added to another seperate chart . - MQL4 programming forum (2013)
                PositionClose is not working - MQL5 programming forum (2020)
                MagicNumber: "Magic" Identifier of the Order - MQL4 Articles (2006)
                Orders, Positions and Deals in MetaTrader 5 - MQL5 Articles (2011)
                Limit one open buy/sell position at a time - General - MQL5 programming forum (2022)

      You need one Magic Number for each symbol/timeframe/strategy.
           Trade current timeframe, one strategy, and filter by symbol requires one MN.
           If trading multiple timeframes, and filter by symbol requires use a range of MN (base plus timeframe).
                Why are MT5 ENUM_TIMEFRAMES strange? - General - MQL5 programming forum - Page 2 #11 (2020)

  5.     if(is_trade_on_candle_close && Volume[0] <= 1)

    For a new bar test, Bars is unreliable (a refresh/reconnect can change number of bars on chart), volume is unreliable (miss ticks), Price is unreliable (duplicate prices and The == operand. - MQL4 programming forum.) Always use time.
              MT4: New candle - MQL4 programming forum #3 (2014)
              MT5: Accessing variables - MQL4 programming forum #3 (2022)

    I disagree with making a new bar function, because it can only be called once per tick (second call returns false). A variable can be tested multiple times.
              Running EA once at the start of each bar - MQL4 programming forum (2011)

  6.       current_lot = NormalizeDouble(current_risk_amount / ((current_open_price - current_sl_price)/Point()), 2);

    Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin and leverage. No SL means you have infinite risk (on leveraged symbols). Never risk more than a small percentage of your trading funds, certainly less than 2% per trade, 6% total.

    1. You place the stop where it needs to be — where the reason for the trade is no longer valid. E.g. trading a support bounce, the stop goes below the support.

    2. AccountBalance * percent/100 = RISK = OrderLots * (|OrderOpenPrice - OrderStopLoss| * DeltaPerLot + CommissionPerLot) (Note OOP-OSL includes the spread, and DeltaPerLot is usually around $10/PIP, but it takes account of the exchange rates of the pair vs. your account currency.)

    3. Do NOT use TickValue by itself - DeltaPerLot and verify that MODE_TICKVALUE is returning a value in your deposit currency, as promised by the documentation, or whether it is returning a value in the instrument's base currency.
                MODE_TICKVALUE is not reliable on non-fx instruments with many brokers - MQL4 programming forum (2017)
                Is there an universal solution for Tick value? - Currency Pairs - General - MQL5 programming forum (2018)
                Lot value calculation off by a factor of 100 - MQL5 programming forum (2019)

    4. You must normalize lots properly and check against min and max.

    5. You must also check Free Margin to avoid stop out

    6. For MT5, see 'Money Fixed Risk' - MQL5 Code Base (2017)

    Most pairs are worth about $10 per PIP. A $5 risk with a (very small) 5 PIP SL is $5/$10/5 or 0.1 Lots maximum.

  7.    if(OrdersTotal() != 0)
         {
          for(int i=0; i<=OrdersTotal()+2; i++)
            {
             OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
    When i i greater or equal to OrdersTotal, the select fails but you don't check.
  8. In the presence of multiple orders (one EA multiple charts, multiple EAs, manual trading), while you are waiting for the current operation (closing, deleting, modifying) to complete, any number of other operations on other orders could have concurrently happened and changed the position indexing and order count:

    1. For non-FIFO (non-US brokers), (or the EA only opens one order per symbol), you can simply count down, in an index loop, and you won't miss orders. Get in the habit of always counting down.
                Loops and Closing or Deleting Orders - MQL4 programming forum

    2. For In First Out (FIFO rules — US brokers), and you (potentially) process multiple orders per symbol, you must find the earliest order (count up), close it, and on a successful operation, reprocess all positions (from zero).
                CloseOrders by FIFO Rules - Strategy Tester - MQL4 programming forum - Page 2 #16
                MetaTrader 5 platform beta build 2155: MQL5 scope, global Strategy Tester and built-in Virtual Hosting updates - Best Expert Advisors - General - MQL5 programming forum #1.11

    and check OrderSelect in case other positions were deleted.
              What are Function return values ? How do I use them ? - MQL4 programming forum
              Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles

    and if you (potentially) process multiple orders, must call RefreshRates() after server calls if you want to use, on the next order / server call, the Predefined Variables (Bid/Ask.) Or instead, be direction independent and just use OrderClosePrice().

 
Thanks for your help. But the information seems to be too much and a little confusing. If you don't mind, can you help me make the corrections on the code?
 
ecsentricjay #: Thanks for your help. But the information seems to be too much and a little confusing. If you don't mind, can you help me make the corrections on the code?

If you want to learn to code, then you need to put in more effort and dedicate some time to researching the information.

If you can't do that, then consider hiring someone to code it for you.

Trading applications for MetaTrader 5 to order
Trading applications for MetaTrader 5 to order
  • 2023.05.30
  • www.mql5.com
The largest freelance service with MQL5 application developers
 
ecsentricjay # If you don't mind, can you help me make the corrections on the code?

Help you with what? You haven't stated a problem, you stated a want. Show us your attempt (using the CODE button) and state the nature of your difficulty.
          No free help (2017)

Or pay someone. Top of every page is the link Freelance.
          Hiring to write script - General - MQL5 programming forum (2018)

We're not going to code it for you (although it could happen if you are lucky or the issue is interesting).
          No free help (2017)

Reason: