would you please help me to implement a mechanism in my code to maximize profits and minimize loses in challenging market condions

 

Hi, I try to implement a mechanism in my EA code to minimize loses and maximize profits even in challenging market conditions , would you please help me to do this ? please provide code for the modifications that I should made if possible Here is my code:

//+------------------------------------------------------------------+
//| Property                                                         |
//+------------------------------------------------------------------+
#property strict
//+------------------------------------------------------------------+
//| Global variables                                                 |
//+------------------------------------------------------------------+
input int MA_Period = 50; // Period for the moving average
input double Risk_Percentage = 1.0; // 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;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   // Calculate position size based on risk percentage and stop loss
   LotSize = AccountInfoDouble(ACCOUNT_FREEMARGIN) * Risk_Percentage / Stop_Loss;
   Digits = int(SymbolInfoInteger(_Symbol, SYMBOL_DIGITS)); // Get the number of decimal places for the symbol
   
   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 (!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
   {
      MqlTradeRequest request;
      request.action = TRADE_ACTION_DEAL;
      request.magic = 123456;
      request.symbol = _Symbol;
      request.volume = LotSize;
      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] + Take_Profit * Point, Digits); // Set take profit 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
   {
      MqlTradeRequest request;
      request.action = TRADE_ACTION_DEAL;
      request.magic = 123456;
      request.symbol = _Symbol;
      request.volume = LotSize;
      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] - Take_Profit * Point, Digits); // Set take profit level

      MqlTradeResult result;

      if (!OrderSend(request, result))
      {
         Print("Sell OrderSend error: ", GetLastError());
         return;
      }
   }
}
 
محمد دهقانی: o implement a mechanism in my EA code to minimize loses and maximize profits even in challenging market conditions , would you please help me to do this
  1. Until you can state your requirements in concrete terms, it can not be coded.

  2. 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)

  3. int OnInit(){
       LotSize = AccountInfoDouble(ACCOUNT_FREEMARGIN) * Risk_Percentage / Stop_Loss;
    Don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet:
    1. Terminal starts.
    2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
    3. OnInit is called.
    4. For indicators OnCalculate is called with any existing history.
    5. Human may have to enter password, connection to server begins.
    6. New history is received, OnCalculate called again.
    7. A new tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.
  4. Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin or 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% account 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. Then you compute your lot size.

    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.

  5.    double ma = iMA(_Symbol, 0, MA_Period, 0, MODE_SMA, PRICE_CLOSE);
    

    As I have stated, at least three (3) times before, fix your code. How can I solve ')' - open parenthesis expected in MQL5? - Moving Average, MA - General - MQL5 programming forum #2.2

 
William Roeder #:
  1. Until you can state your requirements in concrete terms, it can not be coded.

  2. 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)

  3. Don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet:
    1. Terminal starts.
    2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
    3. OnInit is called.
    4. For indicators OnCalculate is called with any existing history.
    5. Human may have to enter password, connection to server begins.
    6. New history is received, OnCalculate called again.
    7. A new tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.
  4. Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin or 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% account 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. Then you compute your lot size.

    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.

  5. As I have stated, at least three (3) times before, fix your code. How can I solve ')' - open parenthesis expected in MQL5? - Moving Average, MA - General - MQL5 programming forum #2.2

"Don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet"

Wow, I really just discovered that it is not good practice to call indicators in OnInit.  Thank you!

 
Enrique Enguix #:

"Don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet"

Wow, I really just discovered that it is not good practice to call indicators in OnInit.  Thank you!

Yes, you will have to state your requirements. I can not elaborate more on the code as i can see it was explained to you already. Always make sure to use functions for its intended purpose and in the right place, this is a very important thing to remember. Syntax is key to creating a working expert/Indicator

 
OK , you are right , I stated my requirements next time. 
 
Enrique Enguix #: Wow, I really just discovered that it is not good practice to call indicators in OnInit.  Thank you!
  1. I didn't say that.
  2. They all (including iCustom) return a handle (an int). You get that in OnInit. In OnTick/OnCalculate (after the indicator has updated its buffers), you use the handle, shift and count to get the data.
              Technical Indicators - Reference on algorithmic/automated trading language for MetaTrader 5
              Timeseries and Indicators Access / CopyBuffer - Reference on algorithmic/automated trading language for MetaTrader 5
              How to start with MQL5 - General - MQL5 programming forum - Page 3 #22 (2020)
              How to start with MQL5 - MetaTrader 5 - General - MQL5 programming forum - Page 7 #61 (2020)
              MQL5 for Newbies: Guide to Using Technical Indicators in Expert Advisors - MQL5 Articles (2010)
              How to call indicators in MQL5 - MQL5 Articles (2010)

 
William Roeder #:
  1. Until you can state your requirements in concrete terms, it can not be coded.

  2. 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)

  3. Don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet:
    1. Terminal starts.
    2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
    3. OnInit is called.
    4. For indicators OnCalculate is called with any existing history.
    5. Human may have to enter password, connection to server begins.
    6. New history is received, OnCalculate called again.
    7. A new tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.
  4. Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin or 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% account 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. Then you compute your lot size.

    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.

  5. As I have stated, at least three (3) times before, fix your code. How can I solve ')' - open parenthesis expected in MQL5? - Moving Average, MA - General - MQL5 programming forum #2.2

I want to edit it and fix my code but I can’t because the edit option does not exist in my profile under my post it has just delete option , I deleted my post instead.
 
محمد دهقانی #:
I want to edit it and fix my code but I can’t because the edit option does not exist in my profile under my post it has just delete option , I deleted my post instead.

you can create a new post with the fixed code.

Reason: