return value of 'OrderSelect' should be checked | need help on this code error

 
//+------------------------------------------------------------------+
//|                                             sma9ema45crosstp.mq4 |
//|                                                           Zubair |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
// Expert Advisor parameters
extern int fastMA = 9;             // Period for the fast moving average
extern int slowMA = 45;            // Period for the slow moving average
extern double lotSize = 0.05;       // Fixed lot size for trades
extern int takeProfit = 200;       // Take profit distance in pips

// Global variables
int maCrossOver = 0;                // Variable to store the moving average crossover signal

// Initialization function
int init()
{
    return(0);
}

// Deinitialization function
int deinit()
{
    return(0);
}

// Entry point function
int start()
{
    // Calculate the moving averages
    double fastMAValue = iMA(NULL, 0, fastMA, 0, MODE_SMA, PRICE_CLOSE, 0);
    double slowMAValue = iMA(NULL, 0, slowMA, 0, MODE_EMA, PRICE_CLOSE, 0);

    // Determine the moving average crossover signal
    if (fastMAValue > slowMAValue)
    {
        maCrossOver = 1; // Fast MA above slow MA (bullish signal)
    }
    else if (fastMAValue < slowMAValue)
    {
        maCrossOver = -1; // Fast MA below slow MA (bearish signal)
    }
    else
    {
        maCrossOver = 0; // No crossover
    }

    // Open trades based on the crossover signal
    if (maCrossOver > 0 && OrdersTotal() == 0)
    {
        // Calculate take profit price
        double takeProfitPrice = Ask + takeProfit * Point;

        // Open a buy trade with take profit
        int ticket = OrderSend(Symbol(), OP_BUY, lotSize, Ask, 0, 0, takeProfitPrice, "Buy Order", 0, 0, Green);
        if (ticket > 0)
        {
            // Trade opened successfully
            Print("Buy trade opened with ticket: ", ticket);
        }
        else
        {
            // Failed to open trade
            Print("Failed to open buy trade. Error code: ", GetLastError());
        }
    }
    else if (maCrossOver < 0 && OrdersTotal() == 0)
    {
        // Calculate take profit price
        //double takeProfitPrice = Bid - takeProfit * Point;


        // Open a sell trade with take profit
  //     int ticket = OrderSend(Symbol(), OP_SELL, lotSize, Bid, 0, 0, takeProfitPrice, "", 0, 0, clrRed);

        if (ticket > 0)
        {
            // Trade opened successfully
            Print("Sell trade opened with ticket: ", ticket);
        }
        else
        {
            // Failed to open trade
            Print("Failed to open sell trade. Error code: ", GetLastError());
        }
    }

    return(0);
}
         
         
         void OnTick()
{
    // Calculate the SMA and EMA values
    double sma9 = iMA(NULL, 0, 9, 0, MODE_SMA, PRICE_CLOSE, 0);
    double ema45 = iMA(NULL, 0, 45, 0, MODE_EMA, PRICE_CLOSE, 0);

    // Check for a negative crossover
    if (sma9 < ema45)
    {
        // Close all buy orders
        for (int i = OrdersTotal() - 1; i >= 0; i--)
        {
            if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
            {
                if (OrderType() == OP_BUY)
                {
                    OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 0, Red);
                }
            }
        }
    }
}


Discover new MetaTrader 5 opportunities with MQL5 community and services
Discover new MetaTrader 5 opportunities with MQL5 community and services
  • 2023.07.12
  • www.mql5.com
MQL5: language of trade strategies built-in the MetaTrader 5 Trading Platform, allows writing your own trading robots, technical indicators, scripts and libraries of functions
 

It is OrderClose that needs to be checked. OrderSelect is already checked.

note: your code can run with warnings.

 
Abrar86:
  1. int start()
    {
        ⋮
    }
             
             
             void OnTick()
    {

    You can have the old event handlers (start) or the new (OnTick), but not both.

    You should stop using the old event handlers (init, start, deinit) and IndicatorCounted() and start using new event handlers (OnInit, OnTick/OnCalculate, OnDeinit).
              Event Handling Functions - MQL4 Reference
              How to do your lookbacks correctly - MQL4 programming forum #9-14 & #19 (2016)

  2.                     OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 0, Red);

    Check your return codes, and report your errors (including market prices and your variables). Don't look at GLE/LE unless you have an error. Don't just silence the compiler (MT5/MT4+strict), it is trying to help you.

  3. MT4: You can use OrderClosePrice() instead of Bid/Ask and be direction independent — no need to check order type to get the close price.

  4.     if (maCrossOver > 0 && OrdersTotal() == 0)
            for (int i = OrdersTotal() - 1; i >= 0; i--)
            {
                if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
                {
                    if (OrderType() == OP_BUY)
                    {
                        OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 0, Red);

    Magic number only allows an EA to identify its trades from all others. Using OrdersTotal/OrdersHistoryTotal (MT4) or PositionsTotal (MT5), directly and/or no Magic number/symbol filtering on your OrderSelect / Position select loop means your code is incompatible with every EA (including itself on other charts and manual trading.)
              Symbol Doesn't equal Ordersymbol when another currency is added to another seperate chart . - MQL4 programming forum (2013)
              PositionClose is not working - MQL5 programming forum (2020)
              MagicNumber: "Magic" Identifier of the Order - MQL4 Articles (2006)
              Orders, Positions and Deals in MetaTrader 5 - MQL5 Articles (2011)
              Limit one open buy/sell position at a time - General - MQL5 programming forum (2022)

    You need one Magic Number for each symbol/timeframe/strategy.
         Trade current timeframe, one strategy, and filter by symbol requires one MN.
         If trading multiple timeframes, and filter by symbol requires use a range of MN (base plus timeframe).
              Why are MT5 ENUM_TIMEFRAMES strange? - General - MQL5 programming forum - Page 2 #11 (2020)