//+------------------------------------------------------------------+
//|                                       GoldTrackerAutoTrade.mq5   |
//|                          Copyright 2024-2026, GoldTracker.ai     |
//|                              https://www.goldtracker.ai          |
//+------------------------------------------------------------------+
#property copyright "GoldTracker.ai"
#property link      "https://www.goldtracker.ai"
#property version   "3.08"
#property description "AI Auto-Trading EA: Polls GoldTracker.ai for AI trade signals and executes them on MT5."
#property description "IMPORTANT: Add www.goldtracker.ai to MT5 Tools -> Options -> Expert Advisors -> Allow WebRequest URLs"
#property strict

//--- Input parameters
// SECURITY (D062): this default previously contained the LIVE signal key, and this file is served
// publicly at https://www.goldtracker.ai/GoldTrackerAutoTrade.mq5 with no credential required —
// verified by downloading it anonymously and getting HTTP 200 from /api/signals/latest with the
// embedded key. That key does not merely READ signals: the same credential authorises
// /api/signals/executed, /close and /command-ack, so anyone holding it could inject fabricated
// trades and closes, which would drive the safety governor and corrupt the execution audit trail.
// Paste your own key from the Admin Dashboard into this input after attaching the EA.
input string ApiKey              = "PASTE_YOUR_SIGNAL_KEY_HERE";                    // Signal API Key (from Admin Dashboard)
input string ServerURL           = "https://www.goldtracker.ai/api/signals/latest";       // Signal endpoint URL
input string ExecutedURL         = "https://www.goldtracker.ai/api/signals/executed";     // Execution report URL
input string CloseURL            = "https://www.goldtracker.ai/api/signals/close";        // Trade close report URL
input string PartialCloseURL     = "https://www.goldtracker.ai/api/signals/partial-close"; // Partial TP report URL
input string ManageURL           = "https://www.goldtracker.ai/api/signals/manage";       // Trade management URL
input string AckURL              = "https://www.goldtracker.ai/api/signals/command-ack";  // D058 command acknowledgement
input int    CheckIntervalSeconds = 30;                                                   // Poll interval (seconds)
input double MaxLots             = 0.10;                                                  // Maximum lot size per trade
input double RiskPercent         = 1.0;                                                   // Risk % (fallback if server doesn't send)
input bool   UseServerRisk       = true;                                                  // Use server-recommended risk (Kelly)
input bool   UseFinalTargetTP    = false;                                                 // Opt-in: requires server partialLadderEnabled too
input bool   AutoExecute         = true;                                                  // Auto-execute (true = no confirmation needed)
input int    MaxOpenTrades       = 2;                                                     // Max concurrent AI trades
input string TradeSymbol         = "XAUUSD";                                              // Symbol to trade
input int    MagicNumber         = 202604;                                                // Magic number for AI trades
input int    Slippage            = 30;                                                    // Max slippage in points

//--- Build identity.
// The MT5 title bar shows #property version, but nothing reached the SERVER, so the only way to
// tell which build was attached was to count function call sites in the source. That is the same
// inference problem D057 fixed for the server by putting the build SHA in application_name.
// EA_VERSION now rides on every request, so /api/health states the attached build outright.
#define EA_VERSION "3.08"

//--- Global variables
string executedSignalIds[];     // Track executed signal IDs to prevent duplicates
int    executedCount = 0;
int    g_ackRetryOffset = 0;
int    g_commandFileSerial = 0;

// D058 — execution audit state. Declared here, before first use, because MQL5 resolves globals in
// declaration order.
//
// g_lastRetcode: the broker's answer to the last management action. A rejected modification is
//   evidence, not noise — it separates "the policy asked for X" from "the position was at X", and
//   until now it existed only in this terminal's log.
// g_lastOrderTicket / g_lastDealTicket / g_lastFillPrice: the authoritative identifiers and fill
//   from MqlTradeResult. The execution report used to rediscover its ticket by scanning for the
//   most recent magic-number position, which binds the fill to the wrong ticket whenever more than
//   one is open.
int    g_lastRetcode     = 0;
ulong  g_lastOrderTicket = 0;
ulong  g_lastDealTicket  = 0;
double g_lastFillPrice   = 0;

//+------------------------------------------------------------------+
//| Expert initialization function                                     |
//+------------------------------------------------------------------+
int OnInit()
{
   Print("[GoldTracker AI] ", EA_VERSION, " starting...");
   if(StringLen(ApiKey) == 0)
   {
      Print("[GoldTracker AI] ERROR: ApiKey is empty. Get your signal key from Admin Dashboard -> AI Trading tab.");
      return(INIT_PARAMETERS_INCORRECT);
   }
   if(StringLen(ApiKey) > 4096 || StringFind(ApiKey, "\r") >= 0 || StringFind(ApiKey, "\n") >= 0)
   {
      Print("[GoldTracker AI] ERROR: ApiKey is not a valid single-line header value.");
      return(INIT_PARAMETERS_INCORRECT);
   }

   // Validate symbol exists
   if(!SymbolSelect(TradeSymbol, true))
   {
      Print("[GoldTracker AI] WARNING: Symbol ", TradeSymbol, " may not be available on your broker.");
   }

   EventSetTimer(CheckIntervalSeconds);

   Print("[GoldTracker AI] ====================================");
   Print("[GoldTracker AI] EA initialized successfully");
   Print("[GoldTracker AI] Symbol: ", TradeSymbol);
   Print("[GoldTracker AI] Poll interval: ", CheckIntervalSeconds, "s");
   Print("[GoldTracker AI] Max lots: ", DoubleToString(MaxLots, 2));
   Print("[GoldTracker AI] Risk: ", DoubleToString(RiskPercent, 1), "% (fallback)");
   Print("[GoldTracker AI] Server Kelly risk: ", UseServerRisk ? "ENABLED" : "DISABLED");
   Print("[GoldTracker AI] Auto-execute: ", AutoExecute ? "YES" : "NO (confirm dialog)");
   Print("[GoldTracker AI] Close report: ", CloseURL);
   Print("[GoldTracker AI] Trade management: ", ManageURL);
   Print("[GoldTracker AI] Max open trades: ", MaxOpenTrades);
   Print("[GoldTracker AI] Server: ", ServerURL);
   Print("[GoldTracker AI] ====================================");

   // Initial check on startup
   ReportTerminalState("heartbeat", 0, 0);
   CheckForSignals();

   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                    |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   EventKillTimer();
   Print("[GoldTracker AI] EA removed. Reason: ", reason);
}

//+------------------------------------------------------------------+
//| Timer function                                                      |
//+------------------------------------------------------------------+
void OnTimer()
{
   ManageOpenTrades();
   RetryCommandAcks(); // Bounded retries run after protective management, even when flat.
   ReportTerminalState("heartbeat", 0, 0);
   CheckForSignals();
}

//+------------------------------------------------------------------+
//| Check for new AI signals                                           |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Shared HTTP headers.                                              |
//|                                                                   |
//| 2026-08-27: added User-Agent. MT5's WebRequest does NOT add a     |
//| default User-Agent when you pass a custom header string, so every |
//| request left here with no UA. A UA-less request from a datacenter |
//| IP is a standard bot-filter trigger, and the terminal was getting |
//| "Server returned HTTP 403" every 30s while a browser on the SAME  |
//| machine, hitting the SAME URL with the SAME key, returned 200.    |
//| Nothing in the server returns 403 for this path, so the block is  |
//| upstream of it.                                                   |
//|                                                                   |
//| This also matters far beyond polling: the same transport posts    |
//| trade CLOSE reports. Reports lost to 403s are what starved the    |
//| server of closes and triggered its (now removed) 24h "stale       |
//| cleanup", which invented ~21 fabricated outcomes and fed them to  |
//| the learning loop.                                                |
//+------------------------------------------------------------------+
string HttpHeaders()
{
   return "Content-Type: application/json\r\n"
          "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) GoldTrackerEA/" + EA_VERSION + "\r\n"
          "Accept: application/json\r\n"
          "X-Signal-Key: " + ApiKey + "\r\n";
}

string HttpDiagnostic(string value)
{
   // A proxy/error response can echo request credentials. Redact before truncation.
   if(StringLen(ApiKey) > 0) StringReplace(value, ApiKey, "[REDACTED]");
   return StringSubstr(value, 0, 300);
}

//+------------------------------------------------------------------+
//| WebRequest with retry + full diagnostics on failure.              |
//| Returns the HTTP status (or -1). Fills `body` with the response.  |
//|                                                                   |
//| The old code fired once and discarded the response body on any    |
//| non-200, so a failure told us the status code and nothing else.   |
//| On a close report that meant the outcome was lost permanently.    |
//+------------------------------------------------------------------+
int HttpRequest(string method, string url, char &postData[], string &body, string tag, int attempts = 3, int timeoutMs = 10000)
{
   char   result[];
   string responseHeaders;
   int    res = -1;

   for(int i = 0; i < attempts; i++)
   {
      if(i > 0) Sleep(1500);          // brief backoff between attempts
      ArrayFree(result);
      string headers = HttpHeaders();
      res = WebRequest(method, url, headers, timeoutMs, postData, result, responseHeaders);

      if(res == -1)
      {
         int err = GetLastError();
         if(err == 4014)
         {
            Print("[GoldTracker AI] ERROR: WebRequest not allowed. Tools -> Options -> Expert Advisors -> Allow WebRequest, and add the server URL.");
            return -1;                 // config error: retrying cannot help
         }
         Print("[GoldTracker AI] ", tag, " WebRequest failed (attempt ", i + 1, "/", attempts, "). Error: ", err);
         continue;
      }

      body = CharArrayToString(result, 0, WHOLE_ARRAY, CP_UTF8);
      if(res == 200) return 200;

      // Non-200: log WHO rejected us. This is what identifies an upstream
      // bot-filter/WAF versus our own application.
      Print("[GoldTracker AI] ", tag, " HTTP ", res, " (attempt ", i + 1, "/", attempts, ")");
      Print("[GoldTracker AI] ", tag, " response body: ", HttpDiagnostic(body));
      Print("[GoldTracker AI] ", tag, " response headers: ", HttpDiagnostic(responseHeaders));
   }
   return res;
}

// Telemetry never changes trading permissions or retries an order.
void ReportTerminalState(string kind, int retcode, int errorCode)
{
   static datetime lastReport=0;
   if(kind=="heartbeat" && TimeLocal()-lastReport<60)return;
   lastReport=TimeLocal();
   string url=ServerURL;
   int suffix=StringFind(url,"/api/signals/latest");
   if(suffix<0)return;
   url=StringSubstr(url,0,suffix)+"/api/signals/telemetry";
   string json="{\"kind\":\""+kind+"\",\"eaVersion\":\""+EA_VERSION+"\","+
       "\"terminalAllowed\":"+(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED)?"true":"false")+","+
       "\"eaAllowed\":"+(MQLInfoInteger(MQL_TRADE_ALLOWED)?"true":"false")+","+
       "\"accountAllowed\":"+((AccountInfoInteger(ACCOUNT_TRADE_ALLOWED)&&AccountInfoInteger(ACCOUNT_TRADE_EXPERT))?"true":"false")+","+
       "\"connected\":"+(TerminalInfoInteger(TERMINAL_CONNECTED)?"true":"false")+","+
       "\"retcode\":"+IntegerToString(retcode)+",\"errorCode\":"+IntegerToString(errorCode)+"}";
   char payload[];int copied=StringToCharArray(json,payload,0,WHOLE_ARRAY,CP_UTF8);
   if(copied>0)ArrayResize(payload,copied-1);
   string response;HttpRequest("POST",url,payload,response,"Telemetry",1,1500);
}

void CheckForSignals()
{
   // Build URL with API key
   string url = ServerURL + "?ea=" + EA_VERSION
                + "&ladder=" + (UseFinalTargetTP ? "1" : "0");

   // Send HTTP GET request (retries, and logs the response body on any failure)
   char   postData[];
   string response = "";
   int res = HttpRequest("GET", url, postData, response, "SignalPoll");
   if(res != 200) return;

   // Check if there's a signal
   bool hasSignal = false;
   if(StringFind(response, "\"hasSignal\":true") >= 0 || StringFind(response, "\"hasSignal\": true") >= 0)
      hasSignal = true;

   if(!hasSignal)
   {
      static string lastReason="";
      string reason=ExtractJsonString(response,"reason");
      if(reason!=lastReason){if(StringLen(reason)>0)Print("[GoldTracker AI] No entry: ",reason);lastReason=reason;}
      return;
   }

   // Check if already executed
   if(StringFind(response, "\"alreadyExecuted\":true") >= 0 || StringFind(response, "\"alreadyExecuted\": true") >= 0)
      return;

   // Check if server paused trading (drawdown protection)
   string pausedStr = ExtractJsonString(response, "paused");
   if(pausedStr == "true")
   {
      string reason = ExtractJsonString(response, "reason");
      Print("[GoldTracker AI] Server PAUSED trading: ", reason);
      return;
   }

   // Parse server-recommended risk (Kelly-based)
   double serverRisk = ExtractJsonDouble(response, "recommendedRisk");

   // Parse signal fields (nested inside "signal":{})
   string direction  = ExtractJsonString(response, "direction");
   double entry      = ExtractJsonDouble(response, "entry");
   double sl         = ExtractJsonDouble(response, "sl");
   double tp1        = ExtractJsonDouble(response, "tp1");
   double tp2        = ExtractJsonDouble(response, "tp2");
   double tp3        = ExtractJsonDouble(response, "tp3");
   int    confidence = (int)ExtractJsonDouble(response, "confidence");
   double timestamp  = ExtractJsonDouble(response, "timestamp");
   // Use server signal ID (format: sig_<timestamp>_<direction>)
   string signalId   = ExtractJsonString(response, "id");
   if(StringLen(signalId) == 0)
      signalId = "sig_" + DoubleToString(timestamp, 0) + "_" + direction; // fallback

   if(StringLen(direction) == 0 || entry <= 0 || sl <= 0)
   {
      Print("[GoldTracker AI] Invalid signal data — direction:", direction, " entry:", entry, " sl:", sl);
      return;
   }

   Print("[GoldTracker AI] Signal parsed: ", direction, " @ ", entry, " SL:", sl, " TP1:", tp1, " Conf:", confidence, "%");

   // Check if we already executed this signal
   if(IsSignalExecuted(signalId))
   {
      return; // Already handled
   }

   // Check max open trades
   int aiTrades = CountAITrades();
   if(aiTrades >= MaxOpenTrades)
   {
      Print("[GoldTracker AI] Max open trades reached (", aiTrades, "/", MaxOpenTrades, "). Skipping signal: ", signalId);
      MarkSignalExecuted(signalId); // Don't keep retrying
      return;
   }

   // Calculate lot size — use server Kelly risk if available
   double effectiveRisk = RiskPercent;
   if(UseServerRisk && serverRisk > 0)
   {
      effectiveRisk = serverRisk;
      Print("[GoldTracker AI] Using server Kelly risk: ", DoubleToString(effectiveRisk, 2), "%");
   }
   double lots = CalculateLotSizeWithRisk(direction, entry, sl, effectiveRisk);
   if(lots <= 0)
   {
      Print("[GoldTracker AI] Calculated lot size is 0 or negative. Skipping.");
      return;
   }

   // Cap at MaxLots
   if(lots > MaxLots) lots = MaxLots;

   // D049 restoration (EA 3.04): the broker TP must be the FINAL target, not TP1.
   // Pinning it at TP1 closed the ENTIRE position at the first waypoint on tick — the
   // server's partial-close commands always arrived at a flat position (271 of 271 closes
   // at full size; D049 removed the ladder as dead code) and the payoff ceiling stayed
   // capped near TP1 while losers paid the full stop. With TP3 as the broker TP the race
   // is winnable: server partials close into an OPEN position at TP1/TP2, and the broker
   // TP remains as the runner's fallback exit if the server link dies mid-trade. The SL
   // is untouched. Version 3.05 requires both the local opt-in and the server's partial strategy;
   // upgrading either component alone keeps the previous TP1 policy.
   double tp = tp1;
   if(UseFinalTargetTP && ExtractJsonString(response, "tpStrategy") == "partial")
      tp = (tp3 > 0) ? tp3 : (tp2 > 0) ? tp2 : tp1;

   Print("[GoldTracker AI] ========== NEW SIGNAL ==========");
   Print("[GoldTracker AI] Direction: ", direction);
   Print("[GoldTracker AI] Entry: $", DoubleToString(entry, 2));
   Print("[GoldTracker AI] SL: $", DoubleToString(sl, 2));
   Print("[GoldTracker AI] TP1: $", DoubleToString(tp1, 2), " | TP2: $", DoubleToString(tp2, 2), " | TP3: $", DoubleToString(tp3, 2));
   Print("[GoldTracker AI] Confidence: ", confidence, "%");
   Print("[GoldTracker AI] Lots: ", DoubleToString(lots, 2));
   Print("[GoldTracker AI] ================================");

   if(!AutoExecute)
   {
      // Show confirmation dialog
      string msg = "GoldTracker AI Signal\n\n"
                 + "Direction: " + direction + "\n"
                 + "Entry: $" + DoubleToString(entry, 2) + "\n"
                 + "SL: $" + DoubleToString(sl, 2) + "\n"
                 + "TP: $" + DoubleToString(tp, 2) + "\n"
                 + "Confidence: " + IntegerToString(confidence) + "%\n"
                 + "Lots: " + DoubleToString(lots, 2) + "\n\n"
                 + "Execute this trade?";

      int reply = MessageBox(msg, "GoldTracker AI", MB_YESNO | MB_ICONQUESTION);
      if(reply != IDYES)
      {
         Print("[GoldTracker AI] Signal declined by user: ", signalId);
         MarkSignalExecuted(signalId);
         return;
      }
   }

   // Execute the trade
   bool success = ExecuteTrade(direction, lots, sl, tp, signalId, confidence);

   if(success)
   {
      MarkSignalExecuted(signalId);
      ReportExecution(signalId, direction, entry, sl, tp, lots);
   }
}

//+------------------------------------------------------------------+
//| Emergency close for a position whose stop could not be confirmed. |
//| An unprotected position is an unbounded loss — flat is strictly    |
//| better than exposed with no stop.                                  |
//+------------------------------------------------------------------+
bool CloseUnprotectedPosition(ulong ticket)
{
   if(!PositionSelectByTicket(ticket)) return false;

   MqlTradeRequest req;
   MqlTradeResult  res;
   ZeroMemory(req);
   ZeroMemory(res);

   string sym  = PositionGetString(POSITION_SYMBOL);
   long   type = PositionGetInteger(POSITION_TYPE);
   int    dig  = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);

   req.action    = TRADE_ACTION_DEAL;
   req.position  = ticket;
   req.symbol    = sym;
   req.volume    = PositionGetDouble(POSITION_VOLUME);
   req.deviation = Slippage;
   req.magic     = MagicNumber;
   req.comment   = "GoldTracker AI emergency close (no SL)";
   req.type      = (type == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
   req.price     = NormalizeDouble((type == POSITION_TYPE_BUY)
                     ? SymbolInfoDouble(sym, SYMBOL_BID)
                     : SymbolInfoDouble(sym, SYMBOL_ASK), dig);

   if(OrderSend(req, res) && res.retcode == TRADE_RETCODE_DONE)
   {
      Print("[GoldTracker AI] Emergency close OK for ticket ", ticket);
      return true;
   }
   Print("[GoldTracker AI] EMERGENCY CLOSE FAILED for ticket ", ticket, " retcode ", res.retcode,
         " — POSITION IS OPEN WITH NO STOP. Intervene manually.");
   return false;
}

//+------------------------------------------------------------------+
//| Execute a trade                                                    |
//+------------------------------------------------------------------+
bool ExecuteTrade(string direction, double lots, double sl, double tp, string signalId, int confidence)
{
   MqlTradeRequest request;
   MqlTradeResult  result;
   ZeroMemory(request);
   ZeroMemory(result);

   request.action   = TRADE_ACTION_DEAL;
   request.symbol   = _Symbol;  // Use chart symbol, not input
   request.volume   = NormalizeDouble(lots, 2);
   request.deviation = Slippage;
   request.magic    = MagicNumber;
   request.comment  = "GoldTracker AI " + IntegerToString(confidence) + "%";

   // Trim direction string and normalize
   string dir = direction;
   StringTrimLeft(dir);
   StringTrimRight(dir);
   StringToUpper(dir);

   if(dir == "BUY")
   {
      request.type  = ORDER_TYPE_BUY;
      request.price = SymbolInfoDouble(TradeSymbol, SYMBOL_ASK);
   }
   else if(dir == "SELL")
   {
      request.type  = ORDER_TYPE_SELL;
      request.price = SymbolInfoDouble(TradeSymbol, SYMBOL_BID);
   }
   else
   {
      Print("[GoldTracker AI] Unknown direction: ", direction);
      return false;
   }

   // Use chart symbol instead of input (fixes symbol name mismatch)
   string sym = _Symbol;
   int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
   double freshAsk = SymbolInfoDouble(sym, SYMBOL_ASK);
   double freshBid = SymbolInfoDouble(sym, SYMBOL_BID);
   Print("[GoldTracker AI] Symbol: ", sym, " Digits: ", digits, " Ask: ", freshAsk, " Bid: ", freshBid);

   if(dir == "BUY")
      request.price = NormalizeDouble(freshAsk, digits);
   else
      request.price = NormalizeDouble(freshBid, digits);

   // Attach SL/TP to the ENTRY order. A position that exists without a stop is an
   // unbounded loss, and the old code deliberately opened one on every trade, relying on
   // a follow-up modify that had no retry and no failure handling. If a broker rejects
   // inline stops, the post-fill modify below still runs as a fallback.
   request.sl = (sl > 0) ? NormalizeDouble(sl, digits) : 0;
   request.tp = (tp > 0) ? NormalizeDouble(tp, digits) : 0;

   // Filling mode — detect what broker supports
   long filling = SymbolInfoInteger(sym, SYMBOL_FILLING_MODE);
   if((filling & SYMBOL_FILLING_IOC) != 0)
      request.type_filling = ORDER_FILLING_IOC;
   else if((filling & SYMBOL_FILLING_FOK) != 0)
      request.type_filling = ORDER_FILLING_FOK;
   else
      request.type_filling = ORDER_FILLING_RETURN;
   Print("[GoldTracker AI] Filling mode: ", request.type_filling, " (supported: ", filling, ")");

   Print("[GoldTracker AI] Sending: ", dir, " ", DoubleToString(lots, 2), " lots @ ", DoubleToString(request.price, digits),
         " Ask:", DoubleToString(freshAsk, digits), " Bid:", DoubleToString(freshBid, digits));

   if(!OrderSend(request, result))
   {
      int sendError=GetLastError();
      Print("[GoldTracker AI] OrderSend FAILED. Error: ", sendError, " Retcode: ", result.retcode);
      ReportTerminalState("order_failed",(int)result.retcode,sendError);
      return false;
   }

   if(result.retcode == TRADE_RETCODE_DONE || result.retcode == TRADE_RETCODE_PLACED)
   {
      // D058 (corrected): keep the AUTHORITATIVE identifiers from the order result. The execution
      // report previously found its ticket by scanning for the "most recent" magic-number position,
      // which attaches the fill to the wrong ticket whenever more than one position is open.
      g_lastOrderTicket = result.order;
      g_lastDealTicket  = result.deal;
      g_lastFillPrice   = result.price;
      Print("[GoldTracker AI] ORDER EXECUTED! Ticket: ", result.order, " Deal: ", result.deal, " Price: ", DoubleToString(result.price, digits));

      // Now modify to add SL/TP
      if(sl > 0 || tp > 0)
      {
         Sleep(500); // Wait for position to register
         MqlTradeRequest modReq;
         MqlTradeResult modRes;
         ZeroMemory(modReq);
         ZeroMemory(modRes);
         modReq.action = TRADE_ACTION_SLTP;
         modReq.position = result.order;
         modReq.symbol = TradeSymbol;
         if(sl > 0) modReq.sl = NormalizeDouble(sl, digits);
         if(tp > 0) modReq.tp = NormalizeDouble(tp, digits);
         bool slOk = false;
         for(int attempt = 0; attempt < 3 && !slOk; attempt++)
         {
            if(attempt > 0) Sleep(1000);
            ZeroMemory(modRes);
            if(OrderSend(modReq, modRes) && modRes.retcode == TRADE_RETCODE_DONE)
               slOk = true;
            else
               Print("[GoldTracker AI] SL/TP modify attempt ", attempt + 1, "/3 failed: ", modRes.retcode);
         }

         // Verify against the BROKER, not against what we asked for. Reporting the
         // intended stop while the broker holds none is exactly how an unprotected
         // position stays invisible to the server.
         if(PositionSelectByTicket(result.order))
         {
            double brokerSl = PositionGetDouble(POSITION_SL);
            slOk = (brokerSl > 0);
            Print("[GoldTracker AI] Broker SL confirmed: ", DoubleToString(brokerSl, digits),
                  " TP: ", DoubleToString(PositionGetDouble(POSITION_TP), digits));
         }

         if(!slOk)
         {
            Print("[GoldTracker AI] CRITICAL: stop could not be confirmed on ticket ", result.order, " — closing position.");
            CloseUnprotectedPosition(result.order);
            return false;
         }
      }

      return true;
   }
   else
   {
      Print("[GoldTracker AI] Order rejected. Retcode: ", result.retcode, " Comment: ", result.comment);
      ReportTerminalState("order_failed",(int)result.retcode,0);
      return false;
   }
}

//+------------------------------------------------------------------+
//| Calculate lot size based on risk percentage                        |
//+------------------------------------------------------------------+
double CalculateLotSize(string direction, double entry, double sl)
{
   return CalculateLotSizeWithRisk(direction, entry, sl, RiskPercent);
}

double CalculateLotSizeWithRisk(string direction, double entry, double sl, double riskPct)
{
   if(sl <= 0 || entry <= 0) return 0.01; // Default minimum

   double riskAmount = AccountInfoDouble(ACCOUNT_EQUITY) * (riskPct / 100.0);
   double slDistance = MathAbs(entry - sl);

   if(slDistance <= 0) return 0.01;

   // For gold: 1 lot = 100 oz, so $1 move = $100 per lot.
   // Use the CHART symbol, matching ExecuteTrade(). These previously read TradeSymbol
   // (the "XAUUSD" input) while the order was placed on _Symbol. If a broker's symbol
   // name differed at all, SymbolInfoDouble returned 0 and this silently fell through to
   // `return 0.01` — sizing every trade at the minimum lot instead of the intended size,
   // with no warning anywhere.
   string sizingSym = _Symbol;
   double tickValue = SymbolInfoDouble(sizingSym, SYMBOL_TRADE_TICK_VALUE);
   double tickSize  = SymbolInfoDouble(sizingSym, SYMBOL_TRADE_TICK_SIZE);

   if(tickValue <= 0 || tickSize <= 0)
   {
      Print("[GoldTracker AI] WARNING: tick data unavailable for ", sizingSym,
            " (tickValue=", tickValue, " tickSize=", tickSize, ") — falling back to minimum lot.");
      return 0.01;
   }

   double pipValue = tickValue / tickSize; // value per $1 move per 1 lot
   double lots = riskAmount / (slDistance * pipValue);

   // D038 hard $ loss cap REVERTED 2026-07-28 (see product-memory/FAILED_IDEAS.md F013):
   // it shrank winners and silently skipped trades when the SL was wide. Position size is
   // bounded by MaxLots + server Kelly risk% only.

   // Normalize to symbol lot step
   double lotStep = SymbolInfoDouble(TradeSymbol, SYMBOL_VOLUME_STEP);
   double minLot  = SymbolInfoDouble(TradeSymbol, SYMBOL_VOLUME_MIN);
   double maxLot  = SymbolInfoDouble(TradeSymbol, SYMBOL_VOLUME_MAX);

   if(lotStep > 0)
      lots = MathFloor(lots / lotStep) * lotStep;

   if(lots < minLot) lots = minLot;
   if(lots > maxLot) lots = maxLot;

   return NormalizeDouble(lots, 2);
}

//+------------------------------------------------------------------+
//| Count currently open AI trades (by magic number)                   |
//+------------------------------------------------------------------+
int CountAITrades()
{
   int count = 0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket > 0)
      {
         // Match on the CHART symbol, consistent with ExecuteTrade(). Comparing against
         // the TradeSymbol input meant that on any symbol-name mismatch this counted 0
         // regardless of what was actually open, silently disabling the MaxOpenTrades cap.
         if(PositionGetInteger(POSITION_MAGIC) == MagicNumber &&
            PositionGetString(POSITION_SYMBOL) == _Symbol)
         {
            count++;
         }
      }
   }
   return count;
}

//+------------------------------------------------------------------+
//| Check if a signal was already executed                             |
//+------------------------------------------------------------------+
bool IsSignalExecuted(string signalId)
{
   for(int i = 0; i < executedCount; i++)
   {
      if(executedSignalIds[i] == signalId)
         return true;
   }
   return false;
}

//+------------------------------------------------------------------+
//| Mark a signal as executed                                          |
//+------------------------------------------------------------------+
void MarkSignalExecuted(string signalId)
{
   executedCount++;
   ArrayResize(executedSignalIds, executedCount);
   executedSignalIds[executedCount - 1] = signalId;

   // Keep array manageable — only last 100
   if(executedCount > 100)
   {
      int keep = 50;
      for(int i = 0; i < keep; i++)
         executedSignalIds[i] = executedSignalIds[executedCount - keep + i];
      executedCount = keep;
      ArrayResize(executedSignalIds, executedCount);
   }
}

//+------------------------------------------------------------------+
//| Report execution back to server                                    |
//+------------------------------------------------------------------+
void ReportExecution(string signalId, string direction, double entry, double sl, double tp, double lots)
{
   string url = ExecutedURL + "?ea=" + EA_VERSION;

   // D058 (corrected): use the ticket the BROKER returned for THIS order. Scanning the position
   // list for the most recent magic-number position mis-attributes the fill whenever more than one
   // position is open — and an execution row bound to the wrong ticket corrupts every downstream
   // join, including the exit audit trail this change exists to build.
   ulong ticket = g_lastOrderTicket;
   if(ticket == 0)
   {
      // Fall back to the old scan only if the result was somehow unavailable, and say so, so the
      // ambiguity is visible in the log instead of silently assumed correct.
      Print("[GoldTracker AI] WARNING: no order ticket from result — falling back to position scan");
      for(int i = PositionsTotal() - 1; i >= 0; i--)
      {
         ulong t = PositionGetTicket(i);
         if(t > 0 && PositionGetInteger(POSITION_MAGIC) == MagicNumber) { ticket = t; break; }
      }
   }

   // D058: the BROKER's actual entry fill and confirmed bracket, read from the open position.
   //
   // `entry` above is the SIGNAL's intended entry, not the fill. That single omission is why P&L
   // implied by (entry, close_price) disagreed with net_pnl for 91% of trades, why true execution R
   // could only ever be back-derived, and why a whole afternoon went into establishing that
   // close_price was not fabricated. The EA has always known the fill — it prints result.price at
   // execution — and simply never sent it.
   double brokerEntry = 0, brokerSl = 0, brokerTp = 0;
   long   brokerTime  = 0;
   if(ticket > 0 && PositionSelectByTicket(ticket))
   {
      brokerEntry = PositionGetDouble(POSITION_PRICE_OPEN);
      brokerSl    = PositionGetDouble(POSITION_SL);   // as ACCEPTED, which may be normalised
      brokerTp    = PositionGetDouble(POSITION_TP);
      brokerTime  = (long)PositionGetInteger(POSITION_TIME) * 1000;
   }

   string json = "{"
      + "\"signalId\":\"" + signalId + "\","
      + "\"ticket\":" + IntegerToString((long)ticket) + ","
      + "\"direction\":\"" + direction + "\","
      + "\"entry\":" + DoubleToString(entry, 2) + ","
      + "\"sl\":" + DoubleToString(sl, 2) + ","
      + "\"tp\":" + DoubleToString(tp, 2) + ","
      + "\"lots\":" + DoubleToString(lots, 2) + ","
      + "\"brokerEntryPrice\":" + DoubleToString(brokerEntry, 2) + ","
      + "\"brokerInitialSl\":" + DoubleToString(brokerSl, 2) + ","
      + "\"brokerInitialTp\":" + DoubleToString(brokerTp, 2) + ","
      + "\"brokerEntryTs\":" + IntegerToString(brokerTime)
      + "}";

   char postData[];
   int bodyBytes = StringToCharArray(json, postData, 0, WHOLE_ARRAY, CP_UTF8);
   // Remove null terminator that StringToCharArray adds
   ArrayResize(postData, MathMax(0, bodyBytes - 1));

   string body = "";
   int res = HttpRequest("POST", url, postData, body, "ExecReport", 3);
   if(res == 200)
      Print("[GoldTracker AI] Execution reported to server successfully");
   else
      Print("[GoldTracker AI] Failed to report execution after retries. HTTP: ", res);
}

//+------------------------------------------------------------------+
//| Detect trade closes and report to server (CRITICAL for algo learn) |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction& trans,
                        const MqlTradeRequest& request,
                        const MqlTradeResult& result)
{
   // Only care about deal additions (executions)
   if(trans.type != TRADE_TRANSACTION_DEAL_ADD) return;

   // Get deal info
   ulong dealTicket = trans.deal;
   if(dealTicket == 0) return;

   // Select the deal
   if(!HistoryDealSelect(dealTicket)) return;

   // Only process our AI trades (by magic number)
   long dealMagic = HistoryDealGetInteger(dealTicket, DEAL_MAGIC);
   if(dealMagic != MagicNumber) return;

   // Only process exit deals (DEAL_ENTRY_OUT or DEAL_ENTRY_INOUT)
   long dealEntry = HistoryDealGetInteger(dealTicket, DEAL_ENTRY);
   if(dealEntry != DEAL_ENTRY_OUT && dealEntry != DEAL_ENTRY_INOUT) return;

   // This is a close — get the details
   double closePrice  = HistoryDealGetDouble(dealTicket, DEAL_PRICE);
   double dealPnl     = HistoryDealGetDouble(dealTicket, DEAL_PROFIT);
   double commission   = HistoryDealGetDouble(dealTicket, DEAL_COMMISSION);
   double swap         = HistoryDealGetDouble(dealTicket, DEAL_SWAP);
   long   positionId   = HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);

   Print("[GoldTracker AI] ========== TRADE CLOSED ==========");
   Print("[GoldTracker AI] Ticket: ", positionId, " Deal: ", dealTicket);
   Print("[GoldTracker AI] Close Price: $", DoubleToString(closePrice, 2));
   Print("[GoldTracker AI] P&L: $", DoubleToString(dealPnl, 2));
   Print("[GoldTracker AI] Commission: $", DoubleToString(commission, 2));
   Print("[GoldTracker AI] Swap: $", DoubleToString(swap, 2));
   Print("[GoldTracker AI] Net P&L: $", DoubleToString(dealPnl + commission + swap, 2));
   Print("[GoldTracker AI] ================================");

   // Report to server so the algo can learn
   ReportClose(positionId, closePrice, dealPnl, commission, swap);
}

//+------------------------------------------------------------------+
//| D058: report what the BROKER did with a management command.        |
//|                                                                     |
//| The missing half of the execution audit trail. Until now a failed   |
//| ModifyPositionSL only printed to this log, so the server's belief   |
//| about the current stop could diverge from the broker's with nothing |
//| detecting it — and 39% of exits happen at a moved stop, none of     |
//| which can be replayed without this.                                 |
//|                                                                     |
//| Sends the retcode, the levels BEFORE and AFTER (the broker may      |
//| normalise or reject what we asked for), the broker's own timestamp, |
//| and the live bid/ask. Failures are reported as first-class          |
//| outcomes, never swallowed.                                          |
//+------------------------------------------------------------------+
void ReportCommandAck(string commandId, string status, int retcode, string comment,
                      double slBefore, double slAfter, double tpBefore, double tpAfter)
{
   if(StringLen(commandId) == 0) return;   // older server build: nothing to tie the answer to

   string sym = _Symbol;
   double bid = SymbolInfoDouble(sym, SYMBOL_BID);
   double ask = SymbolInfoDouble(sym, SYMBOL_ASK);

   string json = "{"
      + "\"commandId\":\"" + commandId + "\","
      + "\"status\":\"" + status + "\","
      + "\"retcode\":" + IntegerToString(retcode) + ","
      + "\"comment\":\"" + EscapeCommandJson(comment) + "\","
      + "\"brokerTs\":" + IntegerToString((long)TimeCurrent() * 1000) + ","
      + "\"slBefore\":" + DoubleToString(slBefore, 2) + ","
      + "\"slAfter\":" + DoubleToString(slAfter, 2) + ","
      + "\"tpBefore\":" + DoubleToString(tpBefore, 2) + ","
      + "\"tpAfter\":" + DoubleToString(tpAfter, 2) + ","
      + "\"bid\":" + DoubleToString(bid, 2) + ","
      + "\"ask\":" + DoubleToString(ask, 2)
      + "}";

   string queued = CommandFilePrefix() + commandId + ".ack";
   if(!WriteCommandFile(queued, json))
      Print("[Trade Mgmt] CRITICAL: cannot persist acknowledgement for ", commandId);
   // Queue first: a crash after writing the receipt must still leave a retryable acknowledgement.
   string receipt = CommandFilePrefix() + commandId + ".receipt";
   if(FileIsExist(receipt, FILE_COMMON)) WriteCommandFile(receipt, json);
   if(PostCommandAck(json)) FileDelete(queued, FILE_COMMON);
}

// Terminal-shared journal, namespaced by broker server, account and EA magic number.
string EscapeCommandJson(string value)
{
   StringReplace(value, "\\", "\\\\"); StringReplace(value, "\"", "\\\"");
   StringReplace(value, "\r", "\\r"); StringReplace(value, "\n", "\\n");
   StringReplace(value, "\t", "\\t");
   return value;
}

string CommandFilePrefix()
{
   string server = AccountInfoString(ACCOUNT_SERVER);
   StringReplace(server, "\\", "_"); StringReplace(server, "/", "_"); StringReplace(server, ":", "_");
   return "GT_" + server + "_" + IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN))
          + "_" + IntegerToString(MagicNumber) + "_";
}

bool WriteCommandFile(string filename, string contents, bool replace = true)
{
   // Publish a flushed UTF-8 file by rename. Never truncate the previous receipt/outbox entry.
   string staging = filename + "." + IntegerToString(ChartID()) + "."
                    + IntegerToString((long)GetTickCount64()) + "."
                    + IntegerToString(g_commandFileSerial++) + ".tmp";
   int handle = FileOpen(staging, FILE_WRITE|FILE_BIN|FILE_COMMON);
   if(handle == INVALID_HANDLE) return false;
   char bytes[];
   int size = StringToCharArray(contents, bytes, 0, WHOLE_ARRAY, CP_UTF8);
   ArrayResize(bytes, MathMax(0, size - 1));
   uint written = FileWriteArray(handle, bytes);
   ResetLastError(); FileFlush(handle);
   bool flushed = GetLastError() == 0;
   FileClose(handle);
   bool complete = written > 0 && written == (uint)ArraySize(bytes) && flushed;
   bool published = complete && FileMove(staging, FILE_COMMON, filename,
                                        FILE_COMMON | (replace ? FILE_REWRITE : 0));
   if(!published) FileDelete(staging, FILE_COMMON);
   return published;
}

bool PostCommandAck(string json)
{
   char   postData[];
   int bodyBytes = StringToCharArray(json, postData, 0, WHOLE_ARRAY, CP_UTF8);
   ArrayResize(postData, MathMax(0, bodyBytes - 1));
   string body = "";
   int code = HttpRequest("POST", AckURL + "?ea=" + EA_VERSION,
                          postData, body, "CommandAck", 1, 1500);
   StringReplace(body, " ", "");
   return code == 200 && StringFind(body, "\"recorded\":true") >= 0;
}

void RetryCommandAcks()
{
   string filename;
   long search = FileFindFirst(CommandFilePrefix() + "*.ack", filename, FILE_COMMON);
   if(search == INVALID_HANDLE) return;
   string queued[];
   int total = 0;
   do {
      ArrayResize(queued, total + 1, 64);
      queued[total++] = filename;
   } while(FileFindNext(search, filename));
   FileFindClose(search);
   // Rotate past failed receipts instead of repeatedly retrying only the first batch.
   int start = g_ackRetryOffset % total, attempted = 0;
   ulong started = GetTickCount64();
   while(attempted < total && attempted < 4 && GetTickCount64() - started < 3000)
   {
      filename = queued[(start + attempted) % total];
      int handle = FileOpen(filename, FILE_READ|FILE_TXT|FILE_ANSI|FILE_COMMON, 0, CP_UTF8);
      if(handle != INVALID_HANDLE)
      {
         string json = FileReadString(handle); FileClose(handle);
         if(PostCommandAck(json)) FileDelete(filename, FILE_COMMON);
      }
      attempted++;
   }
   g_ackRetryOffset = (start + attempted) % total;
}

bool ReservePartialCommand(string commandId)
{
   if(StringLen(commandId) == 0) return false;
   string filename = CommandFilePrefix() + commandId + ".receipt";
   // No-replace publication grants the first reservation. Even an empty/corrupt existing
   // receipt is unresolved evidence, never permission to send another deal.
   if(WriteCommandFile(filename, "reserved", false)) return true;
   int handle = FileOpen(filename, FILE_READ|FILE_TXT|FILE_ANSI|FILE_COMMON, 0, CP_UTF8);
   if(handle == INVALID_HANDLE)
   {
      Print("[Trade Mgmt] CRITICAL: cannot reserve partial command ", commandId);
      return false;
   }
   string saved = FileReadString(handle); FileClose(handle);
   if(StringFind(saved, "\"commandId\"") >= 0) PostCommandAck(saved);
   else ReportCommandAck(commandId, "uncertain", 0, "reserved command requires broker reconciliation", 0, 0, 0, 0);
   return false;
}

//+------------------------------------------------------------------+
//| Report trade close to server for algo learning                     |
//+------------------------------------------------------------------+
void ReportClose(long ticket, double closePrice, double pnl, double commission, double swap)
{
   string url = CloseURL + "?ea=" + EA_VERSION;

   string json = "{"
      + "\"ticket\":" + IntegerToString(ticket) + ","
      + "\"closePrice\":" + DoubleToString(closePrice, 2) + ","
      + "\"pnl\":" + DoubleToString(pnl, 2) + ","
      + "\"commission\":" + DoubleToString(commission, 2) + ","
      + "\"swap\":" + DoubleToString(swap, 2)
      + "}";

   char postData[];
   int bodyBytes = StringToCharArray(json, postData, 0, WHOLE_ARRAY, CP_UTF8);
   ArrayResize(postData, MathMax(0, bodyBytes - 1));

   // THE MOST IMPORTANT REQUEST THE EA MAKES. A lost close report leaves the server
   // believing the trade is still open. Its old 24h "stale cleanup" then invented an
   // outcome at the then-current market price and fed that fiction to the learning loop —
   // ~21 fabricated closes, including a "-$921 loss" on a trade that actually hit its
   // take-profit for +$350.80. Retry hard, and shout if it still fails.
   string body = "";
   int res = HttpRequest("POST", url, postData, body, "CloseReport", 5);
   if(res == 200)
      Print("[GoldTracker AI] Trade close reported — algo will learn from this trade");
   else
      Print("[GoldTracker AI] CRITICAL: close report FAILED after retries (HTTP ", res,
            "). Server will show this trade as still open — reconcile against MT5 History.");
}

//+------------------------------------------------------------------+
//| Manage open trades — poll server for SL moves, partial closes      |
//+------------------------------------------------------------------+
void ManageOpenTrades()
{
   // Only manage if we have open AI trades
   int aiTrades = CountAITrades();
   if(aiTrades == 0) return;

   string url = ManageURL + "?ea=" + EA_VERSION
                + "&ladder=" + (UseFinalTargetTP ? "1" : "0");

   char   postData[];
   string response = "";
   int res = HttpRequest("GET", url, postData, response, "ManagePoll", 2);
   if(res != 200) return;

   // Parse commands array — look for each command block
   int searchPos = 0;
   while(true)
   {
      // Find next command block
      int cmdStart = StringFind(response, "\"ticket\":", searchPos);
      if(cmdStart < 0) break;

      // Extract command fields
      // Find the enclosing {} block
      int blockStart = StringFind(response, "{", cmdStart - 20);
      int blockEnd = StringFind(response, "}", cmdStart);
      if(blockStart < 0 || blockEnd < 0) break;

      string block = StringSubstr(response, blockStart, blockEnd - blockStart + 1);

      string ticket = ExtractJsonString(block, "ticket");
      string action = ExtractJsonString(block, "action");
      double newSl = ExtractJsonDouble(block, "newSl");
      double lots = ExtractJsonDouble(block, "lots");
      string reason = ExtractJsonString(block, "reason");
      // D058: the server stamps every command with an id so the broker's answer can be tied back
      // to the request. Without it, the server knows only what it ASKED for.
      string commandId = ExtractJsonString(block, "commandId");

      if(StringLen(ticket) == 0 || StringLen(action) == 0) { searchPos = blockEnd + 1; continue; }

      long ticketNum = StringToInteger(ticket);

      if(action == "MOVE_SL")
      {
         // Capture broker state BEFORE the attempt. This is the half the server can never see, and
         // its absence is why 39% of exits — the moved stops — cannot be replayed today.
         double slBefore = 0, tpBefore = 0;
         if(PositionSelectByTicket((ulong)ticketNum))
         {
            slBefore = PositionGetDouble(POSITION_SL);
            tpBefore = PositionGetDouble(POSITION_TP);
         }
         else
         {
            // The position is already gone — a resting SL/TP resolved before this command arrived.
            // That is not a failure, it is the single most important fact about the exit, and until
            // now it was invisible: the server retried or assumed success.
            ReportCommandAck(commandId, "noop_closed", 0, "position not found", 0, 0, 0, 0);
            searchPos = blockEnd + 1;
            continue;
         }

         g_lastRetcode = 0;
         bool ok = ModifyPositionSL(ticketNum, newSl);
         double slAfter = slBefore, tpAfter = tpBefore;
         if(PositionSelectByTicket((ulong)ticketNum))
         {
            slAfter = PositionGetDouble(POSITION_SL);   // the NORMALISED level the broker accepted,
            tpAfter = PositionGetDouble(POSITION_TP);   // which may differ from what we requested
         }
         ReportCommandAck(commandId, ok ? "applied" : "rejected", g_lastRetcode,
                          ok ? reason : "modify failed", slBefore, slAfter, tpBefore, tpAfter);
         if(ok) Print("[Trade Mgmt] SL moved for ticket ", ticket, ": ", reason);
         else   Print("[Trade Mgmt] Failed to move SL for ticket ", ticket, " retcode ", g_lastRetcode);
      }
      else if(action == "PARTIAL_CLOSE")
      {
         if(!ReservePartialCommand(commandId)) { searchPos = blockEnd + 1; continue; }
         // D058 (corrected): acknowledge this command too. The first version only acknowledged
         // MOVE_SL, so every PARTIAL_CLOSE sat at ack_status='pending' forever — indistinguishable
         // in the data from a command that was never delivered. A gap that looks like a lost
         // command is worse than a recorded failure, because it invites the wrong diagnosis.
         double slBefore = 0, tpBefore = 0;
         bool   present  = PositionSelectByTicket((ulong)ticketNum);
         if(present)
         {
            slBefore = PositionGetDouble(POSITION_SL);
            tpBefore = PositionGetDouble(POSITION_TP);
         }
         else
         {
            // Already flat — the broker resolved it before this command arrived.
            ReportCommandAck(commandId, "noop_closed", 0, "position not found", 0, 0, 0, 0);
            searchPos = blockEnd + 1;
            continue;
         }

         g_lastRetcode = 0;
         string partialLevel = ExtractJsonString(block, "level");
         bool ladderPartial = partialLevel == "tp1" || partialLevel == "tp2";
         double expectedTp = ExtractJsonDouble(block, "expectedTp");
         double tickSize = SymbolInfoDouble(PositionGetString(POSITION_SYMBOL), SYMBOL_TRADE_TICK_SIZE);
         if(tickSize <= 0) tickSize = 0.01;
         if(ladderPartial && (!UseFinalTargetTP || expectedTp <= 0 || MathAbs(tpBefore - expectedTp) > tickSize / 2))
         {
            ReportCommandAck(commandId, "uncertain", 0, "broker target differs from ladder command", slBefore, slBefore, tpBefore, tpBefore);
            searchPos = blockEnd + 1;
            continue;
         }
         if(PartialClosePosition(ticketNum, lots, ladderPartial))
         {
            Print("[Trade Mgmt] Partial close ", DoubleToString(lots, 2), " lots for ticket ", ticket, ": ", reason);
            double closePrice = 0;
            if(PositionSelectByTicket((ulong)ticketNum))
               closePrice = PositionGetDouble(POSITION_PRICE_CURRENT);
            string level = ExtractJsonString(block, "level");
            ReportCommandAck(commandId, "applied", g_lastRetcode, reason, slBefore, slBefore, tpBefore, tpBefore);
            ReportPartialClose(ticketNum, lots, closePrice, level);
         }
         else
         {
            Print("[Trade Mgmt] Failed to partial close ticket ", ticket);
            // Retry only definite broker refusals. Timeouts, accepted-but-not-filled requests,
            // partial fills and unknown codes require reconciliation instead of another deal.
            bool rejected = g_lastRetcode == TRADE_RETCODE_REJECT
                            || g_lastRetcode == TRADE_RETCODE_REQUOTE
                            || g_lastRetcode == TRADE_RETCODE_INVALID
                            || g_lastRetcode == TRADE_RETCODE_INVALID_VOLUME
                            || g_lastRetcode == TRADE_RETCODE_INVALID_PRICE
                            || g_lastRetcode == TRADE_RETCODE_INVALID_FILL
                            || g_lastRetcode == TRADE_RETCODE_TRADE_DISABLED
                            || g_lastRetcode == TRADE_RETCODE_MARKET_CLOSED
                            || g_lastRetcode == TRADE_RETCODE_NO_MONEY
                            || g_lastRetcode == TRADE_RETCODE_PRICE_CHANGED
                            || g_lastRetcode == TRADE_RETCODE_PRICE_OFF;
            ReportCommandAck(commandId, rejected ? "rejected" : "uncertain", g_lastRetcode,
                             "partial close not confirmed", slBefore, slBefore, tpBefore, tpBefore);
         }
      }

      searchPos = blockEnd + 1;
   }
}

//+------------------------------------------------------------------+
//| Modify position SL                                                 |
//+------------------------------------------------------------------+
bool ModifyPositionSL(long ticket, double newSl)
{
   if(!PositionSelectByTicket((ulong)ticket)) return false;

   string sym = PositionGetString(POSITION_SYMBOL);
   int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
   double currentTp = PositionGetDouble(POSITION_TP);
   double currentSl = PositionGetDouble(POSITION_SL);

   // Only move SL in favorable direction (towards profit)
   long posType = PositionGetInteger(POSITION_TYPE);
   if(posType == POSITION_TYPE_BUY && newSl < currentSl && currentSl > 0) return false; // Don't widen SL for buys
   if(posType == POSITION_TYPE_SELL && newSl > currentSl && currentSl > 0) return false; // Don't widen SL for sells

   MqlTradeRequest request;
   MqlTradeResult  result;
   ZeroMemory(request);
   ZeroMemory(result);

   request.action = TRADE_ACTION_SLTP;
   request.position = (ulong)ticket;
   request.symbol = sym;
   request.sl = NormalizeDouble(newSl, digits);
   request.tp = NormalizeDouble(currentTp, digits);

   bool sent = OrderSend(request, result);
   g_lastRetcode = (int)result.retcode;   // record on BOTH paths — a success code is evidence too
   if(!sent)
   {
      Print("[Trade Mgmt] SL modify failed: ", GetLastError(), " Retcode: ", result.retcode);
      return false;
   }

   return (result.retcode == TRADE_RETCODE_DONE);
}

//+------------------------------------------------------------------+
//| Partial close a position                                           |
//+------------------------------------------------------------------+
bool PartialClosePosition(long ticket, double closeLots, bool preserveRunner)
{
   if(!PositionSelectByTicket((ulong)ticket)) return false;

   string sym = PositionGetString(POSITION_SYMBOL);
   int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
   long posType = PositionGetInteger(POSITION_TYPE);
   double currentLots = PositionGetDouble(POSITION_VOLUME);

   // Don't close more than we have
   if(closeLots > currentLots) closeLots = currentLots;
   // Normalize to lot step
   double lotStep = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP);
   if(lotStep > 0) closeLots = MathFloor(closeLots / lotStep) * lotStep;
   double minLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN);
   if(closeLots < minLot) closeLots = minLot;
   if(preserveRunner && currentLots - closeLots < minLot - 0.0000001)
   {
      g_lastRetcode = TRADE_RETCODE_INVALID_VOLUME;
      return false;
   }

   MqlTradeRequest request;
   MqlTradeResult  result;
   ZeroMemory(request);
   ZeroMemory(result);

   request.action = TRADE_ACTION_DEAL;
   request.position = (ulong)ticket;
   request.symbol = sym;
   request.volume = NormalizeDouble(closeLots, 2);
   request.deviation = Slippage;
   request.magic = MagicNumber;

   // Opposite direction to close
   if(posType == POSITION_TYPE_BUY)
   {
      request.type = ORDER_TYPE_SELL;
      request.price = SymbolInfoDouble(sym, SYMBOL_BID);
   }
   else
   {
      request.type = ORDER_TYPE_BUY;
      request.price = SymbolInfoDouble(sym, SYMBOL_ASK);
   }

   // Filling mode
   long filling = SymbolInfoInteger(sym, SYMBOL_FILLING_MODE);
   if((filling & SYMBOL_FILLING_IOC) != 0) request.type_filling = ORDER_FILLING_IOC;
   else if((filling & SYMBOL_FILLING_FOK) != 0) request.type_filling = ORDER_FILLING_FOK;
   else request.type_filling = ORDER_FILLING_RETURN;

   bool sent = OrderSend(request, result);
   g_lastRetcode = (int)result.retcode;
   if(!sent)
   {
      Print("[Trade Mgmt] Partial close failed: ", GetLastError(), " Retcode: ", result.retcode);
      return false;
   }

   return (result.retcode == TRADE_RETCODE_DONE);
}

//+------------------------------------------------------------------+
//| Report partial close to server                                     |
//+------------------------------------------------------------------+
void ReportPartialClose(long ticket, double closedLots, double closePrice, string level)
{
   string url = PartialCloseURL + "?ea=" + EA_VERSION;
   // Level identifies which ladder rung banked the partial ('tp1'/'tp2'); manual
   // dashboard closes carry no level and are reported as 'manual'.
   if(StringLen(level) == 0) level = "manual";

   string json = "{"
      + "\"ticket\":" + IntegerToString(ticket) + ","
      + "\"closedLots\":" + DoubleToString(closedLots, 2) + ","
      + "\"closePrice\":" + DoubleToString(closePrice, 2) + ","
      + "\"tpLevel\":\"" + level + "\""
      + "}";

   char postData[];
   int bodyBytes = StringToCharArray(json, postData, 0, WHOLE_ARRAY, CP_UTF8);
   ArrayResize(postData, MathMax(0, bodyBytes - 1));

   string body = "";
   int res = HttpRequest("POST", url, postData, body, "PartialClose", 1, 1500);
   if(res == 200)
      Print("[Trade Mgmt] Partial close reported to server");
   else
      Print("[Trade Mgmt] Failed to report partial close after retries. HTTP: ", res);
}

//+------------------------------------------------------------------+
//| Extract a string value from JSON by key                            |
//+------------------------------------------------------------------+
string ExtractJsonString(string json, string key)
{
   string search = "\"" + key + "\":\"";
   int pos = StringFind(json, search);
   if(pos < 0)
   {
      search = "\"" + key + "\": \"";
      pos = StringFind(json, search);
   }
   if(pos < 0) return "";

   int start = pos + StringLen(search);
   int end = StringFind(json, "\"", start);
   if(end < 0) return "";

   return StringSubstr(json, start, end - start);
}

//+------------------------------------------------------------------+
//| Extract a numeric value from JSON by key                           |
//+------------------------------------------------------------------+
double ExtractJsonDouble(string json, string key)
{
   // Try "key":value format
   string search = "\"" + key + "\":";
   int pos = StringFind(json, search);
   if(pos < 0)
   {
      search = "\"" + key + "\": ";
      pos = StringFind(json, search);
   }
   if(pos < 0) return 0;

   int start = pos + StringLen(search);
   // Skip any whitespace
   while(start < StringLen(json) && (StringGetCharacter(json, start) == ' ' || StringGetCharacter(json, start) == '"'))
      start++;

   string numStr = "";
   for(int i = start; i < StringLen(json); i++)
   {
      ushort c = StringGetCharacter(json, i);
      if((c >= '0' && c <= '9') || c == '.' || c == '-')
         numStr += ShortToString(c);
      else
         break;
   }

   if(StringLen(numStr) == 0) return 0;
   return StringToDouble(numStr);
}
//+------------------------------------------------------------------+
