preview
How Far Away Is the Stop-Out? A Stop-Out Threshold Finder and Pre-Trade Guard in MQL5

How Far Away Is the Stop-Out? A Stop-Out Threshold Finder and Pre-Trade Guard in MQL5

MetaTrader 5 — Examples |
70 0
Ali Akbar
Ali Akbar

Contents

  1. Introduction
  2. What the server checks
  3. Architecture
  4. Section 1: Status codes and results
  5. Section 2: The search, without a terminal
  6. Section 3: What the shortcut misses
  7. Section 4: CStopOutGuard and the symbol model
  8. Section 5: The recorder
  9. Section 6: Checking the code
  10. Section 7: The threshold against the tester's crossing tick
  11. Section 8: Using the guard in an EA
  12. Section 9: A consistency check in Python
  13. What the checks do not cover
  14. Limitations
  15. Conclusion
  16. Attached files


Introduction

An Expert Advisor that trades without a stop loss, or with a stop far away, has one exit it does not control. When the margin level falls to the broker's stop-out level, the server starts closing positions on its own. The account information shows the margin level now. It does not show how far the price has to move before the level is reached, and it does not show how much closer a new order would bring that point.

Grid and averaging EAs need this number most, because every new position moves the stop-out closer. The usual estimate takes the equity above the stop-out level and divides it by the money one point is worth. That shortcut assumes a point is worth the same at any price, and that the margin stays the same while the price moves. On MetaQuotes-Demo the first assumption failed for USDJPY, whose profit is converted at the price it is valued at. The second one held in the tester runs, and my first model got it wrong. For EURUSD and XAUUSD, OrderCalcMargin() returns a different margin at a different price, and the model used that. The tester kept the margin of an open position at its value from the fill, and a check built into the class showed the difference. A third finding concerns new orders: the margin per lot grows with the total volume on the symbol.

Three different prices are involved, and this article keeps them apart:

  1. The threshold price is a calculated value. It is the first bid on the symbol's tick grid at which the model of the account reaches the stop-out level. The model moves one symbol and holds every other price, the spread, and the swaps as they are now.
  2. The crossing tick is the first real tick in the Strategy Tester at which the tester's own margin level was at or below the stop-out level.
  3. The stop-out deal is the deal with DEAL_REASON_SO that closed the position. Its price depends on when the server checks the level.

CStopOutGuard computes only the first of these. The class values the open positions of one symbol at a hypothetical price using OrderCalcProfit() and OrderCalcMargin(). Then it searches within 50% of the current bid on each side. When the level is not reached within that range, the search reports SOG_OUT_OF_RANGE and gives no price. The same search answers a question an EA can ask before it trades: if this order is filled at the current price, how far away will the threshold price be? CanAdd() checks only that distance and does not replace an order check. The method adds no commission for the planned order. CanAdd() and the results here therefore apply to accounts and symbols without an entry commission.

A recorder class writes every prediction to a CSV file and catches the crossing tick. I used it in 44 Strategy Tester runs on MetaQuotes-Demo, with USDJPY, XAUUSD, and EURUSD. In the median case, the last snapshot before the crossing was within 2 points of the crossing tick's bid on USDJPY (15 crossings) and within 14 points on XAUUSD (16 crossings). EURUSD gave only two crossings. Most of the gold difference came from the price jump between the tick before the crossing and the crossing tick itself. The article measures that jump separately. The runs also showed how this tester setup timed the stop-out deals. This timing is an observation about these runs, not a documented property of the Strategy Tester.


What the server checks

The account properties ACCOUNT_MARGIN_SO_MODE, ACCOUNT_MARGIN_SO_CALL, and ACCOUNT_MARGIN_SO_SO describe the rule. In percent mode the margin level is equity divided by margin, times 100, and positions are closed when it reaches the stop-out level. In money mode the equity itself is compared with the level. On my MetaQuotes-Demo account the margin call is at 50% and the stop-out at 30%. A position closed this way leaves a deal with the reason DEAL_REASON_SO.

Several published articles deal with margin, and none of those I found answers this question. Artyom Trishkin's DoEasy library tracks the margin level as an account event in parts XII and XIII. Building Your Personal Expert Advisor (Part 3) works out the margin and the allowable risk of a new trade. Both look at the account as it is now. I found no article that computes the price at which the stop-out level is reached, or checks how a new order would move that price.


Architecture

The core module consists of four include files. The package also contains two test scripts, three Expert Advisors, and a Python script, listed at the end of the article. Fig. 1 shows how a question from the EA turns into a threshold price.

The threshold search

From the EA's question to the first grid price where the model reaches the stop-out level

The EA asks CStopOutGuard. The guard builds a model of one symbol's positions and passes it to the search. The recorder calls the guard, catches the crossing tick and the tick before it, and stores every stop-out deal together with those two ticks

Fig. 1. The EA asks CStopOutGuard. The guard builds a model of one symbol's positions and passes it to the search. The recorder calls the guard, catches the crossing tick and the tick before it, and stores every stop-out deal together with those two ticks

Only one symbol moves in a search. Every other symbol keeps its current price, and the swaps, commissions, and profits already in the equity stay as they are. The model applies only the change that the price move causes.

File Contents Needs a terminal
StopOutTypes.mqh Status codes, the SStopOutRules and SStopOutPoint structures No
StopOutMath.mqh IAccountModel, CStopOutMath: level arithmetic, the threshold search, the linear shortcut No
StopOutGuard.mqh CSymbolModel and CStopOutGuard: positions, OrderCalcProfit(), OrderCalcMargin(), CanAdd() Yes
StopOutRecorder.mqh CStopOutRecorder: snapshots, crossing ticks, and stop-out deals in a CSV file Yes


Section 1: Status codes and results

A search can end in six ways. Two of these outcomes are not errors. SOG_OUT_OF_RANGE means the level was not reached within the search range. The threshold is then further away than the range, or does not exist in that direction, and no price is returned. SOG_ALREADY_BELOW means the account is at or below the level right now.

//+------------------------------------------------------------------+
//| Result of a stop-out price search for one symbol                 |
//+------------------------------------------------------------------+
enum ENUM_SOG_STATUS
  {
   SOG_OK=0,            // a threshold price was found inside the search range
   SOG_NO_POSITIONS,    // no open positions on the symbol
   SOG_OUT_OF_RANGE,    // no threshold inside the search range in that direction, no price given
   SOG_ALREADY_BELOW,   // the account is at or below the level already
   SOG_NO_MARGIN,       // the account uses no margin, so there is no stop-out
   SOG_CALC_FAILED      // OrderCalcProfit() or OrderCalcMargin() failed
  };

The result of a search is a price and its distance from the current bid. The bid is the price the search moves. A buy is valued at the bid and a sell at the ask, and the spread is held at its current value. The last field compares the model with the account, as Section 4 explains.

//+------------------------------------------------------------------+
//| Threshold price of one symbol, all other prices held still       |
//+------------------------------------------------------------------+
struct SStopOutPoint
  {
   string            symbol;       // symbol that was moved
   ENUM_SOG_STATUS   status;       // outcome of the search
   double            bid_now;      // bid when the search ran
   double            bid_at;       // first bid on the tick grid where the model reaches the level
   double            points;       // distance from bid_now, in points (signed)
   double            percent;      // distance from bid_now, in percent of bid_now (signed)
   double            equity;       // model equity at bid_at
   double            margin;       // model margin at bid_at
   double            margin_check; // account margin minus model margin at bid_now, % (EMPTY_VALUE: not checked)
  };


Section 2: The search, without a terminal

CStopOutMath knows nothing about positions. The class works with any object that can say what the equity and the margin would be at a given bid. That interface is the whole contract:

//+------------------------------------------------------------------+
//| Equity and margin of the account as a function of one bid        |
//+------------------------------------------------------------------+
class IAccountModel
  {
public:
   virtual bool      Evaluate(const double bid,double &equity,double &margin)=0;
  };

The gap is the equity left above the level. The gap is positive while the account is safe and zero or negative once the level is reached.

//+------------------------------------------------------------------+
//| Equity at which the level is reached for a given margin          |
//+------------------------------------------------------------------+
double CStopOutMath::Threshold(const bool percent,const double level,const double margin)
  {
//--- percent mode compares equity/margin*100 with the level, money mode compares equity itself
   return(percent ? level*margin/100.0 : level);
  }
//+------------------------------------------------------------------+
//| Equity left above the level, negative once the level is crossed  |
//+------------------------------------------------------------------+
double CStopOutMath::Gap(const bool percent,const double level,const double equity,const double margin)
  {
   return(equity-Threshold(percent,level,margin));
  }

Solve() looks between the current bid and a limit, which CStopOutGuard puts 50% away on each side. If the gap is already gone at the bid, the answer is the bid. Otherwise it walks toward the limit in 32 equal steps and stops at the first step where the gap is gone. If there is none, it reports SOG_OUT_OF_RANGE. A bisection then narrows the crossing between that step and the previous one to less than half a tick. The answer is the first price on the tick grid at or past the crossing. The tick grid is the set of multiples of SYMBOL_TRADE_TICK_SIZE. This answer is a grid price, not a prediction of a market tick. The market can jump over this price, and Section 7 shows how often it did.

//+------------------------------------------------------------------+
//| First grid price from bid_now toward bid_limit at the level      |
//+------------------------------------------------------------------+
ENUM_SOG_STATUS CStopOutMath::Solve(IAccountModel &model,const bool percent,const double level,
                                    const double bid_now,const double bid_limit,const double tick,
                                    double &bid_at,double &equity_at,double &margin_at)
  {
   bid_at=0.0;
   double e=0.0,m=0.0;
   if(!model.Evaluate(bid_now,e,m))
      return(SOG_CALC_FAILED);
   equity_at=e;
   margin_at=m;
   if(m<=0.0 && percent)
      return(SOG_NO_MARGIN);
   if(Gap(percent,level,e,m)<=0.0)
     {
      bid_at=bid_now;
      return(SOG_ALREADY_BELOW);
     }
//--- a scan in equal steps finds the first step past the level, so a gap that crosses
//--- the level more than once still gives the nearest crossing, unless it dips below
//--- the level and comes back within one step
   double lo=bid_now,hi=bid_now;
   bool   found=false;
   for(int s=1; s<=SOG_SCAN_STEPS && !found; s++)
     {
      double p=bid_now+(bid_limit-bid_now)*s/SOG_SCAN_STEPS;
      if(!model.Evaluate(p,e,m))
         return(SOG_CALC_FAILED);
      if(Gap(percent,level,e,m)<=0.0)
        {
         hi=p;
         found=true;
        }
      else
         lo=p;
     }
   if(!found)
      return(SOG_OUT_OF_RANGE);
//--- lo keeps a price above the level, hi a price at or below it
   for(int i=0; i<200 && MathAbs(hi-lo)>tick*0.5; i++)
     {
      double mid=0.5*(lo+hi);
      if(!model.Evaluate(mid,e,m))
         return(SOG_CALC_FAILED);
      if(Gap(percent,level,e,m)>0.0)
         lo=mid;
      else
         hi=mid;
     }
//--- the answer is the first price on the tick grid at or past the crossing:
//--- step away from the bid until the level is reached, then back while it still is
   bool   down=(bid_limit<bid_now);
   double step=down ? -tick : tick;
   double t=SnapToTick(0.5*(lo+hi),tick,down);
   for(int i=0; i<4; i++)
     {
      if(!model.Evaluate(t,e,m))
         return(SOG_CALC_FAILED);
      if(Gap(percent,level,e,m)<=0.0)
         break;
      t+=step;
     }
   for(int i=0; i<4; i++)
     {
      double back=t-step;
      if(!model.Evaluate(back,e,m))
         return(SOG_CALC_FAILED);
      if(Gap(percent,level,e,m)>0.0)
         break;
      t=back;
     }
   if(!model.Evaluate(t,e,m))
      return(SOG_CALC_FAILED);
   bid_at=t;
   equity_at=e;
   margin_at=m;
   return(SOG_OK);
  }

My first version only stepped away from the bid after the rounding, so it could stop one grid price too far. The second loop now steps back while the level is still reached. Checks 28 and 29 in Section 6 test this on 2,000 synthetic accounts per side.

The bisection is correct only if the gap crosses zero exactly once between two scan steps. For the tested cases, this condition holds on each side of the bid. On EURUSD and XAUUSD with a USD account the equity is a straight line in the bid. With the default margin basis (Section 4) the margin does not change with the price, so the gap is a straight line too. With the margin charged at the moved price, the margin is the larger of the two sides' margins. Each side's margin is a straight line, or with volume tiers a curve that gets steeper as the price rises.

The gap is then a concave function. If the gap is positive at the bid, it can cross zero at most once on each side. On USDJPY the margin is fixed in USD and the equity changes in one direction only. I have not shown this for other account currencies, for cross rates that move together, or for other margin rules. For those, the scan step acts as a safeguard. The scan still finds the nearest crossing when the gap goes under the level and comes back. However, the scan can miss a dip narrower than one scan step. With the default range, one scan step is 1.56% of the price. Checks 26 and 27 show both cases. After a missed dip, Nearest() reports a crossing that is further away, or SOG_OUT_OF_RANGE. CanAdd() can then pass an order whose real threshold is closer than the minimum it was given.

Equal opposite positions keep the equity flat. In percent mode, that does not by itself keep the margin level flat, because the margin can move with the price. Whether it does depends on the account. If the margin is charged at the moved price, as OrderCalcMargin() computes it for EURUSD, a large enough hedge reaches the level as the price rises, and the search finds that crossing (check 24). The margin may also stay at the open price, as it did in the tester, or be fixed in the account currency, as on USDJPY with a USD account. Then the level does not move, and SOG_OUT_OF_RANGE is the correct answer (check 23).

For comparison the class also has the common shortcut. The shortcut takes the gap and divides it by the money one price unit is worth for the whole volume.

//+------------------------------------------------------------------+
//| The usual shortcut: fixed margin and a fixed tick value          |
//+------------------------------------------------------------------+
double CStopOutMath::LinearDistance(const bool percent,const double level,const double equity,
                                    const double margin,const double volume,const double tick_value,
                                    const double tick_size)
  {
   double money_per_unit=MathAbs(volume)*tick_value/tick_size;
   if(money_per_unit<=0.0)
      return(DBL_MAX);
//--- price distance that eats the equity above the level, in price units
   return(Gap(percent,level,equity,margin)/money_per_unit);
  }


Section 3: What the shortcut misses

Before writing the model I checked what OrderCalcProfit() and OrderCalcMargin() return for a price far from the market. A probe script valued a 1-lot buy at the bid and at 5% and 10% below it, on the live demo account. On USDJPY the 5% drop gave a loss of 5,264.49 USD. The JPY loss is 790,575, and 790,575 divided by the closing price of 150.171 gives 5,264.49. Divided by the current rate of 158.075 it would be 5,001.3. So OrderCalcProfit() converts the profit at the closing price it is given. A USDJPY point is then worth more on the way down, and the threshold is closer than a fixed point value says. On EURUSD and XAUUSD, OrderCalcMargin() for the same lot fell with the price, from 1,124.05 to 1,067.85 USD on EURUSD at 5% lower. My first model charged open positions at the moved price because of this. Section 4 shows why that was wrong in the tester.

The second finding was larger. In the Strategy Tester my first sizing code was refused with "not enough money" for 5.68 lots, on a 10,000 USD account at 1:100. One lot needed 1,140.30 USD, so 5.68 lots should have needed about 6,477. A probe EA asked OrderCalcMargin() and OrderCheck() for several volumes at the same price:

Volume, lots OrderCalcMargin(), USD OrderCheck() margin, USD OrderCheck() verdict Average per lot, USD
0.50 570.15 570.15 accepted 1,140.30
1.00 1,140.30 1,140.30 accepted 1,140.30
2.00 2,280.60 2,280.60 accepted 1,140.30
3.00 3,841.80 3,841.80 accepted 1,280.60
4.00 6,122.40 6,122.40 accepted 1,530.60
4.50 7,394.05 7,394.05 accepted 1,643.12
5.00 9,104.50 9,104.50 accepted 1,820.90
5.20 9,788.68 9,788.68 accepted 1,882.44
8.00 19,367.20 19,367.20 refused, 10019 2,420.90
20.00 60,418.00 60,418.00 refused, 10019 3,020.90

The probe ran in the tester on EURUSD at a bid of 1.14030, with a 10,000 USD deposit and 1:100 leverage.

The two functions agree with each other, and neither is linear in the volume. Up to 2 lots the margin is 1,140.30 per lot. Above that the price of a further lot rises in steps, and above 4.5 lots every further lot costs 3,420.90, three times as much. All 10 rows fit one rule on the notional value of the side. The notional value is the volume times the contract size times the price. The margin is 1% of the first 300,000 USD of notional, 2% of the part from 300,000 to 500,000 USD, and 3% of the rest. At 1.14030 the two steps fall at 2.63 and 4.38 lots. The tiers also apply to the whole side, not to each position. One 2.5-lot buy needed 2,850.75 USD, and a second one raised the account margin to 9,104.50, the margin of 5 lots. A 2.5-lot sell next to those two buys added nothing. On this account a hedge was charged on its larger side only.

These side-wide tiers change how a new order has to be checked. OrderCalcMargin() for the new order alone says 2,850.75, while the account margin rises by 6,253.75. The order of positions does not matter, only the total on each side.


Section 4: CStopOutGuard and the symbol model

CSymbolModel holds the positions of one symbol and implements IAccountModel. LoadRules() reads the account's levels, and Build() copies the symbol's positions into the model. Freeze() stores the profit and the margin at the current bid, so later calls only add the change.

//+------------------------------------------------------------------+
//| Profit and margin of the modelled positions at one bid           |
//+------------------------------------------------------------------+
bool CSymbolModel::Sum(const double bid,double &profit,double &margin)
  {
   profit=0.0;
   margin=0.0;
   double ask=bid+m_spread;
   double buys=0.0,sells=0.0,buy_open=0.0,sell_open=0.0;
   for(int i=0; i<ArraySize(m_type); i++)
     {
      //--- a buy closes at the bid, a sell at the ask
      bool   buy=(m_type[i]==ORDER_TYPE_BUY);
      double p=0.0;
      if(!OrderCalcProfit(m_type[i],m_symbol,m_volume[i],m_open[i],buy ? bid : ask,p))
         return(false);
      profit+=p;
      if(buy)
        {
         buys+=m_volume[i];
         buy_open+=m_volume[i]*m_open[i];
        }
      else
        {
         sells+=m_volume[i];
         sell_open+=m_volume[i]*m_open[i];
        }
     }
//--- the margin is taken on the total volume of each side, since the volume tiers measured on
//--- MetaQuotes-Demo apply to the whole side, and the larger side is charged as it was there;
//--- other hedge rules (SYMBOL_MARGIN_HEDGED), exchange or portfolio margin are not modelled;
//--- the tester kept the margin of an open position at its value from the fill, so by default
//--- each side is charged at its volume-weighted open price
   double pb=(m_basis==SOG_MARGIN_AT_OPEN && buys>0.0) ? buy_open/buys : ask;
   double ps=(m_basis==SOG_MARGIN_AT_OPEN && sells>0.0) ? sell_open/sells : bid;
   double mb=0.0,ms=0.0;
   if(buys>0.0 && !OrderCalcMargin(ORDER_TYPE_BUY,m_symbol,buys,pb,mb))
      return(false);
   if(sells>0.0 && !OrderCalcMargin(ORDER_TYPE_SELL,m_symbol,sells,ps,ms))
      return(false);
   margin=MathMax(mb,ms);
   return(true);
  }
//+------------------------------------------------------------------+
//| Account equity and margin if only this symbol moved to bid       |
//+------------------------------------------------------------------+
bool CSymbolModel::Evaluate(const double bid,double &equity,double &margin)
  {
   double p=0.0,m=0.0;
   if(bid<=0.0 || !Sum(bid,p,m))
      return(false);
//--- only the change is applied, so swaps, commissions and other symbols stay as they are
   equity=m_equity+(p-m_profit_now);
   margin=m_margin+(m-m_margin_now);
   return(true);
  }

Profit is computed per position, because each one has its own open price. Margin is computed once per side from the total volume, for the reason in Section 3, and the larger side is taken. The price at which the margin is charged is a setting. SOG_MARGIN_AT_OPEN, the default, charges each side at its volume-weighted open price, so the margin of open positions does not change in a search. SOG_MARGIN_AT_PRICE charges it at the moved price. This aggregation matches what I measured on MetaQuotes-Demo. The aggregation is not a general margin model for MetaTrader 5.

A different SYMBOL_MARGIN_HEDGED setting, exchange and futures instruments, portfolio margin, or broker-specific rules can charge the same positions differently. To catch such a mismatch, Find() and CanAdd() compare the model's margin at the current bid with ACCOUNT_MARGIN whenever no other symbol has open positions. The difference goes into margin_check, in percent of the account margin.

//+------------------------------------------------------------------+
//| Account margin minus the model's margin now, percent             |
//+------------------------------------------------------------------+
double CSymbolModel::MarginCheck(void) const
  {
//--- meaningful only when every position on the account is in the model
   return(m_margin>0.0 ? 100.0*(m_margin-m_margin_now)/m_margin : EMPTY_VALUE);
  }

This check is how I found the margin basis. In my first batch of runs (Section 7), the model charged margin at the moved price. You can reproduce that behavior in StopOutLab by setting InpMarginAtPrice=true. The margin_check field then reported differences of up to 5.17% on EURUSD and 26.43% on XAUUSD, and none on USDJPY, whose margin is fixed in USD. The model was the side that moved. In all 44 runs of that batch, ACCOUNT_MARGIN stayed at its value from the fill in every snapshot while the position was open, for all three symbols. So SOG_MARGIN_AT_OPEN became the default, and the batch was run again. Over the 480,376 snapshots of the new batch the largest difference was 0.0000%.

These results come from the tester with one open position. I have not checked which basis a live server uses, or how either one handles positions opened at different prices. In the tester both numbers come from the same terminal, so the check confirms the model's aggregation against the tester's own margin, not the server's formula. On another account, margin_check is the way to find out. With a basis that does not fit, it would drift as the price moves away from the open price.

CStopOutGuard searches both directions and keeps the nearer result. StopOut() and MarginCall() are the same search with the two levels.

//+------------------------------------------------------------------+
//| The closer of the two directions                                 |
//+------------------------------------------------------------------+
bool CStopOutGuard::Nearest(const string symbol,const double level,SStopOutPoint &pt)
  {
   SStopOutPoint down,up;
   bool ok=Find(symbol,level,down,up);
   bool d=(down.status==SOG_OK || down.status==SOG_ALREADY_BELOW);
   bool u=(up.status==SOG_OK || up.status==SOG_ALREADY_BELOW);
   if(d && (!u || MathAbs(down.points)<=MathAbs(up.points)))
      pt=down;
   else
      if(u)
         pt=up;
      else
         pt=(down.status!=SOG_OUT_OF_RANGE) ? down : up;
   return(ok);
  }

CanAdd() answers the question before a trade. The method builds the model from the open positions, stores the baseline, and only then adds the planned order at the current ask or bid. The spread the new position pays and the extra margin, tiers included, are both part of the change the search sees.

//+------------------------------------------------------------------+
//| Threshold distance after a planned market order is filled        |
//+------------------------------------------------------------------+
bool CStopOutGuard::CanAdd(const string symbol,const ENUM_ORDER_TYPE type,const double volume,
                           const double min_percent,SStopOutPoint &after)
  {
//--- this is a check of the stop-out distance only, not an order check: free margin, stop and
//--- freeze levels, slippage, partial fills and the spread at the fill are left to OrderCheck()
   CSymbolModel model;
   double bid=0.0,tick=0.0;
   int    others=0;
   if(!Build(model,symbol,bid,tick,others) || !model.Freeze(bid))
     {
      Fill(after,symbol,SOG_CALC_FAILED,bid,0.0,0.0,0.0);
      return(false);
     }
   double check=(others==0) ? model.MarginCheck() : EMPTY_VALUE;
//--- the new position joins the model after the baseline, so its spread cost and margin count
   MqlTick t;
   SymbolInfoTick(symbol,t);
   model.Add(type,volume,type==ORDER_TYPE_BUY ? t.ask : t.bid);
   SStopOutPoint down,up;
   Search(model,symbol,m_rules.stop_out,bid,tick,down,up);
   bool d=(down.status==SOG_OK || down.status==SOG_ALREADY_BELOW);
   bool u=(up.status==SOG_OK || up.status==SOG_ALREADY_BELOW);
   if(d && (!u || MathAbs(down.points)<=MathAbs(up.points)))
      after=down;
   else
      after=u ? up : down;
   after.margin_check=check;
//--- out of range on both sides only says the threshold is further away than the range
   if(!d && !u)
      return(down.status==SOG_OUT_OF_RANGE && up.status==SOG_OUT_OF_RANGE && min_percent<=m_range);
   return(after.status==SOG_OK && MathAbs(after.percent)>=min_percent);
  }

CanAdd() assumes a fill at the current price, with the current spread. The method does not check free margin, stop or freeze levels, the price deviation or slippage of the fill, partial fills, or a spread that changes before the fill. Those checks are the job of OrderCheck(), and GridGuardDemo in Section 8 calls OrderCheck() first. When the search finds no threshold within 50% on either side, CanAdd() passes only a minimum distance of up to 50%, because the search has shown nothing beyond that (checks 37 and 38).

CanAdd() also charges no commission for the planned order. The equity after the simulated fill contains the spread of the new position and nothing else. Commissions already charged for open positions are part of today's equity and are covered. On an account that charges a commission per deal or per lot, the real equity after the fill is lower by that commission. The real threshold is then closer than CanAdd() reports. CanAdd() and the results in this article are therefore limited to accounts and symbols without an entry commission. The test account charged none (Section 7). On a commission account, the EA has to allow for the commission itself, for example with a larger minimum distance.


Section 5: The recorder

CStopOutRecorder is for testing the guard and for looking back after a stop-out. Snapshot() runs a search and writes one line to a CSV file in the common Files folder. Watch() is meant for every tick and reads only the account equity and margin. On the crossing tick, the first tick at or below the stop-out level, it writes:

  1. the crossing tick's bid and margin level
  2. the bid and margin level of the tick before it
  3. the threshold price from the last snapshot
  4. the number of positions on other symbols

The tick before the crossing was still above the level, so the level price lies between the two bids. The tick before the crossing lets Section 7 separate the model's error from the jump between two ticks. ACCOUNT_EQUITY and ACCOUNT_MARGIN cover the whole account. With other symbols open, a crossing may have been caused by them, and the last field says so. In the lab runs of Section 7 no other symbol was open. The margin level often crosses the line and comes back within seconds, so only the first crossing counts until the account recovers above the margin call level.

//+------------------------------------------------------------------+
//| Call on every tick: catch the first tick at or below the level   |
//+------------------------------------------------------------------+
bool CStopOutRecorder::Watch(void)
  {
   if(m_guard==NULL)
      return(false);
   double equity=AccountInfoDouble(ACCOUNT_EQUITY);
   double margin=AccountInfoDouble(ACCOUNT_MARGIN);
   double bid=SymbolInfoDouble(m_symbol,SYMBOL_BID);
   SStopOutRules r=m_guard.Rules();
   if(margin<=0.0)
     {
      m_below=false;
      m_prev_bid=0.0;
      return(false);
     }
//--- an episode ends when the account is back above the margin call level
   if(CStopOutMath::Gap(r.percent,r.call,equity,margin)>0.0)
      m_below=false;
   bool below=(CStopOutMath::Gap(r.percent,r.stop_out,equity,margin)<=0.0);
   double level=CStopOutMath::MarginLevel(equity,margin);
//--- only the first crossing of an episode is kept, the level often crosses back and forth
   if(below && !m_below)
     {
      m_below=true;
      m_cross_time=TimeCurrent();
      m_cross_bid=bid;
      m_cross_level=level;
      m_cross_pred=m_snap_pred;
      //--- the tick before it was still above the level, so the level lies between the two bids
      m_cross_pbid=m_prev_bid;
      m_cross_plev=m_prev_level;
      //--- the account values cover every symbol, so another open symbol may have caused the crossing
      m_cross_other=OtherPositions();
      int digits=(int)SymbolInfoInteger(m_symbol,SYMBOL_DIGITS);
      Line(StringFormat("X,%s,%s,%.2f,%.2f,%.2f,%s,%s,%.2f,%d",TimeToString(m_cross_time,TIME_DATE|TIME_SECONDS),
                        DoubleToString(m_cross_bid,digits),equity,margin,m_cross_level,DoubleToString(m_cross_pred,digits),
                        DoubleToString(m_cross_pbid,digits),m_cross_plev,m_cross_other));
     }
   m_prev_bid=bid;
   m_prev_level=level;
   return(below);
  }

OnTransaction() is called from the EA's OnTradeTransaction(). When a deal with DEAL_REASON_SO arrives, it stores the deal together with the crossing tick and the last snapshot. A sell position is closed at the ask, so the recorder adds the spread from the snapshot to its threshold bid. The deal price is kept for context. The recorder does not use it to judge the threshold, because it depends on when the server checks, as Section 7 shows. ScanHistory() picks up stop-out deals the handler missed, and Report() prints them.

//+------------------------------------------------------------------+
//| Store a stop-out deal with the crossing and snapshot before it   |
//+------------------------------------------------------------------+
void CStopOutRecorder::AddDeal(const ulong deal)
  {
   if(Known(deal) || !HistoryDealSelect(deal))
      return;
   if((ENUM_DEAL_REASON)HistoryDealGetInteger(deal,DEAL_REASON)!=DEAL_REASON_SO)
      return;
   SStopOutEvent ev;
   ev.deal=deal;
   ev.time=(datetime)HistoryDealGetInteger(deal,DEAL_TIME);
   ev.symbol=HistoryDealGetString(deal,DEAL_SYMBOL);
   ev.price=HistoryDealGetDouble(deal,DEAL_PRICE);
   ev.volume=HistoryDealGetDouble(deal,DEAL_VOLUME);
   ev.profit=HistoryDealGetDouble(deal,DEAL_PROFIT);
   ev.swap=HistoryDealGetDouble(deal,DEAL_SWAP);
//--- a sell deal closes a buy position
   ev.buy_closed=((ENUM_DEAL_TYPE)HistoryDealGetInteger(deal,DEAL_TYPE)==DEAL_TYPE_SELL);
   ev.snap_time=m_snap_time;
   ev.snap_bid=m_snap_bid;
   ev.snap_level=m_snap_level;
   ev.cross_time=m_cross_time;
   ev.cross_bid=m_cross_bid;
   ev.cross_level=m_cross_level;
   ev.cross_pred=m_cross_pred;
   ev.cross_prev_bid=m_cross_pbid;
   ev.cross_prev_level=m_cross_plev;
   ev.cross_others=m_cross_other;
//--- a sell position closes at the ask, so the spread is added to the threshold bid; the deal
//--- price depends on when the server checks, so this is context and not an error measure
   ev.snap_close=(m_snap_pred>0.0 && !ev.buy_closed) ? m_snap_pred+m_snap_spread : m_snap_pred;
   int n=ArraySize(m_events);
   ArrayResize(m_events,n+1);
   m_events[n]=ev;
   int digits=(int)SymbolInfoInteger(ev.symbol,SYMBOL_DIGITS);
   Line(StringFormat("D,%s,%s,%I64u,%s,%.2f,%s,%.2f,%s,%s,%.2f",TimeToString(ev.time,TIME_DATE|TIME_SECONDS),
                     ev.symbol,deal,ev.buy_closed ? "buy" : "sell",ev.volume,DoubleToString(ev.price,digits),
                     ev.profit,TimeToString(ev.snap_time,TIME_DATE|TIME_SECONDS),DoubleToString(ev.snap_close,digits),ev.swap));
  }


Section 6: Checking the code

TestStopOutGuard.mq5 runs 40 checks and prints PASS or FAIL for each. The first 29 need no broker. They feed CStopOutMath synthetic accounts whose answer has a closed form. Checks 9 to 16 cover four accounts. The first is a EURUSD-type buy with a margin that follows the price, and the second is the same buy with a fixed margin. The third is a sell that has to be searched upward. The fourth is a USDJPY-type buy whose profit is converted at the moved price. Checks 17 to 22 cover money mode, an account already below the level, an account with no margin, and a model whose terminal call fails. Checks 23 to 29 cover hedges with a fixed and a moving margin, and a gap that crosses the level twice. They also cover a dip narrower than one scan step and the first-grid-price rule on 2,000 accounts per side.

The last 11 are consistency checks on the live account. They call OrderCalcProfit() and OrderCalcMargin() directly at the answer of CanAdd() and one tick before it. Checks 33 and 39 do this once with the margin at the open price and once at the moved price. The guard calls the same two functions, so these checks show that the search and the aggregation are coded as intended. They do not show that the terminal values positions the way the server does.

PASS  1 percent threshold                          30% of 5000 is 1500
PASS  2 money threshold                            money mode ignores the margin
PASS  3 gap above the level                        1600 equity, 100 above
PASS  4 margin level                               1500 / 5000 = 30%
PASS  5 margin level with no margin                0, no division by zero
PASS  6 snap down                                  1.123456 to 1.12345
PASS  7 snap up                                    1.123451 to 1.12346
PASS  8 snap keeps a grid price                    4490.25 on a 0.25 grid
PASS  9 buy, margin follows price                  got 1.15680, formula 1.15680
PASS  10 level reached at the answer               level 29.968%
PASS  11 one tick earlier is still above           level 30.054%
PASS  12 buy, fixed margin                         got 1.15684, formula 1.15684, -4.0 points from the moving-margin answer
PASS  13 sell, search upward                       got 1.18312, formula 1.18312
PASS  14 sell, nothing below the price             out of range
PASS  15 USDJPY-type buy                           got 155.869, formula 155.869
PASS  16 shortcut puts it too far away             shortcut 155.841, exact 155.869, 28 points too far
PASS  17 money mode                                got 1.15666, want 1.15666
PASS  18 just above the level still searches       level 31.3%, found 1.16984
PASS  19 already below the level                   level 28.6%, answer is the current bid
PASS  20 no margin, no stop-out                    no margin
PASS  21 small position, out of range              out of range
PASS  22 failed terminal call                      calc failed
PASS  23 hedge, fixed margin: level never moves    out of range
PASS  24 hedge, margin follows price: level above  got 1.22223, formula 1.22223, equity 2200.00 at both
PASS  25 hedge, margin follows price: none below   out of range
PASS  26 level crossed and recovered: nearest found ok, got 1.14000, band starts at 1.14000
PASS  27 band narrower than a scan step: missed    out of range
PASS  28 first grid price, 2000 buy accounts       0 answers off by a tick
PASS  29 first grid price, 2000 sell accounts      0 answers off by a tick
PASS  30 account rules loaded                      stop-out 30.00, margin call 50.00, percent
PASS  31 no positions on the symbol                no positions
PASS  32 planned buy has a threshold below         67.26 lots, stop-out bid 1.12105, -0.38% away
PASS  33 same functions agree, margin at open      29.9911% there, 30.0218% one tick before
PASS  34 CanAdd passes a smaller minimum
PASS  35 CanAdd refuses a larger minimum
PASS  36 planned sell has a threshold above        stop-out bid 1.12959, 0.38% away
PASS  37 out of range passes a 10% minimum         0.01 lots, out of range
PASS  38 out of range refuses a 60% minimum        60% is beyond the 50% search range
PASS  39 same functions agree, margin at price     29.9873% there, 30.0179% one tick before
PASS  40 the two bases give different answers      at price 1.12101, at open 1.12105, 4 points apart
40 passed, 0 failed

Check 16 is the shortcut on the USDJPY-type account: it puts the threshold 28 points further away than the exact answer. Checks 1 to 29 show that the search does what I wrote it to do on synthetic accounts. Whether the model matches the margin level the tester computes is a different question, and only the tester runs below can answer it.


Section 7: The threshold against the tester's crossing tick

StopOutLab.mq5 opens one position and waits for the stop-out. It sizes the position with CanAdd() so that the threshold is 1.5% of the price away at entry, the largest volume that also passes OrderCheck(). Then it does nothing until the position is closed. Every 300 seconds, and every 10 seconds once the margin level is under 60%, the recorder takes a snapshot. Watch() runs on every tick.

Two details of the tester shaped the test. It ends the whole test at the first stop-out, with the line "stop out occurred on N% of testing interval". So every run gives at most one stop-out, and I ran the EA once per start date: every two weeks, alternating buy and sell. The tester also keeps the inputs of the previous run for any input the configuration file does not set. My first three runs used an old profit target because of that, so the batch script now writes every input. The settings of all runs:

Parameter Value
Server and terminal MetaQuotes-Demo, MetaTrader 5 build 6230
Symbols and periods USDJPY and XAUUSD from 2026.01.05, EURUSD from 2026.07.06, all to 2026.09.30
Start dates Every 14 days, the side alternates
Modeling Every tick based on real ticks
Execution delay None
Chart period H1
Deposit and leverage 10,000 USD, 1:100, hedging account
Stop-out and margin call 30% and 50%
Entry First tick at or after 10:00 server time
Commission Zero, every deal in the 52 tester reports of Sections 7 and 8 shows 0.00

The inputs of StopOutLab in all 44 runs:

Input Value Meaning
InpSide LAB_BUY or LAB_SELL, alternating by start date Side of the position
InpTargetPercent 1.5 Threshold distance at entry, % of the price
InpTakePercent 0 No exit in profit
InpDeposit 10000 Balance restored before each cycle
InpRecordSeconds 300 Seconds between snapshots
InpFastLevel 60 Margin level below which snapshots come faster, percent
InpFastSeconds 10 Seconds between snapshots below that level
InpRestHours 24 Hours to wait after a cycle ends
InpEntryHour 10 No entry before this server hour
InpMaxCycles 200 Upper limit of cycles per run
InpMarginAtPrice false Default basis SOG_MARGIN_AT_OPEN (true only in my first batch)
InpRunTag The run name, for example usdjpy_0105_buy Name of the CSV file

These values are my choices for this test, not tuned results. A target of 1.5% gives a large position: 5.11 lots on USDJPY and 1.25 lots on gold at the first entry. In 35 of the 44 runs the price covered that distance within the test period, so most runs produced a stop-out to compare. A larger target would give fewer stop-outs in the same period. A smaller one would give larger volumes, deeper in the margin tiers of Section 3. The snapshot interval sets how old the last snapshot is at the crossing. Five minutes keeps the CSV files small, and the batch still wrote 480,376 snapshots. The level of 60% lies above the 50% margin call and the 30% stop-out. Below that level a snapshot comes about every 10 seconds, so the accuracy tables below describe a snapshot up to about 10 seconds old. I ran each of these inputs with one value only, so the effect of other values is not measured.

The entry hour came from a mistake. My first runs opened at the first tick of the day, inside the rollover, when the USDJPY spread was 128 points. The model holds the spread constant, so a sell entered there was predicted about 120 points too early. A snapshot 15 seconds later, with a normal spread, was already right.

What the tester did with the stop-out in these runs

My first measure was the price of the stop-out deal against the last snapshot, and on gold the difference was large. In one run the last snapshot before the crossing put the threshold at a bid of 4,364.90, and the stop-out deal came at 4,347.31. The CSV and the log explained it. The crossing tick had a bid of 4,364.36, and the tick before it 4,364.97. Ten seconds later the margin level was 5.47%, and 30 seconds after that it was below zero. The position stayed open. The tester closed it at 02:37:00, at a margin level of -9.80%.

Every one of the 35 stop-out deals in my runs has a time on the first tick of a minute. In 34 cases, the seconds field of the deal time is 00. The other one is 01:00:01, gold's first tick after its daily break. The deals came at margin levels from 29.97% down to -15.33%. In 12 cases the deal came more than a minute after the crossing tick, up to 26 minutes later. Twice the level went under 30% and recovered above the 50% margin call level before a deal. In those two cases the stop-out came later: 41 seconds later on gold, and five days later on USDJPY. This describes one tester setup: one server, one terminal build, three symbols, and one modeling mode. I have not found this timing documented, and I don't know how often a real server checks. A deal price from these runs therefore says little about the threshold.

So the measure is the crossing tick, which Watch() records. For each stop-out I compare the crossing it followed with the last snapshot taken before that crossing. In two runs the tester closed the position on the crossing tick itself, before Watch() saw it, and those two have no crossing to compare.

How close the threshold was

Symbol Runs Stop-outs Crossings compared Last snapshot vs crossing bid, points: median (largest) Largest, % of price
USDJPY 19 16 15 2 (16) 0.010%
XAUUSD 19 17 16 14 (175) 0.037%
EURUSD 6 2 2 0 (0) 0.000%

Positive numbers mean the crossing tick was further away than the threshold. This difference mixes two things: the error of the model, and the jump of the market from the last tick above the level to the first tick at or below it. The second part has nothing to do with the model. So for every crossing I also put a level price between the two ticks, on a straight line between their margin levels, and split the difference there.

Symbol Crossings Model part: snapshot vs level price, points: median (min, max) Tick part: level price vs crossing bid, points: median (max) Threshold between the bids of the two ticks
USDJPY 15 -0.4 (-4, 4) 1.6 (16) 12 of 15
XAUUSD 16 0.1 (-1, 22) 6.4 (153) 14 of 16
EURUSD 2 -0.7 (-1, -1) 0.7 (1) 2 of 2

On USDJPY the model part stayed within 4 points either way, with a median of -0.4. On gold its median was 0.1 points, and in 14 of the 16 crossings the threshold lay between the bids of the two ticks. For those 14 the ticks cannot show any model error, since the level was crossed somewhere between those two ticks and the threshold lies there too. The large gold differences are tick jumps: the tick part reached 153 points, 1.53 USD. The search answers where the level lies on the tick grid. It cannot answer where the next tick will land.

The model part is not zero either, and its larger values have one pattern. On buys it never went above 1.02 points in either direction. The larger values all belong to sells, up to 4 points on USDJPY and 22.43 points on gold. A sell is valued at the ask. The search holds the spread of the snapshot, while the split is done in bids. A spread that changed between the snapshot and the crossing therefore ends up in the model part. The CSV does not record the ask at the crossing tick, so I can't separate the spread from the rest of the model error for the sells.

The samples are small: 44 runs, 35 stop-outs, three symbols, and one server. They show how the model behaved in this setup. They are not enough to rate it across brokers, margin regimes, or instruments. EURUSD in particular gave only two crossings, too few to say more than what happened in those cases.

The prediction made at entry was much less accurate. Gold's worst case was 916 points, and that position had collected 1,212.75 USD of swap in 77 days. Each night's swap lowers the equity and moves the threshold closer. The search reads the equity as it is, so a fresh snapshot follows the drift and a prediction from entry does not. Section 9 shows that adding the swap to the entry calculation closes most of that gap.

Fig. 2 shows one USDJPY sell that stayed open for 94 days. The middle panel is the threshold bid of each snapshot minus the one at entry. The red line steps down by nearly a point every night as the swap is charged, and ends 56 points closer. The downward spikes are the rollover hours. The spread widens then, and the search carries the wide spread forward until the next snapshot.

A USDJPY sell from entry to stop-out

Bid and threshold at entry, the drift of each snapshot's threshold, and the margin level

Top: the bid and the threshold bid predicted at entry, with the stop-out deal circled. Middle: each snapshot's threshold bid minus the one at entry, in points. Bottom: the margin level, cut off at 140%

Fig. 2. Top: the bid and the threshold bid predicted at entry, with the stop-out deal circled. Middle: each snapshot's threshold bid minus the one at entry, in points. Bottom: the margin level, cut off at 140%

The last snapshot's difference, split at the level price

In basis points of the price, one column per crossing, positive when the crossing was further away than the threshold

For every crossing: the model part (last snapshot minus the level price between the two ticks) as a dot, and the tick part (level price minus the crossing bid) as a bar

Fig. 3. For every crossing: the model part (last snapshot minus the level price between the two ticks) as a dot, and the tick part (level price minus the crossing bid) as a bar

How much does the linear shortcut lose here? With a correct point value, less than its assumptions suggest. At entry it differed from the search by at most 52 points on USDJPY. On that symbol the point value changes with the price. On gold and EURUSD it differed by at most 1 point, because the default model also keeps the margin of the open position fixed. The difference is never more than 2.2% of the distance to the threshold. The point value is the bigger trap. On this server XAUUSD reports a SYMBOL_TRADE_TICK_VALUE of 0.1 for a tick of 0.01 on a 100-ounce contract. The correct value is 1.0, so a shortcut built on the reported value puts the threshold 10 times too far away. My lab EA takes the value of one tick from OrderCalcProfit() for that reason. The search never uses the tick value at all. The shortcut also has no answer for a new order whose margin jumps into a higher tier. CanAdd() is built for that case.


Section 8: Using the guard in an EA

GridGuardDemo.mq5 is a plain averaging grid. It opens 0.05 lots, adds another 0.05 lots after every 1% move against the newest position, and closes the whole grid at a profit of 100 USD. Every new grid position goes through OrderCheck() first. With InpUseGuard set, the EA also asks the guard two questions. Before every add, CanAdd() checks that the threshold will still be at least 3% of the price away after the fill. While a grid is open and the margin level is under 200%, StopOut() checks every 10 seconds how far the threshold is now. Below 1% the EA closes the grid itself and stops trading.

//+------------------------------------------------------------------+
//| Open one grid position, asking the guard first when it is on     |
//+------------------------------------------------------------------+
void OpenOne(void)
  {
   ENUM_ORDER_TYPE type=InpSell ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
//--- CanAdd() checks the stop-out distance only, free margin and the rest are OrderCheck()'s job
   if(!OrderFits(type))
      return;
   if(InpUseGuard)
     {
      SStopOutPoint after;
      if(!g_guard.CanAdd(_Symbol,type,InpLot,InpMinPercent,after))
        {
         g_refused++;
         //--- move the reference so the next try waits for one more step
         g_last_open=SymbolInfoDouble(_Symbol,InpSell ? SYMBOL_BID : SYMBOL_ASK);
         //--- a refused first position would be asked again on every tick, so wait an hour
         int count=0;
         BasketProfit(count);
         if(count==0)
            g_pause_until=TimeCurrent()+3600;
         return;
        }
     }
   bool sent=InpSell ? g_trade.Sell(InpLot,_Symbol) : g_trade.Buy(InpLot,_Symbol);
   if(sent && g_trade.ResultRetcode()==TRADE_RETCODE_DONE)
     {
      g_adds++;
      g_last_open=g_trade.ResultPrice();
     }
   else
      if(g_trade.ResultRetcode()==TRADE_RETCODE_MARKET_CLOSED)
         g_pause_until=TimeCurrent()+60;
  }
//+------------------------------------------------------------------+
//| Own exit: close the grid before the broker's stop-out            |
//+------------------------------------------------------------------+
bool OwnExit(const double profit)
  {
   if(!InpUseGuard || InpExitPercent<=0.0 || TimeCurrent()-g_last_check<InpCheckSecs)
      return(false);
   g_last_check=TimeCurrent();
//--- the margin level costs nothing to read, the search runs only when the account is near danger
   double level=CStopOutMath::MarginLevel(AccountInfoDouble(ACCOUNT_EQUITY),AccountInfoDouble(ACCOUNT_MARGIN));
   if(level>InpCheckLevel)
      return(false);
   SStopOutPoint pt;
   if(!g_guard.StopOut(_Symbol,pt))
      return(false);
   bool close=(pt.status==SOG_ALREADY_BELOW) || (pt.status==SOG_OK && MathAbs(pt.percent)<InpExitPercent);
   if(!close)
      return(false);
   double equity=AccountInfoDouble(ACCOUNT_EQUITY);
   if(!CloseAll())
      return(false);
   g_exits++;
   g_exit_loss+=profit;
   g_rec.Line(StringFormat("O,%s,%.2f,%.2f,%.3f,,,,,",TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),profit,equity,
                           MathAbs(pt.percent)));
   PrintFormat("GridGuardDemo: own exit, stop-out was %.2f%% away, grid closed at %.2f, equity before %.2f",
               MathAbs(pt.percent),profit,equity);
//--- the exit works as a circuit breaker, or the grid waits a day and starts again
   g_stopped=InpStopAfterExit;
   g_pause_until=TimeCurrent()+86400;
   return(true);
  }

The inputs of GridGuardDemo in all eight runs:

Input Value Meaning
InpSell false for the buy grids, true for the sell grids Grid side
InpLot 0.05 Volume of every grid position
InpStepPercent 1.0 Adverse move before the next add, % of the price
InpTakeMoney 100 Profit at which the whole grid is closed, USD
InpUseGuard false without the guard, true with it CanAdd() before adds and the own exit
InpMinPercent 3.0 Smallest threshold distance an add may leave, % of the price
InpExitPercent 1.0 Own exit when the threshold is closer than this, % of the price
InpCheckSecs 10 Seconds between threshold checks while a grid is open
InpCheckLevel 200 Search only below this margin level, percent
InpStopAfterExit true No new grid after an own exit
InpRunTag The run name, for example xauusd_buy_guard Name of the CSV file

These values are also my choices for the demonstration. The minimum distance of 3% equals three grid steps of 1%. An add passes only when the price could move three more steps against the grid, with the positions held after the fill, before the threshold is reached. The exit at 1% equals one grid step. Once the threshold is closer than the next add would be, the EA closes the grid itself. The search runs only below a margin level of 200% to save time. For one position whose margin is 1% of its notional value, as for gold at 1:100 on this account, a level of 200% leaves a move of about 1.7% to the 30% stop-out. The search therefore starts before the threshold can come within the 1% exit. A longer check interval than 10 seconds leaves more time for the price to pass the exit between two checks. I ran the grid with one set of these values, so the sensitivity of the results to other values is not measured.

Reading the margin level costs two AccountInfoDouble() calls, so the search runs only when the account is near danger. I ran each grid both ways, with the settings of Section 7, from 2026.01.05 to 2026.09.30 on XAUUSD and USDJPY. Every run is deterministic, so the two runs of a pair follow the same path until the guard first acts.

Grid Without the guard With the guard
XAUUSD buy 91 grids closed in profit, then a stop-out on 30 Jan at a margin level of 15.80%, balance 449.37 91 grids closed in profit, three adds refused, own exit on 30 Jan with the threshold 0.97% away, balance 2,813.37
XAUUSD sell One grid closed in profit, then a stop-out on 21 Jan at 26.98%, balance 493.18 One grid closed in profit, three adds refused, own exit on 21 Jan with the threshold just under 1% away, balance 1,843.27
USDJPY buy Seven grids closed in profit, no stop-out, balance 10,704.99 Same, no add refused, balance 10,704.99
USDJPY sell Nine grids closed in profit, no stop-out, balance 10,757.97 Same, no add refused, balance 10,757.97

Balance at the end of each grid run

2026.01.05 to 2026.09.30, every tick based on real ticks, 10,000 USD, 1:100

Balance at the end of each grid run, without the guard and with CanAdd() before every add and the own exit at 1%

Fig. 4. Balance at the end of each grid run, without the guard and with CanAdd() before every add and the own exit at 1%

The gold grids lost most of the account either way. In January gold rose from about 4,350 to above 5,400 and then fell. This averaging grid did not recover from that move. The guard did not make the grid safe. It decided where the loss stopped, and that left 2,813.37 and 1,843.27 USD instead of 449.37 and 493.18. The size of that gap also depends on the tester: the plain buy grid was closed at a margin level of 15.80%, not at 30%, so it lost more than a close at 30% would have. On USDJPY neither grid came near the stop-out, the guard never refused an add, and both pairs of runs ended with exactly the same balance.

The comparison covers four pairs of runs, on two symbols, over one period, with one set of inputs. These runs show what the guard did in this setting. They do not show that the grid became a sound strategy, or that the guard would improve results in other markets, periods, or settings.


Section 9: A consistency check in Python

Numbers printed by the code that computed them can be wrong in the same way twice. The script stopout_crosscheck.py recomputes the results from the StopOutLab CSV files with the Python 3 standard library only. The script is a second implementation of my own formulas, not an independent validation. Its formulas are simpler than the guard's, and it reads only what the EA wrote.

It solves the threshold bid of each run in closed form from the entry line: balance, volume, open price, bid, ask, and the margin after the fill. The script reads the margin basis of the run from the I line of the CSV file. With the default basis, SOG_MARGIN_AT_OPEN, the formula keeps the margin at its value after the fill on all three symbols. For EURUSD and XAUUSD it takes the equity as a straight line in the bid. For USDJPY it converts the profit at the bid. Each case then has an exact solution. All 44 runs below used the default basis. The formula for SOG_MARGIN_AT_PRICE is described at the end of this section. Then the script adds the swap the position collected to the balance, solves again, and compares the answer with the bid at the crossing tick. The script also repeats the split at the level price from the raw X lines, and the margin comparison from the S lines. The script printed this output for all 44 runs:

1, 2. Crossed past the prediction, points: median (min, max)
symbol  runs  crossings  bisection minus   |  formula with the swap        last snapshot
                         formula (min, max) |
USDJPY    19         15         (  0,  0)  |      1.0 (  -43,   16)          2.0 (   -1,   16)
XAUUSD    19         16         (  0,  0)  |     12.5 (  -14,  163)         14.0 (   -1,  175)
EURUSD     6          2         (  0,  0)  |      0.0 (    0,    0)          0.0 (    0,    0)

3. Last snapshot split at the level price between the two ticks, points: median (min, max)
symbol  crossings  model part             tick part              snapshot between    other symbols
                   (snapshot - level)     (level - crossing)     the two ticks       open
USDJPY         15     -0.4 (   -4,    4)      1.6 (    0,   16)         12 of 15          0
XAUUSD         16      0.1 (   -1,   22)      6.4 (   -1,  153)         14 of 16          0
EURUSD          2     -0.7 (   -1,   -1)      0.7 (    1,    1)          2 of 2           0

   largest model part without its sign, points: buys / sells
   USDJPY  0.86 (8) / 4.00 (7)
   XAUUSD  1.02 (8) / 22.43 (8)
   EURUSD  0.67 (1) / 0.67 (1)

4. Account margin minus model margin, percent of the account margin
symbol  snapshots  largest difference   runs where the account margin moved after the fill
USDJPY     306840              0.0000   0 of 19
XAUUSD     100418              0.0000   0 of 19
EURUSD      73118              0.0000   0 of 6

On all three symbols the bisection and the formula agree to the point in every run. With the default basis the margin of the open position is fixed, and the formula assumes the same. The comparison therefore checks the profit side of the model and the search. The swap explains the drift of the entry prediction. With the swap added, the formula lands between 43 points short of and 16 points beyond the USDJPY crossings, with a median of 1 point. The last-snapshot column repeats the medians of Section 7, the split repeats the second table there, and the last table repeats the margin comparison of Section 4, all from the CSV files alone. Gold shows the same jumps here, since the crossing tick is the same.

SOG_MARGIN_AT_PRICE is the basis of my first batch, and StopOutLab reproduces it with InpMarginAtPrice=true. For runs with this basis the script uses a second formula. On EURUSD and XAUUSD it takes the margin of a fixed volume as proportional to the price. On USDJPY it keeps the margin fixed, as before. In that batch EURUSD was the exception. The bisection came out 8 points below the formula in all six runs. On this account the margin is not proportional to the price. MarginProbe.mq5 prints the margin of 4.5 lots at prices below the market. At 1.14030 it is 7,394.05 USD. At 1.10609, 3% lower, it is 6,954.82, while a proportional margin would be 7,172.23. The notional rule from Section 3 gives 6,954.81, so the tiers are set on the notional value. A lower price moves part of the volume into a cheaper tier. The tier effect matters only for SOG_MARGIN_AT_PRICE. In that mode the guard calls OrderCalcMargin() at every price it tries and follows that curve.


What the checks do not cover

The 40 checks, the tester runs, and the Python consistency check leave these cases untested:

  1. A live server. Every stop-out in this article happened in the Strategy Tester. I have not compared a threshold with a stop-out on a real account.
  2. Other accounts and brokers. All runs used one MetaQuotes-Demo hedging account in USD with 1:100 leverage and the margin settings of that server.
  3. Money mode. Checks 2 and 17 cover it on synthetic accounts only, because the demo account uses percent mode.
  4. Several positions per side. The accuracy tables in Section 7 come from StopOutLab, which opens one position. The grid runs in Section 8 show what the guard did, not how close its threshold was to a crossing.
  5. Hedges in a stop-out. Checks 23 to 25 cover hedges on synthetic accounts, and MarginProbe measured one hedge at a single price. No tester run reached the stop-out with a hedge open.
  6. Other symbols open at the same time. Watch() counts their positions, but no lab run had a second symbol open.
  7. Other account currencies and cross rates. Section 2 shows why the search holds for the three tested symbols with a USD account. I have not shown it for other account currencies or for cross rates.
  8. The future spread and swap. The search holds both at their current values, so the checks measure a snapshot, not a forecast.
  9. Accounts with a commission. Every deal in these runs had a commission of 0.00, and CanAdd() charges none for the planned order (Section 4).
  10. Other values of the test settings. The lab target of 1.5%, the snapshot intervals, and the grid values of 3%, 1%, and 200% were each run with one value. Their effect on the results is not measured.


Limitations

The guard computes a threshold price under fixed assumptions. The guard does not predict the next market tick, and it does not predict the price of a stop-out deal. The search covers 50% of the price on each side by default. Beyond that it reports SOG_OUT_OF_RANGE without a price.

The search moves one symbol and holds every other price still. A position whose profit is converted through another symbol, such as GBPJPY on a USD account, also depends on USDJPY, and a portfolio of several symbols can move together. The guard reports each symbol on its own and does not combine them. Watch() reads the account's equity and margin, so with other symbols open a crossing may not belong to the watched symbol. It counts those positions but cannot tell which symbol caused the crossing.

The spread is held at its value when the search runs. A sell is valued at the ask, so a spread that widens later, at the rollover or around news, brings a sell's real threshold closer than predicted. A prediction made inside a rollover spike carries the wide spread forward instead. The USDJPY example in Section 7 was off by about 120 points for that reason.

Swaps and commissions are part of today's equity, but the search does not project them forward. A position held for weeks collects swap every night, and the threshold moves with it. A fresh snapshot follows that drift. A prediction made at entry does not.

The margin model takes each side's total volume, charges it at the open price by default, and charges the larger side. This rule matches the tester on MetaQuotes-Demo. There the margin of an open position stayed at its value from the fill, and the hedged sell in Section 3 added no margin. A live server may charge at the current price instead. Other SYMBOL_MARGIN_HEDGED settings, exchange and futures instruments, portfolio margin, and broker-specific rules are not modeled. The margin_check field shows a mismatch at the current price only when no other symbol is open. The tester runs held one position on one side, so the hedge rule itself was not tested in a stop-out.

The bisection relies on the gap crossing zero once between two scan steps. Section 2 shows why this holds for the tested symbols with a USD account. For other cases the scan finds a second crossing only if it is wider than one scan step.

CanAdd() is not an order check. The method ignores free margin, stop and freeze levels, slippage, partial fills, spread changes before the fill, and the commission of the planned order.

All of the tests ran in the Strategy Tester on one server, MetaQuotes-Demo, with one terminal build, three symbols, and parts of 2026. The timing of the stop-out deals described in Section 7 belongs to this setup. The thresholds were compared with the tester's crossing tick, not with a real server's stop-out. I have not checked any of this on a real broker server.

The volume tiers in Section 3 belong to this account. Another broker may have none, or other steps, or different ones per symbol. The guard calls OrderCalcMargin() for each side's total volume, so it follows the tiers reported by the terminal. However, the aggregation across sides is my own rule derived from this server.

The live checks in Section 6 call the same terminal functions as the guard, so they test the code, not the terminal's agreement with the server. The Python script reuses my formulas in a simpler form. It assumes one position. With the default basis it keeps the margin at its value after the fill. With SOG_MARGIN_AT_PRICE it takes the margin of a fixed volume on EURUSD and XAUUSD as proportional to the price. Its level price assumes the margin level changes along a straight line between two neighboring ticks.

The grid results come from four pairs of runs on two symbols over one period with one set of inputs.


Conclusion

CStopOutGuard computes a threshold price. The threshold price is the first bid on the tick grid at which the modeled margin level of one symbol's positions reaches the stop-out level, with every other price, the spread, and the swaps held as they are. A broker does not necessarily close the positions at that price. The closing price depends on the server's checks and on the next tick. CanAdd() shows how much closer a planned order would bring the threshold, with the side-wide volume tiers included. The method adds no commission for that order, so it applies as written to accounts without an entry commission. Neither needs a tick value or a leverage figure. Both ask the terminal what the positions would be worth, and what margin they would need, at a hypothetical price.

In 44 tester runs on one demo server, the last snapshot before the crossing was a median of 2 points from the crossing tick on USDJPY and 14 points on gold. Split at the level price between the two ticks, the model's own part stayed within 1.02 points on every buy and reached 22 points on sells. On sells a changed spread falls into the model part. Most of the gold difference was the jump between two ticks. EURUSD gave only two crossings. The margin check built into the class showed that my first model charged open positions at the moved price while the tester kept their margin at its value from the fill, and the default now follows the tester. A prediction made at entry drifts with the swap, so the search has to be repeated while a position is open. In four pairs of grid runs, the guard refused adds and closed the gold grids before the tester's stop-out, and changed nothing on USDJPY. This result holds for those runs and is not evidence that the guard improves a grid in general.

Two findings from this work are worth checking on your own account. MetaQuotes-Demo charges margin in volume tiers on the whole side of a symbol, so the margin of a new order depends on what is already open. In the 35 stop-outs of these runs, the tester closed positions on the first tick of a minute, sometimes long after the crossing tick. A backtest like these can therefore hold positions at margin levels far below the stop-out level. I have not tested whether other builds or servers behave the same way.

To try it, unpack MQL5.zip into the terminal's data folder and run TestStopOutGuard.mq5 on any chart. Then run StopOutLab.mq5 in the Strategy Tester with real ticks, and run stopout_crosscheck.py on the CSV file it writes to the common Files folder.

Attached files

# Name Folder Description
1 StopOutTypes.mqh MQL5/Include/StopOutGuard/ Status codes, SStopOutRules, SStopOutPoint
2 StopOutMath.mqh MQL5/Include/StopOutGuard/ IAccountModel and CStopOutMath: level arithmetic, the threshold search, the linear shortcut
3 StopOutGuard.mqh MQL5/Include/StopOutGuard/ CSymbolModel and CStopOutGuard: StopOut(), MarginCall(), CanAdd(), margin_check
4 StopOutRecorder.mqh MQL5/Include/StopOutGuard/ CStopOutRecorder: snapshots, crossing ticks with the tick before, and stop-out deals in a CSV file
5 TestStopOutGuard.mq5 MQL5/Scripts/StopOutGuard/ Verification script, 40 checks with PASS or FAIL
6 StopOutProbe.mq5 MQL5/Scripts/StopOutGuard/ Prints OrderCalcProfit() and OrderCalcMargin() at the market and 5% and 10% away
7 StopOutLab.mq5 MQL5/Experts/StopOutGuard/ Tester EA: one oversized position, snapshots until the stop-out
8 GridGuardDemo.mq5 MQL5/Experts/StopOutGuard/ Averaging grid with OrderCheck() and an optional CanAdd() check before every add
9 MarginProbe.mq5 MQL5/Experts/StopOutGuard/ Tester EA that prints the margin of several volumes and of two positions on one side
10 stopout_crosscheck.py MQL5/Files/StopOutGuard/ Python 3 consistency check that recomputes the results from the StopOutLab CSV files
11 MQL5.zip Unpack into the terminal's data folder All 10 files, with MQL5 as the root folder and a StopOutGuard subfolder in Include, Scripts, Experts, and Files

Every MQL5 file compiles with 0 errors and 0 warnings in MetaEditor build 6230. Tested on MetaTrader 5 build 6230, MetaQuotes-Demo, hedging account.

Attached files |
StopOutTypes.mqh (3.43 KB)
StopOutGuard.mqh (17.77 KB)
StopOutRecorder.mqh (15.77 KB)
StopOutProbe.mq5 (2.99 KB)
StopOutLab.mq5 (13.27 KB)
GridGuardDemo.mq5 (11.15 KB)
MarginProbe.mq5 (4.53 KB)
MQL5.zip (28.7 KB)
Native SFTP Client in MQL5: Uploading Trade Reports over SSH Without External Tools Native SFTP Client in MQL5: Uploading Trade Reports over SSH Without External Tools
Send MetaTrader 5 trade reports to an SFTP server without WinSCP or external scripts. A pure-MQL5 SSH/SFTP client uses host-key pinning, safe packet handling and a temporary “.part” swap to avoid partial files, while an EA writes daily CSV reports and a service uploads them. The article also explains a Strategy Tester case where the final closing deal misses OnTradeTransaction and how to capture it
Building a Dynamic Drop List in MQL5 Building a Dynamic Drop List in MQL5
This article describes CDropList, a composite class that implements an interactive drop-down list from standard MQL5 chart objects. It details creation/destruction, coordinates and sizes, color configuration, item management, and a Refresh method that keeps objects in sync. Event handling covers opening/closing, hover highlight, item clicks, and scrolling, helping you embed consistent selection controls in indicators, dashboards, and trading panels.
Neural Networks in Trading: Bidirectional Adaptive Temporal Correlation (Conclusion) Neural Networks in Trading: Bidirectional Adaptive Temporal Correlation (Conclusion)
The BAT framework transforms a chaotic stream of market data into accurate forecasts and well-informed trading decisions. Backtesting shows steady capital growth with controlled risks. The model's architecture is simple, scalable, and ready for further optimization.
Developing Smart Chart Objects in MQL5 (Part 3): Integrating Lifecycle Alerts into Managed Trendlines Developing Smart Chart Objects in MQL5 (Part 3): Integrating Lifecycle Alerts into Managed Trendlines
This article adds a lifecycle-driven alert layer to the Smart Trendline Manager. Alerts originate from state transitions (touch, bounce, break, resurrection), pass configurable event and source filters, and are delivered via terminal popups and push notifications. You will see how to wire the alert engine through the manager, configure inputs in the indicator, and receive timely notifications without constant chart monitoring.