Too many orders opening when they shouldn't

 

Hello 

First ever post, and total novice in mql5.

i am coding a practice EA to learn the language and platform. I have placed the trade.buy after checking if any open postions, despite this conditional check the ea seems to just keep placing more orders.

Another weird thing that is happening is a few bar backs there seems to be objects indicating buy orders were placed in those historical bars.

hope someone can point me in the right direction.

here are some snapshots and the code:


#include <Trade\Trade.mqh>

// Create an instance of CTrade
CTrade trade;

bool HasOpenBuyPosition(const string symbol) {
    // Loop through all open positions
    for (int i = PositionsTotal() - 1; i >= 0; i--) {
        ulong ticket = PositionGetTicket(i);

        if (PositionSelect(ticket)) {
            // Check if the position is a buy position and matches the specified symbol
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY &&
                PositionGetString(POSITION_SYMBOL) == symbol) {
                return true;
            }
        }
    }
    return false;
}

void OpenBuyPosition(const string symbol, double lotSize) {
    double bid, ask;
    
    // Get current bid and ask prices
    if (!SymbolInfoDouble(symbol, SYMBOL_BID, bid) || !SymbolInfoDouble(symbol, SYMBOL_ASK, ask)) {
        Print("Failed to get bid/ask prices for symbol: ", symbol);
        return;
    }

    // Calculate stop loss and take profit based on bid and ask prices
    double stopLoss = bid - 50 * _Point;   // Example: 50 pips below current Bid price
    double takeProfit = ask + 100 * _Point;  // Example: 100 pips above current Ask price

    // Check if there is already an open buy position for the specified symbol
    if (!HasOpenBuyPosition(symbol)) {
        // Open a buy position
        if (!trade.Buy(lotSize, symbol, 0, stopLoss, takeProfit)) {
            Print("Failed to open buy position: ", trade.ResultRetcode());
        } else {
            Print("Buy position opened successfully.");
        }
    } else {
        Print("There is already an open buy position for symbol: ", symbol);
    }
}

void OnTick() {
    
    OpenBuyPosition(_Symbol, 0.1);
}

Files:
Capture.JPG  440 kb
Capture2.JPG  279 kb