Skip to content
The Chat Archive
llama-4-maverick-03-26-experimental· Meta LMArena Human Preference 140K

order close by opposite signal not work properly

  1. User

    order close by opposite signal not work properly

  2. Assistant

    The "order close by opposite signal" logic can be tricky, especially in MQL4 where order management and signal generation happen in separate steps. Let's dissect the current implementation and enhance it for reliability:

    Current Logic (Simplified):

    1. Check if there's an open order managed by this EA (MagicNumber match).
    2. If no open order:
      • If prediction > 0.50, open a BUY (OP_BUY).
      • If prediction < 0.50, open a SELL (OP_SELL).
    3. If there is an open order:
      • If it's a BUY (orderType == OP_BUY) and now prediction < 0.50 (opposite signal), close the order.
      • If it's a SELL (orderType == OP_SELL) and now prediction > 0.50 (opposite signal), close the order.

    Potential Issues:

    1. OrderSelect() Failure: If OrderSelect() fails for some reason (e.g., order ticket invalid, order not found), orderType remains -1, and the logic skips closing.
    2. Floating-Point Comparison: prediction < 0.50 or prediction > 0.50 might not behave as expected due to floating-point precision. E.g., 0.49999999 is technically < 0.50 but practically the same signal.
    3. Multiple Orders: If (for any reason) there are multiple open orders with the same MagicNumber (e.g., due to a bug or manual intervention), the current loop only closes the first one it finds. The rest remain open.
    4. Order Closure Errors: OrderClose() can fail (e.g., due to requotes, insufficient funds, server issues). The EA should handle this gracefully.

    Refactored & Robust Order Management Code:

    Replace the entire "Trading Logic" section in OnTick() with the following:

    // --- 3. Trading Logic ---
    int totalOrders = OrdersTotal();
    bool hasOpenBuy = false;
    bool hasOpenSell = false;
    
    // Step 1: Check existing open orders managed by this EA
    for (int i = 0; i < totalOrders; i++) {
       if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
          if (OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol()) {
             if (OrderType() == OP_BUY)  hasOpenBuy = true;
             if (OrderType() == OP_SELL) hasOpenSell = true;
          }
       } else {
          Print("Error selecting order #", i, ": ", GetLastError());
       }
    }
    
    // Step 2: Generate the current signal
    double prediction = ForwardPropagate(features);
    bool isBullishSignal = (prediction > 0.50 + 0.01); // Slight buffer for float precision
    bool isBearishSignal = (prediction < 0.50 - 0.01); // Slight buffer for float precision
    
    // Step 3: Close orders on opposite signal (prioritized)
    if (hasOpenBuy && isBearishSignal) {
       // Close all BUY orders (in case there are multiple)
       for (int i = totalOrders - 1; i >= 0; i--) { // Loop backwards to avoid index shifts
          if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
             if (OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol() && OrderType() == OP_BUY) {
                if (OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, Blue)) {
                   Print("Closed BUY order #", OrderTicket(), " due to opposite (bearish) signal.");
                } else {
                   Print("Failed to close BUY order #", OrderTicket(), ": ", GetLastError());
                }
             }
          }
       }
    }
    if (hasOpenSell && isBullishSignal) {
       // Close all SELL orders
       for (int i = totalOrders - 1; i >= 0; i--) {
          if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
             if (OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol() && OrderType() == OP_SELL) {
                if (OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, Blue)) {
                   Print("Closed SELL order #", OrderTicket(), " due to opposite (bullish) signal.");
                } else {
                   Print("Failed to close SELL order #", OrderTicket(), ": ", GetLastError());
                }
             }
          }
       }
    }
    
    // Step 4: Open new orders if no conflicting position exists
    if (!hasOpenBuy && isBullishSignal) {
       double buyPrice = Ask;
       if (OrderSend(Symbol(), OP_BUY, Lots, buyPrice, Slippage, 0, 0, "NN Buy", MagicNumber, 0, Green)) {
          Print("Opened BUY order at ", buyPrice);
       } else {
          Print("Error opening BUY order: ", GetLastError());
       }
    }
    if (!hasOpenSell && isBearishSignal) {
       double sellPrice = Bid;
       if (OrderSend(Symbol(), OP_SELL, Lots, sellPrice, Slippage, 0, 0, "NN Sell", MagicNumber, 0, Red)) {
          Print("Opened SELL order at ", sellPrice);
       } else {
          Print("Error opening SELL order: ", GetLastError());
       }
    }
    

    Changes Explained:

    1. Separate Flags for BUY/SELL Positions: Instead of just hasOpenOrder, we track hasOpenBuy and hasOpenSell. This lets us open the correct opposite order.
    2. Loop Backwards When Closing: When closing orders, we iterate for (int i = totalOrders - 1; i >= 0; i--). Why? If you close an order at index i, all higher-index orders shift down by 1. Looping backwards avoids skipping orders or indexing out of bounds.
    3. Buffer in Signal Comparison:
      • bool isBullishSignal = (prediction > 0.50 + 0.01);
      • bool isBearishSignal = (prediction < 0.50 - 0.01); This tiny buffer (0.01) prevents oscillations exactly at 0.50. You can adjust or remove it based on your strategy.
    4. Explicit Order Type Check: Before closing, we double-check OrderType() == OP_BUY (or OP_SELL). This ensures we don't accidentally close the wrong type due to any logic slip-ups.
    5. Error Handling: After OrderSelect(), OrderClose(), and OrderSend(), we print any errors. This helps diagnose issues in the log.
    6. Two-Stage Logic:
      • First, close any orders that need to be closed due to an opposite signal.
      • Then, if no conflicting order is open, open a new one.

    Testing Suggestions:

    1. Enable Visual Mode in Strategy Tester: Run the EA in MT4's Strategy Tester (Ctrl+R), check "Visual Mode", and use a recent 2-3 month period on M1, M5, or H1. Observe:
      • Does the EA open/close orders correctly on signal flips?
      • Are there any error messages in the "Experts" tab?
    2. Print Statements: Add more Print() statements if needed. For example:
      • Print("Prediction: ", DoubleToString(prediction, 4), ", isBullishSignal: ", isBullishSignal, ", isBearishSignal: ", isBearishSignal);
      • Print("hasOpenBuy: ", hasOpenBuy, ", hasOpenSell: ", hasOpenSell);
    3. Single-Step Through Ticks: In Visual Mode, you can pause and step through each tick. Verify the logic flow.

    By structuring the code this way, we ensure that:

    • Opposite signals reliably close existing orders.
    • New orders are only opened if there's no conflicting position.
    • We handle multiple open orders gracefully.
    • Any errors during OrderSelect, OrderClose, or OrderSend are logged for debugging.

    This should resolve the "order close by opposite signal not working properly" issue. If problems persist, the detailed print logs will help pinpoint the exact step where the logic diverges from expectations. Happy trading!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.