CustomStopOut: reading closeWorst, the function that closes your worst trade first

      double level = CsoMarginLevel(equity, margin);
      if(m_marginCall.Update(margin, level, m_settings.callLevel))
        {
         CsoNotify(m_settings, CsoMarginCallMessage(level, m_settings.callLevel));
        }
      if(!CsoIsBelow(margin, level, m_settings.stopOutLevel))
        {
         m_refusals.Clear();
         m_hasReportedNothingClosed = false;
         return false;
        }
      return closeWorst(level);

Compute the margin level, raise the margin call alert if one is due, and if the level is under my stop-out, call closeWorst. That method is CustomStopOut, a free script for MetaTrader 5 and MetaTrader 4 on the MQL5 CodeBase, in an MQL5 and an MQL4 version. I drop it on a chart with my own margin call and stop-out levels in percent. Under the margin call it alerts me once. Under the stop-out it closes the open trade with the worst net result, reads the margin level again, and closes the next one only if the level is still too low. It stays on the chart until I remove it.

It’s for traders on leverage who don’t trust the broker’s stop-out, and they shouldn’t. That one sits at 20% or 50%, where the account is already a smoking hole, and closes trades at the worst moment by the broker’s rules. Mine sits wherever I put it, like 100%, so the trades that are still fine get to live instead of being pissed away with the rest.

The inputs, before OnStart

input double InpMarginCallLevel = 150.0;             // Margin call level, % (alert below it)
input double InpStopOutLevel = 100.0;                // Stop-out level, % (close the worst position below it)
input int InpCheckIntervalMs = 500;                  // Check interval, milliseconds
input ENUM_CSO_SYMBOLS InpSymbols = CSO_SYMBOLS_ALL; // Positions to close
input long InpMagic = CSO_ANY_MAGIC;                 // Magic number to close, -1 for any
input int InpSlippagePoints = 30;                    // Maximum slippage on a close, points
input bool InpAlertWindow = true;                    // Alert window
input bool InpAlertPush = false;                     // Push notification
input bool InpAlertSound = false;                    // Sound

This is the dialog that opens when the script lands on a chart. Out of the box: margin call at 150%, stop-out at 100%, a check every 500 milliseconds, every symbol or just the chart’s, any magic number (-1) or a single one, 30 points of slippage allowed on a close, the alert window on, push and sound off. The MT4 file says “order” wherever this one says “position”, so there the symbol input is labelled Orders to close. The defaults don’t change.

Both versions are on the CodeBase, MetaTrader 5 and MetaTrader 4, each a zip with one source file and a screenshot. CustomStopOut.mq5 belongs in MQL5/Scripts/ and CustomStopOut.mq4 in MQL4/Scripts/. Compile it in MetaEditor and drag it from the Navigator onto any chart.

Closing trades needs permission from the terminal: Algo Trading on MT5, and on MT4 both AutoTrading and the Allow live trading box in the script’s settings. When that’s missing, the script tells you at start that closes will be refused and carries on with alerts only. Better to read that line now than to learn it with the account on fire.

Waiting for the trade server

      bool isConnected = TerminalInfoInteger(TERMINAL_CONNECTED) != 0;
      bool hasAccount = AccountInfoString(ACCOUNT_CURRENCY) != "";
      bool hasQuote = SymbolInfoDouble(_Symbol, SYMBOL_BID) > 0;

Connected, an account currency, a bid on the chart’s symbol. OnStart packs the inputs into a settings struct and then sits on these three, checking every 500 ms for up to 30 seconds. The reason is a terminal that just started: it reports an empty account, no currency and the broker’s levels at 0, and measuring my levels against those zeros is horseshit. If the three never come true, the alert is not started reason="no connection to the trade server after 30 seconds" and the script exits.

Refusing levels that can’t work

Next it reads the broker’s margin call and stop-out from the account and hands everything to CsoValidateSettings. Both levels have to be above 0%, the stop-out has to be below the margin call, and the interval has to be at least 1 ms. Then the check that earns its place:

   if(brokerMode == ACCOUNT_STOPOUT_MODE_PERCENT && stopOutLevel <= brokerStopOut)
     {
      reason = StringFormat(
                  "stop-out level %.2f%% must be above the broker's stop-out level %.2f%%, or the broker closes first",

A custom stop-out under the broker’s is decoration. The comparison only runs in percent mode. Some brokers set their levels as an amount of money, and an amount of equity doesn’t map to any fixed margin level, so in that mode the script skips the check and prints that it skipped it. Any refusal is an alert with the reason, and the script ends right there.

Settings that pass get a started line in the log with my levels, the broker’s, the filters and the interval, plus a warning if the script isn’t allowed to trade.

The loop that never sleeps after a close

   CCsoGuard guard(settings, currency);
   while(!IsStopped())
     {
      if(guard.Check())
        {
         continue;
        }
      Sleep(settings.intervalMs);
     }
   Print(CsoStoppedMessage(guard.Closed()));

Check returns true only when it closed something, and then the loop skips the sleep and checks again at once. A margin level that’s still under the stop-out is no time for a nap. Removing the script prints stopped closed= with the number of trades it closed.

The two limits of the whole thing are in these lines. while(!IsStopped()) means the guard exists only while the script runs, so the terminal has to stay on and connected. Sleep(settings.intervalMs) is the gap a fast enough market move can jump straight through while the loop is sleeping its ass off between checks. Under both, the broker’s own stop-out is still there.

Margin level and the margin call

CsoMarginLevel divides equity by used margin and multiplies by 100, MetaTrader’s own definition. No used margin means no open trades, so nothing to alert about and nothing to close. With margin in use, equity at zero or below counts as under every level.

CCsoMarginCallState is one bool. The alert fires when the level drops under my margin call, and it can fire again only after the level has climbed back to the margin call level and dropped under it once more. One alert per fall, not one every 500 ms until I throw the phone at the wall.

Where the alerts go

That alert, and every other message, goes through CsoNotify. It prints to the Experts tab first, as one key=value line, then to whatever I turned on: the alert window, a push notification prefixed with CustomStopOut, and alert.wav. A push or sound that fails is printed and not retried. Push is throttled to hell, and the comment above the call spells it out:

// SendNotification allows at most 2 calls a second and 10 a minute, and
// needs a MetaQuotes ID in the terminal's Notifications settings.

Which level, which trade goes next, when to alert and what the message says are all decided in plain functions that never call the terminal. Define CUSTOM_STOP_OUT_NO_PROGRAM before the include and the file drops its inputs and OnStart, leaving those functions for another program to call.

Picking the worst trade

Under the stop-out, closeWorst gathers the open trades the filters let through and scores each one:

   return position.profit + position.swap + position.commission;

Profit, swap and commission in the account currency, the same order most brokers use at their own stop-out. CsoPickWorst takes the lowest score, and the first in the list on a tie. Entry Ladder Risk Calculator carries a copy of this idea that closes only its own basket of trades, not the whole account.

This is the part where MT4 and MT5 really split. MT4 stores commission on the order, so it’s OrderCommission(), and the MT4 loop takes only open buys and sells, never touching pending orders. MT5 doesn’t store commission on the position, for reasons only MetaQuotes gives a shit about. It’s on the deals, so CsoPositionCommission loads the position’s deal history and sums DEAL_COMMISSION and DEAL_FEE across every deal. When that history won’t load, it prints the reason and counts that trade’s commission as 0.

Closing it, or moving on when the broker says no

MT5 closes with a market deal against the position ticket, request.position = (ulong)position.ticket;, which works the same on hedging and netting accounts. The fill policy is FOK, then IOC, then RETURN, whichever the symbol allows first. MT4 calls RefreshRates() and then OrderClose at the current bid or ask.

Brokers refuse closes constantly: market closed, off quotes, whatever bullshit the server picked today. The refusal branch:

         int err = CsoClosePosition(positions[worst], m_settings.slippagePoints, description);
         if(err != CSO_OK)
           {
            if(m_refusals.IsNew(positions[worst].ticket))
              {
               CsoNotify(m_settings, CsoRefusedMessage(positions[worst], err, description));
              }
            continue;
           }

Each refused ticket is alerted once, then the same check moves to the next worst trade, and the refused one gets another try on the next check. When the margin level is back at or over the stop-out, the record of alerted refusals is wiped. If nothing could be closed at all, below stop-out and nothing closed is printed once per breach.

The error text comes from different places. MT5 reports the trade server’s return code along with the server’s own comment. MT4’s OrderClose returns a bare error number, so the MQL4 file carries a table of the trade errors a close can run into, “Off quotes”, “Market is closed”, “Requote” and the rest, and writes the matching text into desc.

MT4 alert window and Experts log: margin call alert, a close refused with error 136 Off quotes, then the same EURUSD order closed
Error 136, “Off quotes”, on the first close, then the next check closed the 0.01 lot EURUSD buy. Both levels set absurdly high to force it, MT4 demo, version 1.1.

After a close goes through, it waits 300 ms, because on MT5 a finished trade request doesn’t mean the account values have caught up. Then it reads the account again and alerts the close: ticket, symbol, side, lots, net result, and the margin level before and after. If no margin is left in use, the after level is none.

MT5 alert window and Experts log: started line, margin call alert, and a 0.01 lot BTCUSD buy closed with margin_level_after=none
One close, net -0.19 USD, no margin left in use afterwards. Filtered to BTCUSD and one magic number, MT5 demo, version 1.0.

Which leaves the continue in the refusal branch. Take it out and one market that won’t take a close holds the whole guard on that single ticket while every other losing trade keeps bleeding the account.

CustomStopOut is a free download from the MQL5 CodeBase for MetaTrader 5 and MetaTrader 4.