issue with alot of trade being taken in single entry condition

 

hi everyone!!


a lot of trades is being taken when condition met but I want only one trade to be taken an manged then once closed look for another trade.  can you give me a guess where im having issue??


//+------------------------------------------------------------------+
//|                             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

#include <Trade\Trade.mqh>  // Include the trade class

// Input parameters
input int EMA_Fast_Period = 20;
input int EMA_Medium_Period = 50;
input int EMA_Slow_Period = 100;
input double Lot_Size = 0.01;
input double Trailing_Stop_Pips = 10.0; // Trailing stop of 10 pips

// 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[];

// Instance of CTrade class
CTrade trade;
#define MAGIC_NUMBER 123456 // Use any unique number as the magic number

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    // 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);

    // Check if handles are created successfully
    if (EMA_Fast_Handle == INVALID_HANDLE ||
        EMA_Medium_Handle == INVALID_HANDLE ||
        EMA_Slow_Handle == INVALID_HANDLE)
    {
        Print("Error creating EMA handles");
        return(INIT_FAILED);
    }

    // Initialize EMA buffers with enough space
    ArraySetAsSeries(EMA_Fast_Buffer, true);
    ArraySetAsSeries(EMA_Medium_Buffer, true);
    ArraySetAsSeries(EMA_Slow_Buffer, true);

    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    // No cleanup needed
}

void OnTick()
{
    // Check if there are any open positions for the symbol with our magic number
    bool openTradeExists = false;
    ulong positionTicket = -1; // To store the ticket of the open position
    for (int i = 0; i < PositionsTotal(); i++)
    {
        if (PositionGetSymbol(i) == _Symbol && PositionGetInteger(POSITION_MAGIC) == MAGIC_NUMBER)
        {
            openTradeExists = true;
            positionTicket = PositionGetInteger(POSITION_TICKET);
            break;
        }
    }

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

    // Copy EMA values to the buffers
    if (CopyBuffer(EMA_Fast_Handle, 0, 0, 2, EMA_Fast_Buffer) <= 0 ||
        CopyBuffer(EMA_Medium_Handle, 0, 0, 2, EMA_Medium_Buffer) <= 0 ||
        CopyBuffer(EMA_Slow_Handle, 0, 0, 2, EMA_Slow_Buffer) <= 0)
    {
        Print("Failed to copy EMA buffers");
        return;
    }

    // Get the EMA values at index 0 (current bar) and index 1 (previous bar) from the buffers
    emaFastValue = EMA_Fast_Buffer[0];
    emaMediumValue = EMA_Medium_Buffer[0];
    emaSlowValue = EMA_Slow_Buffer[0];

    emaFastValuePrev = EMA_Fast_Buffer[1];
    emaMediumValuePrev = EMA_Medium_Buffer[1];
    emaSlowValuePrev = EMA_Slow_Buffer[1];

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

    // Entry condition: 20 EMA crosses above 50 EMA and 100 EMA from below
    if (!openTradeExists &&
        emaFastValuePrev < emaMediumValuePrev && emaFastValuePrev < emaSlowValuePrev &&
        emaFastValue > emaMediumValue && emaFastValue > emaSlowValue)
    {
        Print("Entry condition met. Placing buy order...");

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

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

        // Place the buy order
        if (trade.Buy(Lot_Size, NULL, Ask, 0.0, 0.0, "EMA Bot Buy Order"))
        {
            Print("Buy order placed successfully");
        }
        else
        {
            Print("Failed to place buy order. Error: ", GetLastError());
        }
    }

    // Exit condition: 20 EMA crosses below 50 EMA from above or additional checks
    if (openTradeExists &&
        ((emaFastValuePrev > emaMediumValuePrev && emaFastValue < emaMediumValue) ||
         (emaFastValuePrev > emaSlowValuePrev && emaFastValue < emaSlowValue)))
    {
        Print("Exit condition met. Closing buy order...");

        // Close the buy order
        if (trade.PositionClose(positionTicket))
        {
            Print("Position closed successfully");
            openTradeExists = false; // Reset the flag since the position is closed
        }
        else
        {
            Print("Failed to close position. Error: ", GetLastError());
        }
    }

    // Trailing stop logic
    if (openTradeExists)
    {
        double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        double trailingStop = currentPrice - Trailing_Stop_Pips * _Point;

        // Get the current stop loss level of the position
        double currentStopLoss = PositionGetDouble(POSITION_SL);

        // Update the stop loss if the trailing stop is higher
        if (trailingStop > currentStopLoss)
        {
            if (!trade.PositionModify(positionTicket, trailingStop, 0))
            {
                Print("Failed to modify position for trailing stop. Error: ", GetLastError());
            }
            else
            {
                Print("Trailing stop updated to: ", trailingStop);
            }
        }
    }
}


thank you for your help guys!! 

 
Asif nawab: a lot of trades is being taken when condition met but I want only one trade to be taken an manged then once closed look for another trade.  can you give me a guess where im having issue??
        if (PositionGetSymbol(i) == _Symbol && PositionGetInteger(POSITION_MAGIC) == MAGIC_NUMBER)

Where do you open a trade with that MN?

 
Set the magic number in OnInit. I don't think you should be setting a flag to true inside this loop. 

Instead of this if(!openTradesExist) condition further down the script, you should do:  if(PositionsTotal()==0)
 
วิลเลียม โรเดอร์ # :

หลังจากนั้นจะเปิดกับ MN ที่ไหน?

5