//+------------------------------------------------------------------+
//|                                                   StopOutLab.mq5 |
//|                                       Copyright 2026, Ali Rajput |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, Ali Rajput"
#property version   "1.10"
#property description "Opens one oversized position at a time and waits for a stop-out, to compare"
#property description "the threshold price with the tick at which the stop-out level was crossed."
//+------------------------------------------------------------------+
//| Includes                                                         |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>
#include <StopOutGuard\StopOutRecorder.mqh>
//+------------------------------------------------------------------+
//| Side of each new position                                        |
//+------------------------------------------------------------------+
enum ENUM_LAB_SIDE
  {
   LAB_BUY=0,       // always buy
   LAB_SELL=1,      // always sell
   LAB_ALTERNATE=2  // buy, then sell, then buy
  };
//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
input ENUM_LAB_SIDE InpSide          = LAB_ALTERNATE; // Side of each position
input double        InpTargetPercent = 1.5;           // Stop-out distance at entry, % of price
input double        InpTakePercent   = 0.0;           // Close in profit after this move, % of price (0: never)
input double        InpDeposit       = 10000.0;       // Balance restored before each cycle
input int           InpRecordSeconds = 300;           // Seconds between snapshots
input double        InpFastLevel     = 60.0;          // Below this margin level, snapshots come faster
input int           InpFastSeconds   = 10;            // Seconds between snapshots below that level
input int           InpRestHours     = 24;            // Hours to wait after a cycle ends
input int           InpEntryHour     = 10;            // No entry before this server hour (rollover spreads)
input int           InpMaxCycles     = 200;           // Stop the test after this many cycles
input bool          InpMarginAtPrice = false;         // Charge the margin at the moved price, not at the open price
input string        InpRunTag        = "";            // CSV name tag (empty: no CSV)
//+------------------------------------------------------------------+
//| Global objects and state                                         |
//+------------------------------------------------------------------+
CTrade           g_trade;                 // order sending
CStopOutGuard    g_guard;                 // stop-out search
CStopOutRecorder g_rec;                   // snapshots and stop-out deals
int              g_cycles=0;              // cycles started
int              g_stopouts=0;            // cycles that ended in a stop-out
int              g_takes=0;               // cycles that ended in profit
bool             g_open=false;            // a cycle is running
bool             g_buy=true;              // side of the running cycle
double           g_entry=0.0;             // open price of the running cycle
double           g_entry_pred=0.0;        // stop-out bid predicted at entry
double           g_entry_naive=0.0;       // stop-out bid from the linear shortcut
datetime         g_last_snap=0;           // time of the last snapshot
datetime         g_rest_until=0;          // no new cycle before this time
int              g_events_seen=0;         // stop-out deals already reported
//+------------------------------------------------------------------+
//| True if a position of this volume fits and keeps the distance    |
//+------------------------------------------------------------------+
bool FarEnough(const ENUM_ORDER_TYPE type,const double volume)
  {
//--- the order must also fit into the free margin, or the server refuses it
   MqlTradeRequest req={};
   MqlTradeCheckResult chk={};
   req.action=TRADE_ACTION_DEAL;
   req.symbol=_Symbol;
   req.volume=volume;
   req.type=type;
   req.price=SymbolInfoDouble(_Symbol,type==ORDER_TYPE_BUY ? SYMBOL_ASK : SYMBOL_BID);
   req.deviation=10;
   req.type_filling=ORDER_FILLING_FOK;
   if(!OrderCheck(req,chk) || chk.retcode!=0)
      return(false);
   SStopOutPoint pt;
   g_guard.CanAdd(_Symbol,type,volume,0.0,pt);
//--- out of range means the stop-out is further away than the whole search range
   if(pt.status==SOG_OUT_OF_RANGE)
      return(true);
   return(pt.status==SOG_OK && MathAbs(pt.percent)>=InpTargetPercent);
  }
//+------------------------------------------------------------------+
//| Largest volume whose stop-out distance is still the target       |
//+------------------------------------------------------------------+
double SizeForTarget(const ENUM_ORDER_TYPE type)
  {
   double vmin=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
   double vmax=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
   double step=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
   SStopOutPoint pt;
   if(!FarEnough(type,vmin))
      return(0.0);
//--- the distance shrinks as the volume grows, so a bisection on the volume finds the target
   double lo=vmin,hi=vmax;
   for(int i=0; i<60 && hi-lo>step; i++)
     {
      //--- every try is a volume the server accepts, a whole number of steps
      double mid=MathMax(vmin,MathFloor(0.5*(lo+hi)/step+1e-9)*step);
      if(mid<=lo)
         break;
      if(FarEnough(type,mid))
         lo=mid;
      else
         hi=mid;
     }
   return(MathFloor(lo/step+1e-9)*step);
  }
//+------------------------------------------------------------------+
//| Linear shortcut: fixed margin and today's value of one tick      |
//+------------------------------------------------------------------+
double NaiveStopOutBid(const bool buy,const double volume)
  {
   SStopOutRules r=g_guard.Rules();
   double ts=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
   double bid=SymbolInfoDouble(_Symbol,SYMBOL_BID);
//--- the value of one tick is taken from OrderCalcProfit(), not from SYMBOL_TRADE_TICK_VALUE,
//--- so the shortcut is not hurt by a wrong tick value in the symbol settings
   double tv=0.0;
   if(!OrderCalcProfit(ORDER_TYPE_BUY,_Symbol,1.0,bid,bid+ts,tv))
      return(0.0);
   double dist=CStopOutMath::LinearDistance(r.percent,r.stop_out,AccountInfoDouble(ACCOUNT_EQUITY),
                                            AccountInfoDouble(ACCOUNT_MARGIN),volume,tv,ts);
   return(buy ? bid-dist : bid+dist);
  }
//+------------------------------------------------------------------+
//| Open the position of a new cycle                                 |
//+------------------------------------------------------------------+
void StartCycle(void)
  {
//--- every cycle starts from the same balance, so every cycle has the same size
   double balance=AccountInfoDouble(ACCOUNT_BALANCE);
   if(MQLInfoInteger(MQL_TESTER) && balance<InpDeposit)
      TesterDeposit(InpDeposit-balance);
   if(MQLInfoInteger(MQL_TESTER) && balance>InpDeposit)
      TesterWithdrawal(balance-InpDeposit);
   g_buy=(InpSide==LAB_BUY) || (InpSide==LAB_ALTERNATE && g_cycles%2==0);
   ENUM_ORDER_TYPE type=g_buy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
   double volume=SizeForTarget(type);
   if(volume<=0.0)
      return;
   bool sent=g_buy ? g_trade.Buy(volume,_Symbol) : g_trade.Sell(volume,_Symbol);
   if(!sent || PositionsTotal()==0)
     {
      //--- a refused order is retried a minute later, not on every tick
      g_rest_until=TimeCurrent()+60;
      PrintFormat("StopOutLab: entry of %.2f lots refused, retcode %u",volume,g_trade.ResultRetcode());
      return;
     }
   g_cycles++;
   g_open=true;
   g_entry=g_trade.ResultPrice();
   SStopOutPoint pt;
   g_guard.StopOut(_Symbol,pt);
   g_entry_pred=pt.bid_at;
   g_entry_naive=NaiveStopOutBid(g_buy,volume);
   int digits=(int)_Digits;
   MqlTick t;
   SymbolInfoTick(_Symbol,t);
   g_rec.Line(StringFormat("E,%s,%s,%.2f,%s,%s,%s,%.2f,%.2f,%d,%s,%s",TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
                           g_buy ? "buy" : "sell",volume,DoubleToString(g_entry,digits),
                           DoubleToString(g_entry_pred,digits),DoubleToString(g_entry_naive,digits),
                           AccountInfoDouble(ACCOUNT_BALANCE),AccountInfoDouble(ACCOUNT_MARGIN),g_cycles,
                           DoubleToString(t.bid,digits),DoubleToString(t.ask,digits)));
   PrintFormat("StopOutLab: cycle %d %s %.2f at %s, stop-out predicted at bid %s (%.2f%%), linear shortcut %s",
               g_cycles,g_buy ? "buy" : "sell",volume,DoubleToString(g_entry,digits),
               DoubleToString(g_entry_pred,digits),pt.percent,DoubleToString(g_entry_naive,digits));
   g_last_snap=0;
  }
//+------------------------------------------------------------------+
//| Report the stop-out deals that arrived since the last call       |
//+------------------------------------------------------------------+
void ReportNewEvents(void)
  {
   SStopOutEvent ev;
   while(g_events_seen<g_rec.Events() && g_rec.Event(g_events_seen,ev))
     {
      g_events_seen++;
      //--- the entry prediction is a bid, a sell position closes at the ask
      double spread=SymbolInfoDouble(_Symbol,SYMBOL_ASK)-SymbolInfoDouble(_Symbol,SYMBOL_BID);
      double entry_close=ev.buy_closed ? g_entry_pred : g_entry_pred+spread;
      PrintFormat("StopOutLab: cycle %d stop-out deal at %s, threshold at entry %s, at the last snapshot %s",
                  g_cycles,DoubleToString(ev.price,_Digits),DoubleToString(entry_close,_Digits),
                  DoubleToString(ev.snap_close,_Digits));
     }
  }
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(!g_guard.LoadRules())
      return(INIT_FAILED);
   g_guard.SetMarginBasis(InpMarginAtPrice ? SOG_MARGIN_AT_PRICE : SOG_MARGIN_AT_OPEN);
   string csv=(InpRunTag=="") ? "" : "StopOutLab_"+InpRunTag+".csv";
   if(!g_rec.Init(GetPointer(g_guard),_Symbol,csv))
      return(INIT_FAILED);
   SStopOutRules r=g_guard.Rules();
   g_rec.Line(StringFormat("I,%s,%s,%.0f,%d,%.2f,%.2f,%s,%s,%d,%s",TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),
                           _Symbol,SymbolInfoDouble(_Symbol,SYMBOL_TRADE_CONTRACT_SIZE),
                           (int)AccountInfoInteger(ACCOUNT_LEVERAGE),r.stop_out,r.call,
                           SymbolInfoString(_Symbol,SYMBOL_CURRENCY_BASE),SymbolInfoString(_Symbol,SYMBOL_CURRENCY_PROFIT),
                           (int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_CALC_MODE),InpMarginAtPrice ? "price" : "open"));
   PrintFormat("StopOutLab: %s, stop-out %.2f%s, margin call %.2f, target %.2f%%, take %.2f%%",
               _Symbol,r.stop_out,r.percent ? "%" : " money",r.call,InpTargetPercent,InpTakePercent);
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   g_rec.ScanHistory(0);
   ReportNewEvents();
   g_rec.Report();
//--- the tester ends the test at a stop-out, so the deals are counted here
   g_stopouts=g_rec.Events();
   PrintFormat("StopOutLab: %d cycles, %d stop-outs, %d closed in profit",g_cycles,g_stopouts,g_takes);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   if(g_open)
     {
      //--- the cycle ends when its position is gone
      if(!PositionSelect(_Symbol))
        {
         g_open=false;
         ReportNewEvents();
         g_rest_until=TimeCurrent()+InpRestHours*3600;
         return;
        }
      g_rec.Watch();
      double bid=SymbolInfoDouble(_Symbol,SYMBOL_BID);
      double move=100.0*(bid-g_entry)/g_entry*(g_buy ? 1.0 : -1.0);
      if(InpTakePercent>0.0 && move>=InpTakePercent)
        {
         g_trade.PositionClose(_Symbol);
         g_open=false;
         g_takes++;
         g_rest_until=TimeCurrent()+InpRestHours*3600;
         return;
        }
      double level=CStopOutMath::MarginLevel(AccountInfoDouble(ACCOUNT_EQUITY),AccountInfoDouble(ACCOUNT_MARGIN));
      int every=(level<InpFastLevel) ? InpFastSeconds : InpRecordSeconds;
      if(TimeCurrent()-g_last_snap>=every)
        {
         SStopOutPoint pt;
         g_rec.Snapshot(pt);
         g_last_snap=TimeCurrent();
        }
      return;
     }
   if(g_cycles>=InpMaxCycles)
     {
      ExpertRemove();
      return;
     }
   MqlDateTime now;
   TimeToStruct(TimeCurrent(),now);
   if(TimeCurrent()>=g_rest_until && now.hour>=InpEntryHour)
      StartCycle();
  }
//+------------------------------------------------------------------+
//| Trade transaction handler                                        |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,const MqlTradeRequest &request,const MqlTradeResult &result)
  {
   g_rec.OnTransaction(trans);
  }
//+------------------------------------------------------------------+
