MQL4: What Is the Minimum Stop Loss and How Does It Work?

Trading automation using Expert Advisors (EAs) in MQL4 requires precise control over order management, and the stop loss is a cornerstone of effective risk control. While setting a stop loss seems straightforward – define a price level where a losing trade should be closed – the MQL4 environment introduces specific considerations, particularly concerning the minimum distance required between the current price and the stop loss level.

Understanding Stop Loss Orders

A stop loss order is a directive to close a position automatically when the market price reaches a specified level that is less favorable than the opening price. Its primary purpose is to limit potential losses on a trade. In MQL4, stop loss levels are typically set when opening a new order using OrderSend() or when modifying an existing order using OrderModify(). These levels must be absolute price values, not distances in pips.

Importance of Stop Loss in Risk Management

For algorithmic traders, disciplined risk management is paramount. Relying solely on manual intervention is impractical for automated systems. A correctly placed stop loss ensures that even if an EA encounters unexpected market movements or logic errors, potential losses on individual trades are capped. This is fundamental to preserving capital and achieving long-term profitability in automated trading.

Relevance of Minimum Stop Loss in MQL4

The concept of minimum stop loss distance is a technical requirement imposed by brokers and liquidity providers. It defines the closest a stop loss level can be set to the current market price (Bid for a buy position, Ask for a sell position) or the order’s open price. Attempting to set a stop loss closer than this minimum distance will result in the order being rejected or the modification failing. Understanding and correctly implementing checks for this minimum level in MQL4 code is crucial for the reliable operation of any EA.

Determining the Minimum Stop Loss Distance in MQL4

To comply with broker restrictions, an MQL4 EA needs to know the specific minimum distance required for stop loss and take profit levels for each trading instrument.

What is Minimum Stop Loss Distance?

The minimum stop loss distance is the smallest number of points (or pips, depending on broker configuration and Digits) that the stop loss or take profit level must be away from the current market price. This value varies between brokers and can also differ for various symbols (currency pairs, indices, commodities) on the same platform. It’s a dynamic value influenced by market conditions and broker policies.

MarketInfo() Function: How to Get Minimum Stop Level

In MQL4, the primary function to retrieve critical symbol properties, including the minimum stop level, is MarketInfo(). The relevant mode for minimum stop/take profit distance is MODE_STOPLEVEL.

double MarketInfo(string symbol, int type);

When calling MarketInfo(Symbol(), MODE_STOPLEVEL), the function returns the minimum required distance in points for the current symbol. It’s important to remember that ‘points’ can be different from ‘pips’ depending on the number of Digits for the symbol (e.g., 5-digit brokers have 10 points per pip).

Note: In MQL5, this information is retrieved using SymbolInfoInteger(symbol, SYMBOL_TRADE_STOPS_LEVEL), which also returns the value in points.

Example Code: Retrieving Minimum Stop Loss Value

Here is a simple MQL4 code snippet demonstrating how to get the minimum stop level for the current symbol and convert it to pips for easier understanding:

int GetMinimumStopLevelPips()
{
    // Get the minimum stop level in points
    int minStopLevelPoints = MarketInfo(Symbol(), MODE_STOPLEVEL);

    // Get the number of digits for the symbol
    int digits = MarketInfo(Symbol(), MODE_DIGITS);

    int minStopLevelPips;

    // Convert points to pips based on digits
    if (digits == 3 || digits == 5) // JPY pairs or 5-digit brokers
    {
        minStopLevelPips = minStopLevelPoints / 10;
    }
    else // Most other pairs (4-digit brokers)
    {
        minStopLevelPips = minStopLevelPoints;
    }

    return minStopLevelPips;
}

void OnStart()
{
    int minStop = GetMinimumStopLevelPips();
    Print("Minimum Stop/Take Profit level for ", Symbol(), ": ", minStop, " pips.");
}

This function calculates the minimum level in pips, making it easier to compare against stop loss distances typically calculated in pips.

How Minimum Stop Loss Works in MQL4

The minimum stop loss level imposes a constraint on when and where stop loss and take profit orders can be placed or adjusted.

Practical Scenarios Where Minimum Stop Loss Applies

  1. Placing New Orders: When using OrderSend() to open a new position, the specified stop loss and take profit prices must be at least MODE_STOPLEVEL points away from the market price at the moment the order is processed by the broker. For buy orders, Stop Loss must be below BidMODE_STOPLEVEL * Points/Pip, and Take Profit above Ask + MODE_STOPLEVEL * Points/Pip. For sell orders, Stop Loss must be above Ask + MODE_LEVELSTOP * Points/Pip, and Take Profit below BidMODE_STOPLEVEL * Points/Pip. Where Points/Pip = Point for 4-digit, Point * 10 for 5-digit etc. calculated from Digits. A safer check is distance in points. Stop Loss Buy must be at least MODE_STOPLEVEL points below Bid. Stop Loss Sell must be at least MODE_STOPLEVEL points above Ask. Similarly for Take Profit.
  2. Modifying Existing Orders: When using OrderModify() to change the stop loss or take profit levels of an open position, the new levels must also respect the minimum distance rule relative to the current market price (Bid or Ask).

Common Errors Related to Minimum Stop Loss

Attempting to set or modify a stop loss or take profit level within the minimum distance zone will lead to order rejection or modification failure. The most common error code associated with this is ERR_INVALID_STOPS (Error 130). Other related errors could include general trade server busy errors (ERR_TRADE_TOO_FAST) if too many invalid requests are sent.

Troubleshooting: Stop Loss Order Rejection

If an OrderSend() or OrderModify() call fails with error 130 (ERR_INVALID_STOPS), the first step is to check the proposed stop loss/take profit level against the current market price and the value returned by MarketInfo(Symbol(), MODE_STOPLEVEL). Ensure that your calculated price is outside the minimum distance zone. It’s crucial to fetch MODE_STOPLEVEL dynamically as it can change. Also, verify that you are using the correct price (Bid for buy checks, Ask for sell checks) when calculating the distance.

Implementing Minimum Stop Loss in MQL4 Code

Robust MQL4 EAs must incorporate checks for the minimum stop level to avoid order execution failures.

Writing Functions to Enforce Minimum Stop Loss

A common pattern is to create helper functions that adjust the calculated stop loss or take profit price to meet the minimum requirement before attempting to place the order. This involves calculating the desired SL/TP based on strategy logic, then comparing its distance from the current market price against MODE_STOPLEVEL.

Example: Calculating and Setting Stop Loss Dynamically

Let’s assume we want to set a stop loss 20 pips away from the open price for a buy order. We need to ensure this 20-pip distance respects the minimum stop level.

// Function to calculate adjusted Stop Loss price for a BUY order
double GetAdjustedStopLossBuy(double openPrice, int desiredStopLossPips)
{
    double stopLossPrice = openPrice - desiredStopLossPips * Point;

    // Get minimum stop level in points
    int minStopLevelPoints = MarketInfo(Symbol(), MODE_STOPLEVEL);

    // Calculate minimum required distance in price units from current Bid
    double minDistancePrice = minStopLevelPoints * Point;

    // Ensure the calculated stop loss is at least the minimum distance from Bid
    // Stop loss for buy should be below Bid. If it's too close or above (invalid), adjust.
    if (stopLossPrice > Bid - minDistancePrice)
    {
        // Adjust stop loss to be exactly the minimum distance below Bid
        stopLossPrice = Bid - minDistancePrice;

        // Add a small epsilon to be safe against floating point issues or tiny market moves
        stopLossPrice -= 5 * Point; // e.g., add 5 points extra distance
    }

    // Normalize the price to the correct number of digits
    return NormalizeDouble(stopLossPrice, Digits);
}

// Example Usage when sending a BUY order
double buyOpenPrice = Ask; // Assuming market order execution
int strategySLPips = 20;

double finalStopLossPrice = GetAdjustedStopLossBuy(buyOpenPrice, strategySLPips);

// Now use finalStopLossPrice in OrderSend() function
// OrderSend(Symbol(), OP_BUY, ..., finalStopLossPrice, ..., 0, 0, "My EA Order", 0, 0, clrNONE);

A similar function would be needed for sell orders, adjusting relative to the Ask price and ensuring the SL is above Ask + minDistancePrice.

Considerations for Different Currency Pairs

The MODE_STOPLEVEL value is symbol-specific. The logic demonstrated above correctly retrieves the level for the Symbol() the EA is attached to. However, if your EA trades multiple pairs simultaneously, you must dynamically fetch MarketInfo(symbol, MODE_STOPLEVEL) for each specific symbol before calculating or modifying stops for trades on that symbol. The Digits and Point values also vary by symbol and must be retrieved per symbol using MarketInfo(symbol, MODE_DIGITS) and MarketInfo(symbol, MODE_POINT) respectively.

Advanced Strategies and Considerations

While the minimum stop level is a technical constraint, dynamic stop loss placement based on market conditions is a strategic choice.

Adapting Stop Loss Based on Market Volatility

Setting a fixed-pip stop loss might be too tight in volatile markets or too wide in calm markets. A more sophisticated approach is to base the stop loss distance on current market volatility. Indicators like Average True Range (ATR) are commonly used for this purpose.

Using ATR (Average True Range) to Calculate Stop Loss

A common technique is to set the stop loss at a multiple of the current ATR value. For instance, SL = OpenPrice ± (ATR * N), where N is a chosen multiplier (e.g., 1.5 or 2). This creates a stop loss that adapts to how much the price is currently moving.

Backtesting Stop Loss Strategies in MQL4

When backtesting dynamic stop loss strategies (including those based on ATR), it is critical to ensure that your backtesting code also includes the check and adjustment for the MODE_STOPLEVEL. The MetaTrader 4 strategy tester does simulate broker rules, including the minimum stop level. If your EA logic attempts to set an invalid stop loss during backtesting, those trades will fail or have incorrect stop levels applied, leading to inaccurate backtesting results. Properly implementing the minimum stop level check ensures your backtest results reflect real-world trading conditions more accurately.


Leave a Reply