🚀 AI One-Click Generation of mql4 Strategy Code

How to Create a Pre-Flight Checklist for Your Mql4 EA for Safe Trading

mql4 | Published on: 2025/12/12
The following content is generated by EasyQuant .

Problem Description

How can I make my trading robot check if it's connected to the server and allowed to trade before it tries to open an order?

Solution

To ensure your trading robot (Expert Advisor) only attempts to trade when it is safe to do so, you should implement a check that verifies the server connection, the account status, and the terminal/EA permissions.

Here is the complete MQL4 code structure implementing a robust CheckTradingStatus() function.

MQL4 Implementation

//+------------------------------------------------------------------+
//|                                            CheckTradeStatus.mq4  |
//|                        Copyright 2023, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   // 1. Define your entry signal logic here
   bool buySignal = false; // Placeholder for your strategy logic
   
   // Example: Simple condition for demonstration
   if(OrdersTotal() == 0) buySignal = true; 

   // 2. Before executing any trade, call the check function
   if(buySignal)
   {
      if(IsTradingAllowedAndConnected())
      {
         // It is safe to trade
         int ticket = OrderSend(Symbol(), OP_BUY, 0.1, Ask, 3, 0, 0, "My EA Order", 12345, 0, clrGreen);
         
         if(ticket < 0)
         {
            Print("OrderSend failed with error #", GetLastError());
         }
      }
      else
      {
         // Optional: Log that a signal was missed due to restrictions
         Print("Signal detected but trading is currently disabled or disconnected.");
      }
   }
}

//+------------------------------------------------------------------+
//| Custom Function: Checks Connection and Permissions               |
//+------------------------------------------------------------------+
bool IsTradingAllowedAndConnected()
{
   // 1. Check connection to the trade server
   if(!IsConnected())
   {
      Print("Error: No connection to the trade server.");
      return(false);
   }

   // 2. Check if the Account allows trading (e.g., not an Investor password)
   if(!AccountInfoInteger(ACCOUNT_TRADE_ALLOWED))
   {
      Print("Error: Trading is not allowed for this specific account (Check if logged in with Investor password).");
      return(false);
   }

   // 3. Check if the Terminal and the EA allow trading
   // IsTradeAllowed() returns true if:
   // a) The "AutoTrading" button in the terminal is ON
   // b) The "Allow live trading" checkbox in the EA properties is CHECKED
   // c) The trade execution thread is free (not busy)
   if(!IsTradeAllowed())
   {
      // We can refine the error message to be more helpful
      if(IsTradeContextBusy())
      {
         Print("Warning: Trade context is busy. The EA will retry on the next tick.");
      }
      else
      {
         Print("Error: Trading disabled. Please check the 'AutoTrading' button and EA 'Common' properties.");
      }
      return(false);
   }

   // 4. (Optional) Check if the market is open for this specific symbol
   // This prevents Error 132 (Market is closed)
   if(!IsTradeAllowed(Symbol(), TimeCurrent()))
   {
       Print("Error: Market is closed for symbol ", Symbol());
       return(false);
   }

   // All checks passed
   return(true);
}

Explanation of Functions Used

  1. IsConnected():

    • Returns true if the terminal is successfully connected to the broker's server.
    • Returns false if there is no internet connection or the server is down.
  2. AccountInfoInteger(ACCOUNT_TRADE_ALLOWED):

    • Checks the account rights specifically. This is crucial because you might be connected, but logged in with a "Read-Only" (Investor) password, which forbids trading.
  3. IsTradeAllowed() (Void parameters):

    • This is the most important check for an EA. It verifies three things simultaneously:
      • Is the AutoTrading button at the top of the terminal enabled?
      • Is the "Allow live trading" checkbox enabled in the specific EA's settings (F7 menu)?
      • Is the trading thread free? (MQL4 is single-threaded for trading; if another EA is trading at the exact same millisecond, this returns false).
  4. IsTradeAllowed(Symbol(), TimeCurrent()):

    • This specific overload checks if the market is currently open for the specific symbol you are trying to trade.

Q&A

Q: What happens if IsTradeContextBusy() returns true?
A: It means the terminal is currently processing another trade operation (perhaps from another EA or a manual trade). In MQL4, you cannot send two orders simultaneously. The code provided simply returns false, meaning the EA will skip this specific tick and try again on the next tick when the context is likely free.

Q: Does IsConnected() guarantee my order will execute?
A: No. IsConnected() only confirms a data link to the server. Order execution depends on liquidity, correct prices, stop levels, and margin requirements. You must still handle the return value of OrderSend() to check for execution errors.

Q: Why check AccountInfoInteger if I already check IsTradeAllowed?
A: IsTradeAllowed checks your software permissions (buttons and checkboxes). AccountInfoInteger checks your broker permissions. It is possible to have AutoTrading turned on but be logged into an account that has been disabled by the broker or is in "Investor" mode. Checking both covers all bases.