OrderSend failed 4756

 

 I am creating a ea using a prediction method for the open,close,high,low price during an hour (not included here). When creating market orders or using buy limit/stop orders I keep on getting failed orders. Is something off with my code or are there any things I am not seeing?



 

 if (predictedOpen < predictedClose) {

            // Place a market Buy order if the predicted close is higher
            PlaceOrder(ORDER_TYPE_BUY);
        } else if (predictedOpen > predictedClose) {
            // Place a market Sell order if the predicted close is lower
            PlaceOrder(ORDER_TYPE_SELL);
        }
        
        // Update last order time
        lastOrderTime = TimeCurrent();
    }
}

//+------------------------------------------------------------------+
//| Place order function                                             |
//+------------------------------------------------------------------+
void PlaceOrder(int orderType) {
    double price, sl, tp;

    // Get the current prices
    double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

    // Determine the price, stop loss, and take profit based on order type
    if (orderType == ORDER_TYPE_BUY) {
        price = ask; // Buy at the current ask price
        sl = ask-100*pointSize; // Set Stop Loss below the predicted low
        tp = ask+100*pointSize; // Set Take Profit at the predicted close

        Print("Market Order: BUY - Predicted Close: ", predictedClose, ", Price: ", price, ", SL: ", sl, ", TP: ", tp);

    } else if (orderType == ORDER_TYPE_SELL) {
        price = bid; // Sell at the current bid price
        sl = bid+100*pointSize; // Set Stop Loss above the predicted high
        tp = bid-100*pointSize; // Set Take Profit at the predicted close

        Print("Market Order: SELL - Predicted Close: ", predictedClose, ", Price: ", price, ", SL: ", sl, ", TP: ", tp);

    } else {
        Print("Invalid order type provided.");
        return; // Exit if order type is not valid
    }

    // Ensure stop loss and take profit are set correctly
    if (fabs(price - sl) < SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * pointSize) {
        Print("Error: SL too close to the price.");
        return;
    }

    if (fabs(price - tp) < SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * pointSize) {
        Print("Error: TP too close to the price.");
        return;
    }

    // Prepare order request
    MqlTradeRequest request;
    MqlTradeResult result;

    request.action = TRADE_ACTION_DEAL; // For market orders
    request.symbol = _Symbol;
    request.volume = 0.01; // Lot size (adjust as necessary)
    request.type = orderType;
    request.price = price; // Current market price
    request.sl = sl; // Stop Loss
    request.tp = tp; // Take Profit
    request.magic = 0; // Magic number (can be customized)
    request.comment = "Linear Regression EA"; // Order comment

    // Check if volume is valid
    double minVolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
    double maxVolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    double stepVolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);

    if (request.volume < minVolume || request.volume > maxVolume || fmod(request.volume, stepVolume) != 0) {
        Print("Error: Invalid trade volume. Min:", minVolume, " Max:", maxVolume);
        return;
    }

    // Send order
    if (!OrderSend(request, result)) {
        Print("OrderSend failed with error: ", GetLastError());
    } else {
        Print("Order successfully placed. Ticket number: ", result.order);
    }
}

 
  1.         price = ask; // Buy at the current ask price
            sl = ask-100*pointSize; // Set Stop Loss below the predicted low
            tp = ask+100*pointSize; // Set Take Profit at the predicted close
    

    You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

    3. Prices (open, SL, and TP) must be a multiple of ticksize. Using Point means code breaks on 4 digit brokers (if any still exists), exotics (e.g. USDZAR where spread is over 500 points), and metals. Compute what a logical PIP is and use that, not points.
                How to manage JPY pairs with parameters? - MQL4 programming forum (2017)
                Slippage defined in index points - Expert Advisors and Automated Trading - MQL5 programming forum (2018)

    4. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

      Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
      My GBPJPY shows average spread = 26 points, average maximum spread = 134.
      My EURCHF shows average spread = 18 points, average maximum spread = 106.
      (your broker will be similar).
                Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

  2. There is no need to create pending orders in code.

    1. The pending has the slight advantage, A) you are closer to the top of the queue (filled quicker), B) there's no round trip network delay (filled quicker.)

      Don't worry about it unless you're scalping M1 or trading news.

    2. Humans can't watch the screen 24/7, so they use pending orders; EAs can, so no need for pending orders, have it wait until the market reaches the trigger price and just open an order.