Coding Issue: Repeated Trades without Closure at Inappropriate Times and Increasing Trade Ticket Numbers


Hello everyone, I'm facing an issue with my trading script that I need your help with. My problem is that the script keeps opening repeated trades without closing them properly, especially during inappropriate times. Another concern is that the trade ticket numbers are increasing inexplicably."

"I'm using various functions for trading within my code, all of which I've ensured are properly defined and there's no interference among them. The main function executes trading based on specific time conditions, yet despite all settings and conditions, these repeated trades keep executing."

"Has anyone ever encountered such an issue? Does anyone have any idea where the problem might stem from? I'd greatly appreciate it if you could share your experiences and guidance with me."

"Thank you for your assistance."

#include <Trade\Trade.mqh>
CTrade trade;

bool IsGoodTimeToTrade()
    int GMTStartHour = 8, GMTEndHour = 22;
    MqlDateTime gmtTime;
    if (gmtTime.hour >= GMTStartHour && gmtTime.hour <= GMTEndHour)
        return true;
        return false;

void OnTick()
    if (IsGoodTimeToTrade())
        double low1 = iLow(_Symbol, 0, 0);
        double low2 = iLow(_Symbol, 0, 1);
        double low3 = iLow(_Symbol, 0, 2);
        double Ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
        double Bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
        double MovingAvrageArray[];
        int MovingAvrageDefinition = iMA(_Symbol,PERIOD_CURRENT,40,0,MODE_SMA,PRICE_CLOSE);
        double myMovigAvrageValue = MovingAvrageArray[0];
        double lowestLow;
        lowestLow = MathMin(low1, MathMin(low2, low3));
        if (PositionsTotal() < 1 && lowestLow > myMovigAvrageValue)
            double stopLoss = lowestLow - 100 * _Point;
            double takeProfit = lowestLow + 150 * _Point;
            trade.Buy(0.1, _Symbol, Ask, stopLoss, takeProfit);
            Comment("Buy order placed.");
        Comment("Not a good time to trade.");
  1. Don't open a new handle on every tick! Your PC or at least the terminal will crash.
  2. Look her how it is done properly:
  3. Maybe you should learn MQL5:
  4. Learn to debug your code:
  5.  "Bear in mind there's virtually nothing that hasn't already been programmed for MT4/MT5 and is ready for you  - copy & paste the fastest form to code.
        => Search in the articles:
        => Search in the codebase:
        => Search in general: or via Google with: " .." (forgives misspelling)

Dokumentation zu MQL5: Technische Indikatoren / iMA
Dokumentation zu MQL5: Technische Indikatoren / iMA
iMA - Technische Indikatoren - Nachschlagewerk MQL5 - Nachschlagewerk über die Sprache des algothitmischen/automatischen Handels für MetaTrader 5