why im not getting profit in this strategy

 

hi everyone,


i hope you are doing well in trading.


can you guys please help me why this code is not giving me any profit?? im using 20 50 100 ema cross over strategy.


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

//|                                                         EMA Bot  |

//|                                      Copyright 2024, YourName    |

//|                                       https://www.yourwebsite.com|

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

#property strict


// Input parameters

input int EMA_Fast_Period = 20;

input int EMA_Medium_Period = 50;

input int EMA_Slow_Period = 100;

input double Risk_Reward_Ratio = 3.0; // 3% reward for 1% risk

input double Lot_Size = 0.01;

input double StopLoss_Factor = 2.0; // Factor to increase stop loss

input double TakeProfit_Factor = 2.0; // Factor to increase take profit

input double Min_Distance = 20.0; // Minimum distance between stop loss and take profit


// EMA variables

double EMA_Fast, EMA_Medium, EMA_Slow;


// EMA calculation variables

double EMA_Fast_Buffer[], EMA_Medium_Buffer[], EMA_Slow_Buffer[];


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

//| Function to calculate Simple Moving Average                      |

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

double SimpleMovingAverage(double &buffer[])

{

    double sum = 0.0;

    for (int i = 0; i < ArraySize(buffer); i++)

    {

        sum += buffer[i];

    }

    return sum / ArraySize(buffer);

}


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

//| Function to calculate EMA                                       |

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

void CalculateEMA(double &buffer[], int period, double price, double &result)

{

    // Add the current price to the buffer

    ArrayResize(buffer, ArraySize(buffer) + 1);

    buffer[ArraySize(buffer) - 1] = price;


    // Calculate smoothing factor

    double smoothingFactor = 2.0 / (period + 1);


    // Calculate EMA

    if (ArraySize(buffer) < period)

    {

        // If there are not enough elements in the buffer, use simple moving average

        result = SimpleMovingAverage(buffer);

    }

    else if (ArraySize(buffer) == period)

    {

        // If the buffer size is equal to the period, initialize EMA with SMA

        result = SimpleMovingAverage(buffer);

    }

    else

    {

        // Calculate EMA based on previous EMA value and current price

        result = (price - result) * smoothingFactor + result;

    }

}


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

//| Expert initialization function                                   |

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

int OnInit()

{

    // Initialize EMA buffers

    ArrayResize(EMA_Fast_Buffer, 0);

    ArrayResize(EMA_Medium_Buffer, 0);

    ArrayResize(EMA_Slow_Buffer, 0);


    return(INIT_SUCCEEDED);

}


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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

{

    // Cleanup code here

}


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

//| Expert tick function                                            |

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

void OnTick()

{

    Print("OnTick() function is being executed.");


    // Get the current Ask price

    double Ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);


    // Calculate EMAs

    CalculateEMA(EMA_Fast_Buffer, EMA_Fast_Period, Ask, EMA_Fast);

    CalculateEMA(EMA_Medium_Buffer, EMA_Medium_Period, Ask, EMA_Medium);

    CalculateEMA(EMA_Slow_Buffer, EMA_Slow_Period, Ask, EMA_Slow);


    // Print EMA prices

    Print("EMA Fast: ", EMA_Fast, ", EMA Medium: ", EMA_Medium, ", EMA Slow: ", EMA_Slow);


    // Entry condition: EMA 20 crosses above EMA 50 and EMA 100

    if (EMA_Fast > EMA_Medium && EMA_Fast > EMA_Slow && EMA_Medium > EMA_Slow)

    {

        Print("Entry condition met. Placing buy order...");


        // Get minimum stop level

        double minStopLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * _Point;


        // Calculate risk and reward levels

        double risk = EMA_Medium - Ask; // Calculate the risk (distance between 50 EMA and Ask)

        double reward = risk * Risk_Reward_Ratio; // Set reward as per risk-reward ratio


        // Increase stop loss and take profit levels by a factor

        risk *= StopLoss_Factor;

        reward *= TakeProfit_Factor;


        double stopLoss = NormalizeDouble(Ask - risk, _Digits); // Set stop loss below the current Ask price

        double takeProfit = NormalizeDouble(Ask + reward, _Digits); // Set take profit above the current Ask price


        // Calculate the minimum distance between stop loss and take profit

        double minDistance = Min_Distance * _Point; 


        // Ensure stopLoss and takeProfit are not equal or invalid

        if (stopLoss >= takeProfit || (takeProfit - stopLoss) < minDistance)

        {

            Print("Stop loss price is higher than or equal to take profit price, or minimum distance not met. Adjusting...");

            stopLoss = NormalizeDouble(Ask - minDistance / 2.0, _Digits); // Adjust stop loss

            takeProfit = NormalizeDouble(Ask + minDistance / 2.0, _Digits); // Adjust take profit

        }


        // Ensure stopLoss and takeProfit are not equal or invalid

        if (stopLoss >= Ask || takeProfit <= Ask)

        {

            Print("Calculated stop loss: ", stopLoss, ", take profit: ", takeProfit, ". Invalid stops.");

            return;

        }


        // Prepare trade request

        MqlTradeRequest request;

        ZeroMemory(request);

        request.action = TRADE_ACTION_DEAL; // Immediate order execution

        request.symbol = _Symbol;

        request.volume = Lot_Size;

        request.price = Ask;

        request.sl = stopLoss;

        request.tp = takeProfit;

        request.magic = 123456; // Unique identifier for the bot's trades

        request.type = ORDER_TYPE_BUY; // Buy order


        // Print trade request details

        Print("Sending buy order request...");

        Print("Ask: ", Ask, ", StopLoss: ", stopLoss, ", TakeProfit: ", takeProfit);


        // Send trade request

        MqlTradeResult result;

        ZeroMemory(result);

        if (OrderSend(request, result))

        {

            Print("Buy order placed successfully");

        }

        else

        {

            Print("Error placing buy order: ", GetLastError());

        }

    }

    else

    {

        Print("Entry condition not met. No action taken.");

    }

}



Regards,

MQL5 forum
MQL5 forum
  • www.mql5.com
MQL5: Forum on automated trading systems and strategy testing
 
What is the real question?

Is the EA not working according to your strategy or it's simply a loosing strategy (as it's easily imaginable)?
 
Asif nawab: hi everyone,

i hope you are doing well in trading.

can you guys please help me why this code is not giving me any profit?? im using 20 50 100 ema cross over strategy.

I edited your post this time. Next time use the CODE button (or Alt+S)! (For large amounts of code, attach it.)
      General rules and best pratices of the Forum. - General - MQL5 programming forum #25 (2019)
          Messages Editor
      Forum rules and recommendations - General - MQL5 programming forum (2023)

 
Hi guys i want to know why this is not giving me any profit

 
Khanya Dyakalashe #:
Hi guys i want to know why this is not giving me any profit

did u optimized and back tested before putting it on live or demo?
 
Fabio Cavalloni #:
What is the real question?

Is the EA not working according to your strategy or it's simply a loosing strategy (as it's easily imaginable)?
it seem like strategy is not working because when I test it in mt5 visual mode I cannot see EMA indicators plus there are many orders being placed par minutes so seems like there is something wrong in my strategy can you help me finding this issue please?
 
You don't see MA into visual tester because you have not used indicators but coded MA calculations inside EA (very bad approach)

For multiple orders placed within few ticks into the same candle, adding a way to check trading signals once per bar can be a good idea in most of cases.
 
Fabio Cavalloni #:
You don't see MA into visual tester because you have not used indicators but coded MA calculations inside EA (very bad approach)

For multiple orders placed within few ticks into the same candle, adding a way to check trading signals once per bar can be a good idea in most of cases.
okay, i have fix the indicators issue but now it is not placing any buy order even though i can see that the ema 20 is crossing 50 and 100 ema here is the updated code:


//+------------------------------------------------------------------+
//|                             EMA Bot |
//|                   Copyright 2024, YourName  |
//|                    https://www.yourwebsite.com|
//+------------------------------------------------------------------+
#property strict
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_color1 Blue
#property indicator_color2 Red
#property indicator_color3 Green

// Input parameters
input int EMA_Fast_Period = 20;
input int EMA_Medium_Period = 50;
input int EMA_Slow_Period = 100;
input double Risk_Reward_Ratio = 3.0; // 3% reward for 1% risk
input double Lot_Size = 0.01;
// Removed StopLoss_Factor as stop-loss is directly placed at EMA price
input double TakeProfit_Factor = 2.0; // Factor to increase take profit
input double Min_Distance = 20.0; // Minimum distance between stop loss and take profit
// EMA handles
int EMA_Fast_Handle, EMA_Medium_Handle, EMA_Slow_Handle;

// EMA calculation variables
double EMA_Fast_Buffer[], EMA_Medium_Buffer[], EMA_Slow_Buffer[];

//+------------------------------------------------------------------+
//| Function to calculate Simple Moving Average           |
//+------------------------------------------------------------------+
double SimpleMovingAverage(double &buffer[])
{
  double sum = 0.0;
  for (int i = 0; i < ArraySize(buffer); i++)
  {
    sum += buffer[i];
  }
  return sum / ArraySize(buffer);
}

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    // Determine the maximum period among the three EMAs
    int maxPeriod = MathMax(EMA_Fast_Period, MathMax(EMA_Medium_Period, EMA_Slow_Period));

    // Initialize EMA handles
    EMA_Fast_Handle = iMA(_Symbol, 0, EMA_Fast_Period, 0, MODE_EMA, PRICE_CLOSE);
    EMA_Medium_Handle = iMA(_Symbol, 0, EMA_Medium_Period, 0, MODE_EMA, PRICE_CLOSE);
    EMA_Slow_Handle = iMA(_Symbol, 0, EMA_Slow_Period, 0, MODE_EMA, PRICE_CLOSE);

    // Initialize EMA buffers with enough space
    ArrayResize(EMA_Fast_Buffer, maxPeriod);
    ArrayResize(EMA_Medium_Buffer, maxPeriod);
    ArrayResize(EMA_Slow_Buffer, maxPeriod);
   
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    // Cleanup code here
}

void OnTick()
{
    Print("OnTick() function is being executed.");

    // Get the current Ask price
    double Ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

    // Declare variables to store EMA values
    double emaFastValue, emaMediumValue, emaSlowValue;

    // Copy EMA values to the buffers
    CopyBuffer(EMA_Fast_Handle, 0, 0, 1, EMA_Fast_Buffer);
    CopyBuffer(EMA_Medium_Handle, 0, 0, 1, EMA_Medium_Buffer);
    CopyBuffer(EMA_Slow_Handle, 0, 0, 1, EMA_Slow_Buffer);

    // Get the EMA values at index 0 from the buffers
    emaFastValue = EMA_Fast_Buffer[0];
    emaMediumValue = EMA_Medium_Buffer[0];
    emaSlowValue = EMA_Slow_Buffer[0];

    // Print EMA prices
    Print("EMA Fast: ", emaFastValue, ", EMA Medium: ", emaMediumValue, ", EMA Slow: ", emaSlowValue);

    // Entry condition: EMA 20 crosses above EMA 50 and EMA 100 in the current tick,
    // and EMA 20 was below both EMA 50 and EMA 100 in the previous tick
    if (emaFastValue > emaMediumValue && emaFastValue > emaSlowValue &&
        ArraySize(EMA_Fast_Buffer) > 1 && ArraySize(EMA_Medium_Buffer) > 1 && ArraySize(EMA_Slow_Buffer) > 1 &&
        EMA_Fast_Buffer[1] < EMA_Medium_Buffer[1] && EMA_Fast_Buffer[1] < EMA_Slow_Buffer[1])
    {
        Print("Entry condition met. Placing buy order...");

        // Get minimum stop level
        double minStopLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * _Point;

        // Set stop loss at EMA 50
        double stopLoss = NormalizeDouble(emaMediumValue, _Digits);

        // Calculate reward level (take profit)
        double reward = (emaMediumValue - Ask) * Risk_Reward_Ratio;

        // Set take profit double the amount of EMA 50
        double takeProfit = NormalizeDouble(emaMediumValue + reward, _Digits);

        // Calculate the minimum distance between stop loss and take profit
        double minDistance = Min_Distance * _Point; 

        // Ensure stopLoss and takeProfit are not equal or invalid
        if (stopLoss >= takeProfit || (takeProfit - stopLoss) < minDistance)
        {
            Print("Stop loss price is higher than or equal to take profit price, or minimum distance not met. Adjusting...");
            stopLoss = NormalizeDouble(Ask - minDistance / 2.0, _Digits); // Adjust stop loss
            takeProfit = NormalizeDouble(Ask + minDistance / 2.0, _Digits); // Adjust take profit
        }

        // Ensure stopLoss and takeProfit are not equal or invalid
        if (stopLoss >= Ask || takeProfit <= Ask)
        {
            Print("Calculated stop loss: ", stopLoss, ", take profit: ", takeProfit, ". Invalid stops.");
            return;
        }

        // Prepare trade request
        MqlTradeRequest request;
        ZeroMemory(request);
        request.action = TRADE_ACTION_DEAL; // Immediate order execution
        request.symbol = _Symbol;
        request.volume = Lot_Size;
        request.price = Ask;
        request.sl = stopLoss;
        request.tp = takeProfit;
        request.magic = 123456; // Unique identifier for the bot's trades
        request.type = ORDER_TYPE_BUY; // Buy order

        // Print trade request details
        Print("Sending buy order request...");
        Print("Ask: ", Ask, ", StopLoss: ", stopLoss, ", TakeProfit: ", takeProfit);

        // Send trade request
        MqlTradeResult result;
        ZeroMemory(result);
        if (OrderSend(request, result))
        {
            Print("Buy order placed successfully");
        }
        else
        {
            Print("Error placing buy order: ", GetLastError());
        }
    }
    else
    {
        Print("Entry condition not met. No action taken.");
    }
}
 
Your arrays at index 1 are emtpy.

You copied buffers starting from shift 0 for 1 value, it mean you only have [0] value.