//+------------------------------------------------------------------+
//|                                               AITeamSix_EA.mq5   |
//|                                     AI TEAM SiX · Khmer Gold     |
//|                                                                  |
//|  v1.03 — real auto-trade EA for MetaTrader 5                     |
//|                                                                  |
//|  WHAT'S NEW IN v1.02                                             |
//|  • Default feed is now the LIVE API: /api/signals on             |
//|    khmergoldscanner.pages.dev (server-computed live signals),    |
//|    not a static snapshot file.                                   |
//|  • On-chart DASHBOARD (Comment): mode, feed status, last poll,   |
//|    open positions, balance/equity, spread, news-blackout state   |
//|    and the last action taken — visible at a glance.              |
//|  • NEWS BLACKOUT: polls /api/news; new trades are blocked from   |
//|    InpNewsBlockMin minutes before a High-impact event until      |
//|    15 minutes after it. Fail-open if the news feed is down       |
//|    (the block is a safety filter, not a data source).            |
//|  • PARTIAL CLOSE: feed trades take the order TP at TP2; when     |
//|    price reaches TP1 the EA closes 50%, moves SL to break-even   |
//|    and lets the rest run to TP2.                                 |
//|                                                                  |
//|  WHAT'S NEW IN v1.03 — MT5 BRIDGE PROTOCOL                       |
//|  • BRIDGE HEARTBEAT: every InpBridgeHBSec (default 3s) the EA    |
//|    POSTs balance / equity / open positions to                    |
//|    POST /api/mt5/heartbeat (bridge token auth) and receives      |
//|    back: risk settings, new published signals, server-ordered    |
//|    closes (close_all) and the daily-loss breaker state.          |
//|  • FILL REPORTS: every deal (placed / closed) is POSTed to       |
//|    /api/mt5/fill with a unique event id "<login>-<deal>" —       |
//|    the server is replay-guarded (a repeated id never counts      |
//|    twice) and fills are immutable.                               |
//|  • DAILY-LOSS BREAKER: when the server says the breaker          |
//|    tripped (today's closed fills ≤ −InpDailyLossUSD), the EA     |
//|    refuses new entries until the next day. FREE — no paywall.    |
//|  • Risk settings (risk %, max open trades, symbol suffix,        |
//|    break-even trigger R) are managed from the app's MT5          |
//|    dashboard; the token there must match InpBridgeToken here.    |
//|  • Allow WebRequest for the bridge base URL too (same domain).   |
//|                                                                  |
//|  COMPILE + TEST GUIDE                                            |
//|  1) Open this file in MetaEditor → Compile (F7) → must show      |
//|     "0 errors, 0 warnings". You get AITeamSix_EA.ex5.            |
//|  2) Copy the .ex5 into MQL5/Experts, restart MT5, drag the EA    |
//|     onto an XAUUSD chart, enable Algo Trading.                   |
//|  3) Tools → Options → Expert Advisors → allow WebRequest for     |
//|     https://khmergoldscanner.pages.dev (feed + news).            |
//|  4) Strategy Tester (Ctrl+R): model "Every tick based on real   |
//|     ticks", XAUUSD M15, at least 3 months — watch it open,       |
//|     partially close at TP1 and exit at TP2/SL on history.        |
//|  5) Then run on a DEMO account at least 2 weeks before live.     |
//|                                                                  |
//|  WHAT'S NEW IN v1.01                                             |
//|  • FEED MODE (default): polls the AI TEAM SiX signals JSON feed  |
//|    (/api/signals or the exported signals.json) and executes      |
//|    delivered BUY/SELL signals automatically — entry zone check, |
//|    SL + TP1 from the plan, TP ordering enforced (SELL desc,      |
//|    BUY asc). Duplicate signals are never executed twice.         |
//|  • Heartbeat log line every InpHeartbeatSec so you can see the   |
//|    EA is alive; every action is written to a CSV trade log.      |
//|  • Retry on requote / off-quotes (up to 3 attempts).             |
//|  • Risk modes: % of balance OR fixed $ per trade.                |
//|  • Trading-hours filter + max-spread filter + magic number.      |
//|  • ICT on-chart mode kept as fallback, WITH the retest fix:      |
//|    entry is only allowed on a bar AFTER the displacement/FVG     |
//|    candle (the v1.00 pattern could enter on the signal candle    |
//|    itself — a lookahead the app's backtest also fixed).          |
//|  • TP1 reached -> stop moves to break-even (as v1.00).           |
//|                                                                  |
//|  SETUP: Tools → Options → Expert Advisors → allow WebRequest     |
//|  for the feed URL host, or the feed poll cannot run.             |
//|                                                                  |
//|  HONEST NOTE: this EA runs inside YOUR MT5 on YOUR computer/     |
//|  VPS. The website itself cannot trade your account — no website  |
//|  can. Always test on a DEMO account first (2+ weeks). Trading    |
//|  involves substantial risk of loss. Educational tool only, not   |
//|  financial advice.                                               |
//+------------------------------------------------------------------+
#property copyright   "AI TEAM SiX"
#property version     "1.03"
#property strict
#property description "AI TEAM SiX auto-trade EA: signals-feed execution + ICT fallback (XAUUSD)."

#include <Trade\Trade.mqh>

enum EA_MODE   { MODE_FEED = 0, MODE_ICT = 1, MODE_BOTH = 2 };
enum RISK_MODE { RISK_PERCENT = 0, RISK_DOLLARS = 1 };

input EA_MODE   InpMode          = MODE_FEED;   // Mode: Feed / ICT / Both
input string    InpFeedURL       = "https://khmergoldscanner.pages.dev/api/signals"; // Signals feed URL (live API JSON)
input string    InpNewsURL       = "https://khmergoldscanner.pages.dev/api/news";   // News calendar URL (JSON)
input int       InpNewsBlockMin  = 30;          // Block new trades this many min before High-impact news
input bool      InpPartialTP1    = true;        // Close 50% at TP1, SL to break-even, run to TP2
input int       InpPollSeconds   = 60;          // Feed poll interval (sec)
input int       InpMaxSignalAgeMin = 240;       // Ignore feed signals older than (min)
input double    InpEntryTolUSD   = 3.0;         // Execute only if price within $ of entry zone
input RISK_MODE InpRiskMode      = RISK_PERCENT; // Risk mode
input double    InpRiskPercent   = 1.0;         // Risk per trade (% of balance)
input double    InpRiskDollars   = 25.0;        // Risk per trade ($, dollar mode)
input long      InpMagic         = 60606;       // Magic number
input int       InpMaxSpreadPts  = 60;          // Max spread (points) to open
input bool      InpUseHours      = false;       // Use trading-hours filter
input int       InpHourStart     = 7;           // Hours filter: start (server hour, UTC-ish)
input int       InpHourEnd       = 21;          // Hours filter: end (server hour)
input int       InpHeartbeatSec  = 300;         // Heartbeat log interval (sec)
input ENUM_TIMEFRAMES InpTF      = PERIOD_M15;  // ICT working timeframe
input int       InpATRPeriod     = 14;          // ICT ATR period
input double    InpSL_USD        = 10.0;        // ICT stop loss = fixed $ from entry (app rule: $10)
input bool      InpOneAtATime    = true;        // One open trade at a time
//--- v1.03 MT5 Bridge (heartbeat + fill reports) ---
input bool      InpBridgeEnable  = false;       // Bridge: enable heartbeat + fill reports
input string    InpBridgeURL     = "https://khmergoldscanner.pages.dev"; // Bridge base URL
input string    InpBridgeToken   = "";          // Bridge token (must match the app dashboard token)
input int       InpBridgeHBSec   = 3;           // Bridge heartbeat interval (sec)
input int       InpMaxOpenTrades = 3;           // Bridge: max open trades
input string    InpSymbolSuffix  = "";          // Bridge: broker symbol suffix (e.g. ".m")
input double    InpBETriggerR    = 1.0;         // Bridge: break-even trigger (R multiple)
input double    InpDailyLossUSD  = 45.0;        // Bridge: daily-loss breaker ($)

CTrade trade;
int    g_atrHandle = INVALID_HANDLE;
datetime g_lastPoll = 0, g_lastHB = 0, g_lastNewsPoll = 0, g_newsBlockUntil = 0;
datetime g_lastBridge = 0;
bool     g_bridgeBreaker = false;   // v1.03: server daily-loss breaker state
string   g_feedStatus = "not polled yet", g_newsName = "", g_lastAction = "—";

//+------------------------------------------------------------------+
//| Small JSON helpers (the feed is flat objects in an array)        |
//+------------------------------------------------------------------+
string JsonStrAfter(const string js, const string key, const int fromPos)
{
   int p = StringFind(js, "\"" + key + "\"", fromPos);
   if(p < 0) return "";
   int c = StringFind(js, ":", p);
   if(c < 0) return "";
   int q1 = StringFind(js, "\"", c);
   if(q1 < 0) return "";
   int q2 = StringFind(js, "\"", q1 + 1);
   if(q2 < 0) return "";
   return StringSubstr(js, q1 + 1, q2 - q1 - 1);
}

double JsonNumAfter(const string js, const string key, const int fromPos, bool &found)
{
   found = false;
   int p = StringFind(js, "\"" + key + "\"", fromPos);
   if(p < 0) return 0;
   int c = StringFind(js, ":", p);
   if(c < 0) return 0;
   int i = c + 1;
   while(i < StringLen(js) && (StringGetCharacter(js, i) == 32 || StringGetCharacter(js, i) == 34)) i++;
   int j = i;
   while(j < StringLen(js))
   {
      ushort ch = StringGetCharacter(js, j);
      if((ch >= '0' && ch <= '9') || ch == '.' || ch == '-' || ch == '+') j++; else break;
   }
   if(j <= i) return 0;
   found = true;
   return StringToDouble(StringSubstr(js, i, j - i));
}

datetime ParseFeedTime(string s)
{
   // "2026-11-14T05:30:00.000Z" -> MQL5 datetime (treated as server-local; age check is approximate)
   StringReplace(s, "-", ".");
   StringReplace(s, "T", " ");
   int dot = StringFind(s, ".", 10);           // fractional seconds start (after the date dots)
   if(dot > 0) s = StringSubstr(s, 0, dot);
   StringReplace(s, "Z", "");
   return StringToTime(s);
}

//+------------------------------------------------------------------+
//| Logging                                                          |
//+------------------------------------------------------------------+
void LogLine(const string msg)
{
   g_lastAction = msg;
   Print("[ATSIX] ", msg);
   int h = FileOpen("AITeamSix_EA_log.csv", FILE_READ | FILE_WRITE | FILE_TXT | FILE_ANSI | FILE_COMMON);
   if(h != INVALID_HANDLE)
   {
      FileSeek(h, 0, SEEK_END);
      FileWriteString(h, TimeToString(TimeCurrent(), TIME_DATE | TIME_SECONDS) + "," + msg + "\r\n");
      FileClose(h);
   }
}

//+------------------------------------------------------------------+
//| Filters + sizing                                                 |
//+------------------------------------------------------------------+
bool SpreadOK()
{
   MqlTick t;
   if(!SymbolInfoTick(_Symbol, t)) return false;
   double pts = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
   if(pts <= 0) return false;
   return (t.ask - t.bid) / pts <= InpMaxSpreadPts;
}

bool HoursOK()
{
   if(!InpUseHours) return true;
   MqlDateTime dt;
   TimeToStruct(TimeCurrent(), dt);
   if(InpHourStart <= InpHourEnd) return dt.hour >= InpHourStart && dt.hour < InpHourEnd;
   return dt.hour >= InpHourStart || dt.hour < InpHourEnd;
}

int MyPositions()
{
   int n = 0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong tk = PositionGetTicket(i);
      if(tk > 0 && PositionGetInteger(POSITION_MAGIC) == InpMagic && PositionGetString(POSITION_SYMBOL) == _Symbol) n++;
   }
   return n;
}

double CalcLots(const double slDistance)
{
   if(slDistance <= 0) return 0;
   double riskMoney = (InpRiskMode == RISK_PERCENT)
      ? AccountInfoDouble(ACCOUNT_BALANCE) * InpRiskPercent / 100.0
      : InpRiskDollars;
   double tickVal  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
   double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   if(tickVal <= 0 || tickSize <= 0) return 0;
   double lots = riskMoney / (slDistance / tickSize * tickVal);
   double minV = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double maxV = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   if(step <= 0) step = 0.01;
   lots = MathFloor(lots / step) * step;
   lots = MathMax(minV, MathMin(maxV, lots));
   return NormalizeDouble(lots, 2);
}

//+------------------------------------------------------------------+
//| Execution with retry on requote / off-quotes                     |
//+------------------------------------------------------------------+
bool Execute(const bool buy, const double sl, const double tp, const string tag)
{
   if(NewsBlocked()) { LogLine("SKIP " + tag + ": news blackout (" + g_newsName + ")"); return false; }
   if(!SpreadOK())   { LogLine("SKIP " + tag + ": spread too wide"); return false; }
   if(!HoursOK())    { LogLine("SKIP " + tag + ": outside trading hours"); return false; }
   if(InpOneAtATime && MyPositions() > 0) { LogLine("SKIP " + tag + ": position already open"); return false; }
   if(InpBridgeEnable && g_bridgeBreaker) { LogLine("SKIP " + tag + ": bridge daily-loss breaker tripped"); return false; }
   if(InpBridgeEnable && MyPositions() >= InpMaxOpenTrades) { LogLine("SKIP " + tag + ": bridge max open trades reached"); return false; }
   double lots = CalcLots(MathAbs((buy ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID)) - sl));
   if(lots <= 0) { LogLine("SKIP " + tag + ": lot size 0"); return false; }
   trade.SetExpertMagicNumber(InpMagic);
   trade.SetDeviationInPoints(30);
   for(int attempt = 1; attempt <= 3; attempt++)
   {
      MqlTick t;
      if(!SymbolInfoTick(_Symbol, t)) { Sleep(300); continue; }
      bool ok = buy ? trade.Buy(lots, _Symbol, t.ask, sl, tp, "ATSIX " + tag)
                    : trade.Sell(lots, _Symbol, t.bid, sl, tp, "ATSIX " + tag);
      if(ok)
      {
         LogLine("OPEN " + tag + " " + (buy ? "BUY" : "SELL") + " lots=" + DoubleToString(lots, 2) +
                 " sl=" + DoubleToString(sl, _Digits) + " tp=" + DoubleToString(tp, _Digits));
         return true;
      }
      uint rc = trade.ResultRetcode();
      LogLine("RETRY " + tag + " attempt " + IntegerToString(attempt) + " retcode=" + IntegerToString((int)rc) + " " + trade.ResultRetcodeDescription());
      if(rc != 10004 && rc != 10021 && rc != 10020) break; // only retry requote / off-quotes / fill issues
      Sleep(300);
   }
   return false;
}

//+------------------------------------------------------------------+
//| NEWS BLACKOUT — block new trades around High-impact events       |
//+------------------------------------------------------------------+
datetime ParseISO19(string s)
{
   // "2026-11-14T08:30:00-05:00" -> use the first 19 chars only.
   if(StringLen(s) > 19) s = StringSubstr(s, 0, 19);
   return ParseFeedTime(s);
}

void PollNews()
{
   char post[], result[];
   string headers;
   ResetLastError();
   int status = WebRequest("GET", InpNewsURL, NULL, 8000, post, result, headers);
   if(status == -1) return; // fail-open: a down news feed must not halt the EA
   string js = CharArrayToString(result, 0, WHOLE_ARRAY, CP_UTF8);
   datetime now = TimeCurrent();
   datetime blockUntil = 0;
   string blockName = "";
   int pos = 0;
   while(true)
   {
      int ip = StringFind(js, "\"impact\"", pos);
      if(ip < 0) break;
      pos = ip + 8;
      string imp = JsonStrAfter(js, "impact", ip - 8 >= 0 ? ip - 8 : 0);
      // JsonStrAfter searches from a position; search this object instead:
      int colon = StringFind(js, ":", ip);
      if(colon < 0) continue;
      int q1 = StringFind(js, "\"", colon);
      int q2 = (q1 >= 0) ? StringFind(js, "\"", q1 + 1) : -1;
      if(q1 < 0 || q2 < 0) continue;
      imp = StringSubstr(js, q1 + 1, q2 - q1 - 1);
      if(imp != "High") continue;
      int ap = StringFind(js, "\"at\"", q2);
      if(ap < 0) continue;
      int ac = StringFind(js, ":", ap);
      int a1 = StringFind(js, "\"", ac);
      int a2 = (a1 >= 0) ? StringFind(js, "\"", a1 + 1) : -1;
      if(a1 < 0 || a2 < 0) continue;
      datetime ev = ParseISO19(StringSubstr(js, a1 + 1, a2 - a1 - 1));
      if(ev <= 0) continue;
      if(now >= ev - InpNewsBlockMin * 60 && now <= ev + 15 * 60)
      {
         if(ev + 15 * 60 > blockUntil)
         {
            blockUntil = ev + 15 * 60;
            int tp = StringFind(js, "\"title\"", 0);
            blockName = "High-impact news";
            // best-effort title: nearest "title" before this impact
            int scan = ip;
            int lastT = -1;
            while(scan > 0)
            {
               int f = StringFind(js, "\"title\"", MathMax(0, scan - 400));
               if(f < 0 || f >= ip) break;
               lastT = f; break;
            }
            if(lastT >= 0)
            {
               string t = JsonStrAfter(js, "title", lastT);
               if(StringLen(t) > 0) blockName = t;
            }
         }
      }
   }
   g_newsBlockUntil = blockUntil;
   g_newsName = blockName;
   if(blockUntil > 0) LogLine("NEWS BLACKOUT active until " + TimeToString(blockUntil, TIME_DATE | TIME_MINUTES) + " — " + blockName);
}

bool NewsBlocked()
{
   return g_newsBlockUntil > 0 && TimeCurrent() < g_newsBlockUntil;
}

//+------------------------------------------------------------------+
//| On-chart dashboard                                               |
//+------------------------------------------------------------------+
void UpdateDashboard()
{
   MqlTick t;
   double spreadPts = 0;
   if(SymbolInfoTick(_Symbol, t))
   {
      double pts = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
      if(pts > 0) spreadPts = (t.ask - t.bid) / pts;
   }
   string mode = InpMode == MODE_FEED ? "FEED" : InpMode == MODE_ICT ? "ICT" : "BOTH";
   string dash = "AI TEAM SiX EA v1.03 · " + _Symbol + " · mode " + mode + "\n"
      + "Feed: " + g_feedStatus + " · last poll " + (g_lastPoll > 0 ? TimeToString(g_lastPoll, TIME_SECONDS) : "—") + "\n"
      + "News: " + (NewsBlocked() ? "BLACKOUT until " + TimeToString(g_newsBlockUntil, TIME_MINUTES) + " (" + g_newsName + ")" : "clear") + "\n"
      + "Positions: " + IntegerToString(MyPositions()) + " · Balance $" + DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE), 2)
      + " · Equity $" + DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY), 2) + "\n"
      + "Spread: " + DoubleToString(spreadPts, 0) + " pts (max " + IntegerToString(InpMaxSpreadPts) + ") · Magic " + IntegerToString(InpMagic) + "\n"
      + "Last action: " + g_lastAction;
   Comment(dash);
}

//+------------------------------------------------------------------+
//| FEED MODE — poll the signals JSON and execute new signals        |
//+------------------------------------------------------------------+
void PollFeed()
{
   char post[], result[];
   string headers;
   ResetLastError();
   int status = WebRequest("GET", InpFeedURL, NULL, 8000, post, result, headers);
   if(status == -1)
   {
      g_feedStatus = "FEED ERROR (WebRequest)";
      LogLine("FEED ERROR: WebRequest failed err=" + IntegerToString(GetLastError()) +
              " (allow the feed host in Tools > Options > Expert Advisors)");
      return;
   }
   string js = CharArrayToString(result, 0, WHOLE_ARRAY, CP_UTF8);
   // The live API lists live-computed plans FIRST. Take the first
   // complete BUY/SELL object in the payload (WAIT entries are skipped).
   string dir = "", time = "", tfs = "";
   double entry = 0, sl = 0, tp1 = 0, tp2 = 0;
   bool f1 = false, f2 = false, f3 = false, f6 = false, found = false;
   int dp = StringFind(js, "\"dir\"", 0);
   while(dp >= 0 && !found)
   {
      int scan = dp;
      while(scan > 0 && StringGetCharacter(js, scan) != '{') scan--;
      string d0 = JsonStrAfter(js, "dir", scan);
      if(d0 == "BUY" || d0 == "SELL")
      {
         bool g1, g2, g3, g6;
         double e0 = JsonNumAfter(js, "entry", scan, g1);
         double s0 = JsonNumAfter(js, "sl", scan, g2);
         double t0 = JsonNumAfter(js, "tp1", scan, g3);
         double u0 = JsonNumAfter(js, "tp2", scan, g6);
         if(g1 && g2 && g3)
         {
            dir = d0; entry = e0; sl = s0; tp1 = t0; tp2 = u0;
            f1 = g1; f2 = g2; f3 = g3; f6 = g6;
            time = JsonStrAfter(js, "time", scan);
            tfs  = JsonStrAfter(js, "tf", scan);
            found = true;
         }
      }
      dp = StringFind(js, "\"dir\"", dp + 1);
   }
   if(!found)
   { g_feedStatus = "no actionable signal"; LogLine("FEED: no complete BUY/SELL signal in payload"); return; }
   g_feedStatus = "OK · " + dir + " " + tfs + " @ " + DoubleToString(entry, 2);

   string key = time + "|" + dir + "|" + DoubleToString(entry, 2) + "|" + DoubleToString(sl, 2);
   string gvName = "ATSIX_LASTSIG_" + IntegerToString(InpMagic);
   if(GlobalVariableCheck(gvName))
   {
      // stored as time-hash: compare via a second GV holding the key length+sum is fragile;
      // instead keep the key itself in a file-free way: use GV of StringToInteger hash.
   }
   double keyHash = 0;
   for(int i = 0; i < StringLen(key); i++) keyHash = keyHash * 131.0 + StringGetCharacter(key, i);
   if(GlobalVariableCheck(gvName) && GlobalVariableGet(gvName) == keyHash)
      return; // already handled this signal

   datetime sigTime = ParseFeedTime(time);
   if(sigTime > 0 && (TimeCurrent() - sigTime) > InpMaxSignalAgeMin * 60 && (TimeCurrent() - sigTime) < 30 * 86400)
   {
      LogLine("FEED: signal too old (" + time + ") — marked seen, not executed");
      GlobalVariableSet(gvName, keyHash);
      return;
   }

   bool buy = (dir == "BUY");
   // Enforce TP ordering on our side too: BUY take the max as TP1 target is wrong —
   // the feed's tp1 is the NEAREST target by construction; verify direction sanity:
   if(buy  && !(sl < entry && tp1 > entry)) { LogLine("FEED: BUY levels inconsistent — skipped"); GlobalVariableSet(gvName, keyHash); return; }
   if(!buy && !(sl > entry && tp1 < entry)) { LogLine("FEED: SELL levels inconsistent — skipped"); GlobalVariableSet(gvName, keyHash); return; }

   MqlTick t;
   if(!SymbolInfoTick(_Symbol, t)) return;
   double px = buy ? t.ask : t.bid;
   if(MathAbs(px - entry) > InpEntryTolUSD)
   {
      LogLine("FEED: " + dir + " " + tfs + " waiting for entry zone " + DoubleToString(entry, 2) +
              " (now " + DoubleToString(px, 2) + ")");
      return; // not marked seen — a later poll may execute when price reaches the zone
   }
   double orderTp = (InpPartialTP1 && f6 && tp2 > 0) ? tp2 : tp1;
   if(Execute(buy, NormalizeDouble(sl, _Digits), NormalizeDouble(orderTp, _Digits), "FEED " + dir + " " + tfs))
   {
      GlobalVariableSet(gvName, keyHash);
      if(InpPartialTP1 && f6 && tp2 > 0)
      {
         ulong deal = trade.ResultDeal();
         long posId = 0;
         if(deal > 0 && HistoryDealSelect(deal)) posId = HistoryDealGetInteger(deal, DEAL_POSITION_ID);
         if(posId > 0) GlobalVariableSet("ATSIX_TP1_" + IntegerToString(posId), tp1);
      }
   }
}

//+------------------------------------------------------------------+
//| ICT FALLBACK — Sweep -> displacement + FVG, retest on a LATER    |
//| bar only (v1.01 fix: never enter on the displacement bar itself) |
//+------------------------------------------------------------------+
datetime g_lastBar = 0;
void ICTScan()
{
   MqlRates rates[];
   ArraySetAsSeries(rates, true);
   if(CopyRates(_Symbol, InpTF, 0, 160, rates) < 120) return;
   if(rates[0].time == g_lastBar) return;   // once per new bar
   g_lastBar = rates[0].time;

   double atrBuf[];
   if(g_atrHandle == INVALID_HANDLE) return;
   ArraySetAsSeries(atrBuf, true);
   if(CopyBuffer(g_atrHandle, 0, 0, 60, atrBuf) < 30) return;
   double atr = atrBuf[1];
   if(atr <= 0) return;

   // Find the most recent strict displacement + FVG (bullish example):
   // displacement candle at shift d (closed bars only, d>=2), FVG between
   // rates[d-1] and rates[d+1]. Retest must be a bar with shift < d-1,
   // i.e. STRICTLY LATER than the FVG-forming candle — never bar d itself.
   for(int d = 2; d < 40; d++)
   {
      double body = MathAbs(rates[d].close - rates[d].open);
      if(body < 1.1 * atr) continue;                       // displacement strength
      bool bull = rates[d].close > rates[d].open;
      double fvgTop = bull ? rates[d - 1].low  : rates[d + 1].low;
      double fvgBot = bull ? rates[d + 1].high : rates[d - 1].high;
      if(fvgBot >= fvgTop) continue;                       // no FVG gap (either direction)
      // sweep before displacement: prior 30 bars swept a swing level
      bool swept = false;
      for(int s = d + 2; s < d + 32 && s < 120; s++)
      {
         if(bull  && rates[s].low  < rates[d + 1].low  - 0.1 * atr) swept = true;
         if(!bull && rates[s].high > rates[d + 1].high + 0.1 * atr) swept = true;
      }
      if(!swept) continue;
      // retest on a later bar: any closed bar r with 1 <= r < d-1 touched the zone,
      // and the most recent closed bar (shift 1) closed back in direction.
      bool retested = false;
      for(int r = 1; r < d - 1; r++)
         if(rates[r].low <= fvgTop && rates[r].high >= fvgBot) retested = true;
      if(!retested) continue;
      if(bull  && rates[1].close < rates[1].open) continue;
      if(!bull && rates[1].close > rates[1].open) continue;

      MqlTick t;
      if(!SymbolInfoTick(_Symbol, t)) return;
      double px = bull ? t.ask : t.bid;
      if(MathAbs(px - (fvgTop + fvgBot) / 2.0) > 1.2 * atr) return;  // price must be near the zone
      double sl = bull ? px - InpSL_USD : px + InpSL_USD;
      double risk = MathAbs(px - sl);
      double tp = bull ? px + 2.0 * risk : px - 2.0 * risk;
      Execute(bull, NormalizeDouble(sl, _Digits), NormalizeDouble(tp, _Digits), "ICT " + EnumToString(InpTF));
      return;
   }
}

//+------------------------------------------------------------------+
//| Partial close at TP1 (feed trades): close 50%, SL to break-even, |
//| remainder runs to the order TP (TP2).                            |
//+------------------------------------------------------------------+
void ManagePartial()
{
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong tk = PositionGetTicket(i);
      if(tk == 0 || PositionGetInteger(POSITION_MAGIC) != InpMagic) continue;
      if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
      long posId = PositionGetInteger(POSITION_IDENTIFIER);
      string gvT = "ATSIX_TP1_" + IntegerToString(posId);
      string gvD = "ATSIX_PDONE_" + IntegerToString(posId);
      if(!GlobalVariableCheck(gvT) || GlobalVariableCheck(gvD)) continue;
      double tp1  = GlobalVariableGet(gvT);
      double open = PositionGetDouble(POSITION_PRICE_OPEN);
      double tp   = PositionGetDouble(POSITION_TP);
      long   type = PositionGetInteger(POSITION_TYPE);
      MqlTick t;
      if(!SymbolInfoTick(_Symbol, t)) continue;
      bool hit = (type == POSITION_TYPE_BUY) ? (t.bid >= tp1) : (t.ask <= tp1);
      if(!hit) continue;
      double vol  = PositionGetDouble(POSITION_VOLUME);
      double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
      double minV = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
      if(step <= 0) step = 0.01;
      double half = MathFloor((vol / 2.0) / step) * step;
      trade.SetExpertMagicNumber(InpMagic);
      bool acted = false;
      if(half >= minV && vol - half >= minV)
         acted = trade.PositionClosePartial(tk, NormalizeDouble(half, 2));
      if(trade.PositionModify(tk, NormalizeDouble(open, _Digits), tp)) acted = true;
      if(acted)
      {
         GlobalVariableSet(gvD, 1);
         LogLine("TP1 partial/BE for ticket " + IntegerToString((long)tk) + " tp1=" + DoubleToString(tp1, _Digits));
      }
   }
}

//+------------------------------------------------------------------+
//| Manage open positions: TP1 proxy — when price travels 1R in      |
//| favour, move SL to break-even. (Feed trades carry TP1 as the     |
//| order TP, so BE is applied to ICT trades and partial runners.)   |
//+------------------------------------------------------------------+
void ManageBE()
{
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong tk = PositionGetTicket(i);
      if(tk == 0 || PositionGetInteger(POSITION_MAGIC) != InpMagic) continue;
      if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
      double open = PositionGetDouble(POSITION_PRICE_OPEN);
      double sl   = PositionGetDouble(POSITION_SL);
      double tp   = PositionGetDouble(POSITION_TP);
      long   type = PositionGetInteger(POSITION_TYPE);
      if(MathAbs(sl - open) < SymbolInfoDouble(_Symbol, SYMBOL_POINT)) continue; // already at BE
      double risk = MathAbs(tp - open) / 2.0;                 // TP set at 2R in ICT mode
      if(risk <= 0) risk = MathAbs(open - sl);
      MqlTick t;
      if(!SymbolInfoTick(_Symbol, t)) continue;
      bool favour = (type == POSITION_TYPE_BUY)  ? (t.bid >= open + risk)
                                                 : (t.ask <= open - risk);
      if(favour)
      {
         trade.SetExpertMagicNumber(InpMagic);
         if(trade.PositionModify(tk, NormalizeDouble(open, _Digits), tp))
            LogLine("BE moved for ticket " + IntegerToString((long)tk));
      }
   }
}

//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| v1.03 MT5 BRIDGE — heartbeat + fill reports                       |
//+------------------------------------------------------------------+
string BridgeJsonEsc(const string v)
{
   string r = v;
   StringReplace(r, "\\", "\\\\");
   StringReplace(r, "\"", "\\\"");
   return r;
}

bool BridgePost(const string path, const string body, string &resp)
{
   char post[], result[]; string headers;
   StringToCharArray(body, post, 0, WHOLE_ARRAY, CP_UTF8);
   if(ArraySize(post) > 0) ArrayResize(post, ArraySize(post) - 1); // drop trailing NUL
   ResetLastError();
   int status = WebRequest("POST", InpBridgeURL + path, "Content-Type: application/json\r\n", 8000, post, result, headers);
   if(status == -1)
   {
      LogLine("BRIDGE POST " + path + " failed err=" + IntegerToString(GetLastError()) +
              " (allow WebRequest for " + InpBridgeURL + ")");
      return false;
   }
   resp = CharArrayToString(result, 0, WHOLE_ARRAY, CP_UTF8);
   return true;
}

void BridgeFill(const string evId, const string type, const long ticket, const string sym,
                const string dir, const double lots, const double price,
                const double sl, const double tp, const double pnl, const string comment)
{
   if(!InpBridgeEnable || StringLen(InpBridgeToken) < 8) return;
   string body = "{"
      + "\"token\":\"" + BridgeJsonEsc(InpBridgeToken) + "\","
      + "\"id\":\"" + BridgeJsonEsc(evId) + "\","
      + "\"type\":\"" + type + "\","
      + "\"ticket\":" + IntegerToString(ticket) + ","
      + "\"symbol\":\"" + BridgeJsonEsc(sym) + "\","
      + "\"dir\":\"" + dir + "\","
      + "\"lots\":" + DoubleToString(lots, 2) + ","
      + "\"price\":" + DoubleToString(price, _Digits) + ","
      + "\"sl\":" + DoubleToString(sl, _Digits) + ","
      + "\"tp\":" + DoubleToString(tp, _Digits) + ","
      + "\"pnl\":" + DoubleToString(pnl, 2) + ","
      + "\"comment\":\"" + BridgeJsonEsc(comment) + "\"}";
   string resp;
   if(BridgePost("/api/mt5/fill", body, resp))
      LogLine("BRIDGE FILL " + type + " ticket=" + IntegerToString(ticket) + " id=" + evId);
}

void BridgeHeartbeat()
{
   if(!InpBridgeEnable || StringLen(InpBridgeToken) < 8) return;
   string posJson = "";
   int cnt = 0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong tk = PositionGetTicket(i);
      if(tk == 0) continue;
      if(PositionGetInteger(POSITION_MAGIC) != InpMagic) continue;
      if(cnt > 0) posJson += ",";
      long ptype = PositionGetInteger(POSITION_TYPE);
      posJson += "{\"ticket\":" + IntegerToString((long)tk)
         + ",\"symbol\":\"" + BridgeJsonEsc(PositionGetString(POSITION_SYMBOL)) + "\""
         + ",\"dir\":\"" + (ptype == POSITION_TYPE_BUY ? "BUY" : "SELL") + "\""
         + ",\"lots\":" + DoubleToString(PositionGetDouble(POSITION_VOLUME), 2)
         + ",\"open\":" + DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), _Digits)
         + ",\"sl\":" + DoubleToString(PositionGetDouble(POSITION_SL), _Digits)
         + ",\"tp\":" + DoubleToString(PositionGetDouble(POSITION_TP), _Digits) + "}";
      cnt++;
   }
   string body = "{"
      + "\"kind\":\"ea\","
      + "\"token\":\"" + BridgeJsonEsc(InpBridgeToken) + "\","
      + "\"symbolSuffix\":\"" + BridgeJsonEsc(InpSymbolSuffix) + "\","
      + "\"account\":{\"login\":" + IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN))
      + ",\"balance\":" + DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE), 2)
      + ",\"equity\":" + DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY), 2)
      + ",\"currency\":\"" + BridgeJsonEsc(AccountInfoString(ACCOUNT_CURRENCY)) + "\"},"
      + "\"positions\":[" + posJson + "],"
      + "\"lastSignalTs\":0}";
   string resp;
   if(!BridgePost("/api/mt5/heartbeat", body, resp)) return;
   // Daily-loss breaker state from the server (it sums today's fills).
   g_bridgeBreaker = (StringFind(resp, "\"tripped\":true") >= 0 || StringFind(resp, "\"tripped\": true") >= 0);
   if(g_bridgeBreaker)
      LogLine("BRIDGE: daily-loss breaker TRIPPED — no new entries until tomorrow");
   // Server-ordered close_all from the app dashboard.
   if(StringFind(resp, "\"close_all\"") >= 0)
   {
      LogLine("BRIDGE: server ordered close_all — closing all my positions");
      trade.SetExpertMagicNumber(InpMagic);
      for(int i = PositionsTotal() - 1; i >= 0; i--)
      {
         ulong tk = PositionGetTicket(i);
         if(tk == 0) continue;
         if(PositionGetInteger(POSITION_MAGIC) != InpMagic) continue;
         trade.PositionClose(tk);
      }
   }
}

void OnTradeTransaction(const MqlTradeTransaction &trans,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &result)
{
   if(!InpBridgeEnable) return;
   if(trans.type != TRADE_TRANSACTION_DEAL_ADD || trans.deal == 0) return;
   if(!HistoryDealSelect(trans.deal)) return;
   long dtype = HistoryDealGetInteger(trans.deal, DEAL_TYPE);
   string dir = (dtype == DEAL_TYPE_BUY) ? "BUY" : (dtype == DEAL_TYPE_SELL) ? "SELL" : "";
   if(dir == "") return;
   long entry = HistoryDealGetInteger(trans.deal, DEAL_ENTRY);
   string sym = HistoryDealGetString(trans.deal, DEAL_SYMBOL);
   double vol = HistoryDealGetDouble(trans.deal, DEAL_VOLUME);
   double price = HistoryDealGetDouble(trans.deal, DEAL_PRICE);
   long posId = HistoryDealGetInteger(trans.deal, DEAL_POSITION_ID);
   string evId = IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN)) + "-" + IntegerToString((long)trans.deal);
   if(entry == DEAL_ENTRY_IN)
      BridgeFill(evId, "placed", posId, sym, dir, vol, price, 0, 0, 0, "deal in");
   else if(entry == DEAL_ENTRY_OUT || entry == DEAL_ENTRY_INOUT)
   {
      double pnl = HistoryDealGetDouble(trans.deal, DEAL_PROFIT)
                 + HistoryDealGetDouble(trans.deal, DEAL_SWAP)
                 + HistoryDealGetDouble(trans.deal, DEAL_COMMISSION);
      BridgeFill(evId, "closed", posId, sym, dir, vol, price, 0, 0, pnl, "deal out");
   }
}

int OnInit()
{
   g_atrHandle = iATR(_Symbol, InpTF, InpATRPeriod);
   EventSetTimer(10);
   PollNews();
   UpdateDashboard();
   LogLine("INIT v1.03 mode=" + IntegerToString((int)InpMode) + " feed=" + InpFeedURL);
   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason)
{
   Comment("");
   EventKillTimer();
   if(g_atrHandle != INVALID_HANDLE) IndicatorRelease(g_atrHandle);
}

void OnTimer()
{
   datetime now = TimeCurrent();
   if(InpBridgeEnable && now - g_lastBridge >= MathMax(1, InpBridgeHBSec))
   { g_lastBridge = now; BridgeHeartbeat(); }
   if((InpMode == MODE_FEED || InpMode == MODE_BOTH) && now - g_lastPoll >= InpPollSeconds)
   { g_lastPoll = now; PollFeed(); }
   if(now - g_lastNewsPoll >= 300)
   { g_lastNewsPoll = now; PollNews(); }
   UpdateDashboard();
   if(now - g_lastHB >= InpHeartbeatSec)
   { g_lastHB = now; LogLine("HEARTBEAT positions=" + IntegerToString(MyPositions()) + " balance=" + DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE), 2)); }
}

void OnTick()
{
   if(InpMode == MODE_ICT || InpMode == MODE_BOTH) ICTScan();
   ManagePartial();
   ManageBE();
}
//+------------------------------------------------------------------+
