//+------------------------------------------------------------------+
//| Open Legacy All-in-One EA                                           |
//| v1.70: ONE EA = webhook trader + instant TP/SL close + Auto SL/TP |
//|        + Copy Master (ShareToReceiver) + Copy Receiver (Role).     |
//| Opens trades from Open Legacy indicator alerts. TradingView sends |
//| the alert to your relay (Cloudflare Worker); this EA checks the   |
//| relay every second and places the trade. Runs on the MQL5 VPS.    |
//| Needs: Tools > Options > Expert Advisors > Allow WebRequest, with |
//| your Relay URL added to the list.                                 |
//+------------------------------------------------------------------+
#property copyright "Open Legacy"
#property version   "1.84"
#property description "Open Legacy All-in-One EA - trades the indicator's alerts (lot size comes from the indicator), with a max open trades limit and an optional waiting list."
#include <Trade\Trade.mqh>

void OLComment(const string txt);
void OLPanelClear();
enum ENUM_ROLE { ROLE_TRADER=0, ROLE_RECEIVER=1 };
enum ENUM_NEWS_LEVEL { NEWS_RED_ONLY=0, NEWS_ORANGE_RED=1, NEWS_ALL_COLOURS=2 };
enum ENUM_NEWS_SRC { SRC_FOREX_FACTORY=0, SRC_MT5_CALENDAR=1 };

input group "Role"
input ENUM_ROLE Role = ROLE_TRADER; // Role: Trader or Copy Receiver
input group "Splash screen"
input bool   ShowSplash     = true; // Show the Open Legacy splash screen on start
input bool   SplashStay     = false; // Keep it on the chart permanently
input int    SplashSeconds  = 6;    // Seconds shown (0 = until clicked)
input int    SplashOpacity  = 90;   // Opacity % (lower = see more chart)
input group "Webhook"
input string RelayURL       = "https://your-relay.workers.dev"; // Relay URL (Cloudflare Worker)
input string SecretKey      = ""; // Secret key
input int    PollSeconds    = 1; // Check for signals every (sec)
input int    MaxSignalAge   = 120; // Ignore signals older than (sec)

input group "Trade limits"
input int    MaxOpenTrades   = 1; // Max trades open at once
input bool   CountAllTrades  = false; // Count manual/other trades too
input bool   CloseOnOpposite = true; // Opposite signal closes + flips
input bool   CloseOnAlert    = true; // Close the trade the moment the indicator alerts TP hit / SL hit
input bool   QueueSignals    = true; // Hold signals until a slot is free
input int    QueueExpiryMin  = 30; // Drop held signal after (min)
input string AllowedSymbols  = ""; // Only trade pairs (blank = all)

input group "Symbols (lot set in indicator)"
input string SymbolMap       = ""; // Name map, e.g. SP500=US500
input string SymbolSuffix    = ""; // Pair suffix, e.g. .s
input int    SlippagePoints  = 30; // Max slippage (points)

input group "Match TP / SL (price differences)"
input bool   MatchChartMove  = true; // Match indicator TP/SL distance
input int    TPBufferPoints  = 0; // TP closer by (points)
input int    SLBufferPoints  = 0; // SL further by (points), minus = closer
input string TPBufferMap     = "XAUUSD=0.30,BTCUSD=15,NAS100=2,AUDUSD=0.00006,GBPUSD=0.00008"; // Per-pair TP buffer (price)
input string SLBufferMap     = ""; // Per-pair SL buffer (price), e.g. XAUUSD=-0.20

input group "News filter (skips trades near news)"
input bool   UseNewsFilter   = true; // Skip trades near news
input int    NewsBeforeMin   = 40; // Pause this many min before news
input int    NewsAfterMin    = 30; // ...and this many min after
input bool   CloseBeforeNews = false; // Also close open trades when the pause starts
input ENUM_NEWS_SRC NewsSource = SRC_FOREX_FACTORY; // News source
input ENUM_NEWS_LEVEL NewsLevel = NEWS_ORANGE_RED; // Colours to avoid
input bool   NewsKeyOnly     = false; // Key words only (off = all events)
input string NewsKeywords    = "CPI,PPI,PCE,FOMC,Fed,Powell,Non-Farm,Nonfarm,NFP,PMI,ISM,Interest Rate,Rate Decision,Rate Statement,GDP,Retail Sales,Unemployment,Jobless Claims,Employment Change,Consumer Confidence,Bailey,Lagarde"; // Key event words
input string NewsExtraCcy    = "USD"; // Always watch these currencies
input string NewsAlwaysWords = ""; // Always-pause words (any colour)
input string NewsIgnoreOrange = "Speaks,Speech"; // Ignore orange words (not red)
input int    NewsShiftMin    = 0;   // News clock offset (min)
input group "Auto SL/TP for manual trades"
input bool   UseAutoSLTP     = false; // Turn on Auto SL/TP
input string AutoRules       = "XAUUSD=60/40, NAS100=1400/1000"; // Pair=SL/TP in pips, comma separated
input int    AutoPointsPerPip = 10; // Points per pip (10 for gold, BTC, indices)
input bool   AutoManualOnly  = true; // Only touch trades you open yourself (not the EA's)
input group "Copy Master (share trades)"
input bool   ShareToReceiver = false; // Share every trade here with a Copy Receiver
input string Channel         = "main"; // Channel name (receiver must use the same)

input long   OnlyMagic       = -1;     // Share only this magic number (-1 = all)
input bool   ShareExisting   = false;  // Also share trades already open when this EA starts
input string OnlySymbols     = "";     // Only share these pairs, e.g. XAUUSD.s (blank = all)

input int    ScanMs          = 250;    // How often to check this account (ms)
input int    SnapshotSeconds = 10;     // Safety snapshot every (sec)


enum LOT_MODE { LOT_MULTIPLIER = 0, LOT_FIXED = 1 };

input group "Copy Receiver settings"
input group "Receiver lot size"
input LOT_MODE LotMode     = LOT_MULTIPLIER; // Lot sizing
input double LotMultiplier = 1.0;    // Multiplier x the Master's lots
input double FixedLot      = 0.01;   // Fixed lot (when mode = Fixed)
input double MaxLotPerTrade = 0;     // Cap per trade (0 = no cap)

input group "Safety"
input int    RMaxOpenTrades   = 0;    // Max copied trades open at once (0 = no limit)
input int    PollMs         = 1000; // Receiver: check for new trades every (ms)
input int    MaxOpenAgeSec   = 20;   // Skip copy if Master opened it over (sec) ago
input bool   SLTPFromEntry   = true; // Keep SL/TP distance from entry
input bool   SyncOrphans     = true; // Close copies whose Master trade no longer exists
input string RAllowedSymbols  = "";   // Only copy these Master pairs (blank = all)

input group "Symbols"
input string RSymbolMap       = "";   // Master=This broker, e.g. XAUUSD.s=XAUUSD
input string RSymbolSuffix    = "";   // Added to the base name if needed, e.g. .cash
input long   RMagic     = 777002; // Magic number for copied trades


input group "Layering (extra half-size trade from Open Legacy Side-Kick)"
input bool   UseLayering     = false; // Accept layer signals from Open Legacy Side-Kick
input double LayerLotPct     = 50; // Layer size (% of first trade lots)
input long   MagicNumber     = 777001; // Magic number

CTrade trade;
ulong nextWh = 0;

// ---- Auto SL/TP (merged from the Auto SL/TP EA) ----
string aSym[];
double aSl[];
double aTp[];
ulong  aDone[];
ulong  aTryT[];
int    aTryN[];

bool AIsDone(ulong t){ for(int i=0;i<ArraySize(aDone);i++) if(aDone[i]==t) return true; return false; }
void AMarkDone(ulong t){ int n=ArraySize(aDone); ArrayResize(aDone,n+1); aDone[n]=t; }
int  ATries(ulong t){ for(int i=0;i<ArraySize(aTryT);i++) if(aTryT[i]==t) return ++aTryN[i]; int n=ArraySize(aTryT); ArrayResize(aTryT,n+1); ArrayResize(aTryN,n+1); aTryT[n]=t; aTryN[n]=1; return 1; }

bool AParse()
{
   ArrayResize(aSym,0); ArrayResize(aSl,0); ArrayResize(aTp,0);
   string parts[];
   int n = StringSplit(AutoRules, ',', parts);
   for(int i=0;i<n;i++)
   {
      string p = parts[i];
      StringTrimLeft(p); StringTrimRight(p);
      if(StringLen(p)==0) continue;
      string kv[];
      if(StringSplit(p, '=', kv)!=2) { Print("Open Legacy Auto SL/TP: can't read rule '", p, "' (use PAIR=SL/TP)"); return false; }
      string key = kv[0]; StringTrimLeft(key); StringTrimRight(key); StringToUpper(key);
      string v[];
      if(StringSplit(kv[1], '/', v)!=2) { Print("Open Legacy Auto SL/TP: can't read '", p, "' (use PAIR=SL/TP)"); return false; }
      int k = ArraySize(aSym);
      ArrayResize(aSym,k+1); ArrayResize(aSl,k+1); ArrayResize(aTp,k+1);
      aSym[k] = key; aSl[k] = StringToDouble(v[0]); aTp[k] = StringToDouble(v[1]);
   }
   return ArraySize(aSym) > 0;
}

int AFind(string sym)
{
   string s = sym; StringToUpper(s);
   for(int i=0;i<ArraySize(aSym);i++) if(StringFind(s, aSym[i])==0) return i;
   return -1;
}

void AutoApply()
{
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      ulong t = PositionGetTicket(i);
      if(t==0 || AIsDone(t)) continue;
      if(AutoManualOnly && PositionGetInteger(POSITION_MAGIC)!=0) { AMarkDone(t); continue; }
      string sym = PositionGetString(POSITION_SYMBOL);
      int r = AFind(sym);
      if(r<0) { AMarkDone(t); continue; }
      double curSl = PositionGetDouble(POSITION_SL), curTp = PositionGetDouble(POSITION_TP);
      if(curSl!=0.0 && curTp!=0.0) { AMarkDone(t); continue; }   // already has both: leave it

      bool   buy   = PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY;
      double open  = PositionGetDouble(POSITION_PRICE_OPEN);
      double pt    = SymbolInfoDouble(sym, SYMBOL_POINT);
      int    dg    = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
      double dSl   = aSl[r] * AutoPointsPerPip * pt;
      double dTp   = aTp[r] * AutoPointsPerPip * pt;
      double sl    = curSl!=0.0 ? curSl : (aSl[r]>0 ? (buy ? open-dSl : open+dSl) : 0.0);
      double tp    = curTp!=0.0 ? curTp : (aTp[r]>0 ? (buy ? open+dTp : open-dTp) : 0.0);

      // keep levels outside the broker's minimum distance
      double minD  = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL) * pt;
      double bid   = SymbolInfoDouble(sym, SYMBOL_BID), ask = SymbolInfoDouble(sym, SYMBOL_ASK);
      double ref   = buy ? bid : ask;
      if(sl!=0.0) sl = buy ? MathMin(sl, ref-minD) : MathMax(sl, ref+minD);
      if(tp!=0.0) tp = buy ? MathMax(tp, ref+minD) : MathMin(tp, ref-minD);
      sl = NormalizeDouble(sl, dg); tp = NormalizeDouble(tp, dg);

      if(trade.PositionModify(t, sl, tp))
      {
         AMarkDone(t);
         PrintFormat("Open Legacy Auto SL/TP: %s #%I64u  SL %s  TP %s", sym, t, DoubleToString(sl,dg), DoubleToString(tp,dg));
      }
      else if(ATries(t)>=10)
      {
         AMarkDone(t);
         PrintFormat("Open Legacy Auto SL/TP: gave up on #%I64u (%s): %s", t, sym, trade.ResultRetcodeDescription());
      }
   }
}


long   lastId  = 0;
string status  = "Starting...";
string lastSig = "none yet";
string gvName;

// Signals waiting for a free slot (one per pair, newest wins)
string   qSide[], qTv[];
double   qSl[], qTp[], qLots[];
datetime qTime[];

// Looks up a pair in a buffer map (price units). Returns EMPTY_VALUE if the pair isn't listed.
double MapBuf(const string map, const string tv, const string sym)
{
   string parts[];
   int n = StringSplit(map, ',', parts);
   string a = tv, b = sym;
   StringToUpper(a); StringToUpper(b);
   int dot = StringFind(b, "."); if(dot>0) b = StringSubstr(b, 0, dot);
   for(int i=0;i<n;i++)
   {
      string kv[];
      if(StringSplit(parts[i], '=', kv)!=2) continue;
      string k = kv[0]; StringTrimLeft(k); StringTrimRight(k); StringToUpper(k);
      if(k==a || k==b) return StringToDouble(kv[1]);
   }
   return EMPTY_VALUE;
}

string Trim(string s){ StringTrimLeft(s); StringTrimRight(s); return s; }
string Up(string s){ StringToUpper(s); return s; }

void Note(const string msg);

// readable signal name for on-screen messages, e.g. "LSELL" -> "layer SELL", "XTP@15" -> "TP hit (15)"
string NiceSide(const string sd)
{
   string s = sd, tf = "";
   int at = StringFind(s, "@");
   if(at>0) { tf = StringSubstr(s, at+1); s = StringSubstr(s, 0, at); }
   string r = s;
   if(s=="LBUY")  r = "layer BUY";
   if(s=="LSELL") r = "layer SELL";
   if(s=="XTP")   r = "TP hit";
   if(s=="XSL")   r = "SL hit";
   if(tf!="") r += " (" + tf + ")";
   return r;
}

// ---- news filter ----
bool KeyMatch(const string name)
{
   string n = name; StringToUpper(n);
   string w[];
   int k = StringSplit(NewsKeywords, ',', w);
   for(int i=0;i<k;i++)
   {
      string x = Trim(w[i]); StringToUpper(x);
      if(x!="" && StringFind(n, x)>=0) return true;
   }
   return false;
}

bool IgnoreMatch(const string name)
{
   string n = name; StringToUpper(n);
   string w[];
   int k = StringSplit(NewsIgnoreOrange, ',', w);
   for(int i=0;i<k;i++)
   {
      string x = Trim(w[i]); StringToUpper(x);
      if(x!="" && StringFind(n, x)>=0) return true;
   }
   return false;
}

bool AlwaysMatch(const string name)
{
   string n = name; StringToUpper(n);
   string w[];
   int k = StringSplit(NewsAlwaysWords, ',', w);
   for(int i=0;i<k;i++)
   {
      string x = Trim(w[i]); StringToUpper(x);
      if(x!="" && StringFind(n, x)>=0) return true;
   }
   return false;
}

bool calWarned = false;

// ---- Forex Factory feed (fetched through your relay, refreshed every 10 min) ----
datetime ffT[]; string ffC[]; int ffI[]; string ffN[];
int ffCount = 0; datetime ffLast = 0; bool ffOk = false;

void FFLoad()
{
   if(NewsSource!=SRC_FOREX_FACTORY) return;
   if(ffLast!=0 && TimeLocal()-ffLast < 600) return;
   ffLast = TimeLocal();
   string url = Trim(RelayURL); url += "/?key=" + SecretKey + "&ff=1";
   char post[], res[]; string rh;
   ResetLastError();
   int code = WebRequest("GET", url, "", 8000, post, res, rh);
   if(code!=200) { if(!ffOk) Note(code==-1 ? "News: allow the relay URL under Tools > Options > Expert Advisors > WebRequest. Using MT5 calendar" : "News: Forex Factory feed unavailable (code " + (string)code + "). Using MT5 calendar"); ffLast = TimeLocal() - 540; return; }
   string txt = CharArrayToString(res, 0, WHOLE_ARRAY, CP_UTF8);
   string lines[]; int n = StringSplit(txt, '\n', lines);
   ArrayResize(ffT, 0); ArrayResize(ffC, 0); ArrayResize(ffI, 0); ArrayResize(ffN, 0);
   int k = 0;
   for(int i=0;i<n;i++)
   {
      string f[]; if(StringSplit(lines[i], ';', f) < 4) continue;
      if(f[0]=="FF") continue;
      ArrayResize(ffT, k+1); ArrayResize(ffC, k+1); ArrayResize(ffI, k+1); ArrayResize(ffN, k+1);
      ffT[k] = (datetime)StringToInteger(f[0]); ffC[k] = f[1]; ffI[k] = (int)StringToInteger(f[2]);
      ffN[k] = f[3]; for(int j=4;j<ArraySize(f);j++) ffN[k] += ";" + f[j];
      k++;
   }
   ffCount = k;
   if(k>0){ if(!ffOk) Note("Forex Factory news loaded: " + (string)k + " events this week"); ffOk = true; }
}

bool FFBlock(const string &cur[], int nc, string &why)
{
   int minImp = (NewsLevel==NEWS_RED_ONLY) ? 3 : (NewsLevel==NEWS_ORANGE_RED ? 2 : 1);
   datetime g = TimeGMT();
   for(int i=0;i<ffCount;i++)
   {
      if(ffT[i] < g - NewsAfterMin*60 || ffT[i] > g + NewsBeforeMin*60) continue;
      bool ok = false;
      for(int c=0;c<nc;c++) if(cur[c]==ffC[i]) ok = true;
      if(!ok) continue;
      if(!AlwaysMatch(ffN[i]))
      {
         if(ffI[i] < minImp) continue;
         if(ffI[i] < 3 && IgnoreMatch(ffN[i])) continue;
         if(NewsKeyOnly && !KeyMatch(ffN[i])) continue;
      }
      string col = ffI[i]==3 ? "RED" : (ffI[i]==2 ? "ORANGE" : "YELLOW");
      why = "Forex Factory " + col + " " + ffC[i] + " " + ffN[i] + " at " + TimeToString(ffT[i], TIME_DATE|TIME_MINUTES) + " GMT";
      return true;
   }
   return false;
}


// True if a qualifying event for this pair's currencies is inside the pause window.
bool NewsBlock(const string sym, string &why)
{
   if(!UseNewsFilter) return false;
   string cur[]; int nc = 0;
   string list = SymbolInfoString(sym, SYMBOL_CURRENCY_BASE) + "," + SymbolInfoString(sym, SYMBOL_CURRENCY_PROFIT) + "," + NewsExtraCcy;
   string raw[]; int rn = StringSplit(list, ',', raw);
   for(int i=0;i<rn;i++)
   {
      string c = Trim(raw[i]); StringToUpper(c);
      if(c=="") continue;
      bool dup = false;
      for(int j=0;j<nc;j++) if(cur[j]==c) dup = true;
      if(dup) continue;
      ArrayResize(cur, nc+1); cur[nc++] = c;
   }
   if(NewsSource==SRC_FOREX_FACTORY){ FFLoad(); if(ffOk) return FFBlock(cur, nc, why); }
   datetime nowS = TimeTradeServer();
   datetime from = nowS - NewsAfterMin*60 + NewsShiftMin*60, to = nowS + NewsBeforeMin*60 + NewsShiftMin*60;
   for(int c=0;c<nc;c++)
   {
      MqlCalendarValue v[];
      ResetLastError();
      int got = CalendarValueHistory(v, from, to, NULL, cur[c]);
      if(got<0)
      {
         if(!calWarned){ calWarned = true; Note("News filter: calendar not available (error " + (string)GetLastError() + ") - trading without it"); }
         continue;
      }
      for(int i=0;i<got;i++)
      {
         MqlCalendarEvent ev;
         if(!CalendarEventById(v[i].event_id, ev)) continue;
         if(ev.type==CALENDAR_TYPE_HOLIDAY) continue;
         bool force = AlwaysMatch(ev.name);   // your own must-pause words, any colour
         if(!force)
         {
            bool okImp = (ev.importance==CALENDAR_IMPORTANCE_HIGH) || (NewsLevel==NEWS_ORANGE_RED && ev.importance==CALENDAR_IMPORTANCE_MODERATE);
            if(!okImp) continue;
            if(ev.importance==CALENDAR_IMPORTANCE_MODERATE && IgnoreMatch(ev.name)) continue;   // medium speeches never pause trading
            if(NewsKeyOnly && !KeyMatch(ev.name)) continue;
         }
         why = cur[c] + " " + ev.name + " at " + TimeToString(v[i].time, TIME_MINUTES) + " (server time now " + TimeToString(nowS, TIME_MINUTES) + ", shift " + (string)NewsShiftMin + ")";
         return true;
      }
   }
   return false;
}

void Note(const string msg)
{
   lastSig = TimeToString(TimeLocal(), TIME_SECONDS) + "  " + msg;
   Print("Open Legacy All-in-One EA: ", msg);
}

// Reads "A=1, B=2" style lists. key must be upper case.
string ListGet(const string list, const string key, const string def)
{
   string parts[];
   int n = StringSplit(list, ',', parts);
   for(int i=0;i<n;i++)
   {
      string kv[];
      if(StringSplit(parts[i], '=', kv)!=2) continue;
      if(Up(Trim(kv[0]))==key) return Trim(kv[1]);
   }
   return def;
}

bool Allowed(const string tv)
{
   if(Trim(AllowedSymbols)=="") return true;
   string parts[];
   int n = StringSplit(AllowedSymbols, ',', parts);
   for(int i=0;i<n;i++) if(Up(Trim(parts[i]))==tv) return true;
   return false;
}

// TradingView name -> your broker's symbol (handles XAUUSD vs XAUUSD.s / XAUUSDm)
string Resolve(const string tv)
{
   string b = ListGet(SymbolMap, tv, tv + SymbolSuffix);
   if(SymbolSelect(b, true)) return b;
   int total = SymbolsTotal(false);
   for(int i=0;i<total;i++)
   {
      string s = SymbolName(i, false);
      if(StringFind(Up(s), tv)==0 && SymbolSelect(s, true)) return s;
   }
   return "";
}

double LotFor(const string sym, const double want)
{
   double step = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP);
   double mn   = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN);
   double mx   = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX);
   double v    = (want > 0) ? want : mn;     // no lot in the alert -> smallest allowed
   if(step>0) v = MathFloor(v/step + 1e-9)*step;
   v = MathMax(mn, MathMin(mx, v));
   return NormalizeDouble(v, 8);
}

int CountOpen()
{
   int n = 0;
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      ulong t = PositionGetTicket(i);
      if(t==0) continue;
      if(StringFind(PositionGetString(POSITION_COMMENT), "OL Layer")==0) continue;
      if(CountAllTrades || PositionGetInteger(POSITION_MAGIC)==MagicNumber) n++;
   }
   return n;
}

ulong FindOurs(const string sym, ENUM_POSITION_TYPE &type)
{
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      ulong t = PositionGetTicket(i);
      if(t==0) continue;
      if(PositionGetInteger(POSITION_MAGIC)!=MagicNumber) continue;
      if(PositionGetString(POSITION_SYMBOL)!=sym) continue;
      if(StringFind(PositionGetString(POSITION_COMMENT), "OL Layer")==0) continue;
      type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
      return t;
   }
   return 0;
}

void QRemove(const int i)
{
   int n = ArraySize(qTv);
   for(int j=i; j<n-1; j++)
   {
      qSide[j]=qSide[j+1]; qTv[j]=qTv[j+1]; qSl[j]=qSl[j+1]; qTp[j]=qTp[j+1]; qLots[j]=qLots[j+1]; qTime[j]=qTime[j+1];
   }
   ArrayResize(qSide,n-1); ArrayResize(qTv,n-1); ArrayResize(qSl,n-1); ArrayResize(qTp,n-1); ArrayResize(qLots,n-1); ArrayResize(qTime,n-1);
}

void QDropPair(const string tv)
{
   for(int i=ArraySize(qTv)-1; i>=0; i--) if(qTv[i]==tv) QRemove(i);
}

void QPush(const string side, const string tv, const double sl, const double tp, const double lots)
{
   QDropPair(tv);                       // one held signal per pair: the newest
   int n = ArraySize(qTv);
   ArrayResize(qSide,n+1); ArrayResize(qTv,n+1); ArrayResize(qSl,n+1); ArrayResize(qTp,n+1); ArrayResize(qLots,n+1); ArrayResize(qTime,n+1);
   qSide[n]=side; qTv[n]=tv; qSl[n]=sl; qTp[n]=tp; qLots[n]=lots; qTime[n]=TimeLocal();
}


// Close every trade of ours on a symbol (the first trade and its layer)
bool CloseAllOurs(const string sym)
{
   bool ok = true;
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      ulong t = PositionGetTicket(i);
      if(t==0) continue;
      if(PositionGetInteger(POSITION_MAGIC)!=MagicNumber) continue;
      if(PositionGetString(POSITION_SYMBOL)!=sym) continue;
      if(!trade.PositionClose(t)) { Note("FAILED to close " + sym + ": " + trade.ResultRetcodeDescription()); ok = false; }
   }
   return ok;
}

// News: when a pair enters its news pause window (NewsBeforeMin before the event), close our open trades on it.
// New trades stay blocked until NewsAfterMin after the event.
void CloseForNews()
{
   if(!UseNewsFilter || !CloseBeforeNews) return;
   string done[]; int nd = 0;
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      ulong t = PositionGetTicket(i);
      if(t==0) continue;
      if(PositionGetInteger(POSITION_MAGIC)!=MagicNumber) continue;
      string sym = PositionGetString(POSITION_SYMBOL);
      bool seen = false;
      for(int j=0;j<nd;j++) if(done[j]==sym) seen = true;
      if(seen) continue;
      ArrayResize(done, nd+1); done[nd++] = sym;
      string why = "";
      if(NewsBlock(sym, why))
      {
         Note("NEWS - closing " + sym + " before news: " + why);
         CloseAllOurs(sym);
      }
   }
}

// Side-Kick says "layer now": add ONE extra trade, same SL and TP as the first trade, half the lots.
void HandleLayer(const string side, const string tv)
{
   bool buy = (side=="LBUY");
   if(!UseLayering) { Note("IGNORED layer " + tv + " - layering is off"); return; }
   if(!Allowed(tv)) return;
   string sym = Resolve(tv);
   if(sym=="") { Note("IGNORED layer " + tv + " - symbol not found on this broker"); return; }
   string nwhy;
   if(NewsBlock(sym, nwhy)) { Note("SKIPPED layer " + sym + " - news pause: " + nwhy); return; }

   ulong mt = 0;
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      ulong t = PositionGetTicket(i);
      if(t==0) continue;
      if(PositionGetInteger(POSITION_MAGIC)!=MagicNumber || PositionGetString(POSITION_SYMBOL)!=sym) continue;
      if(StringFind(PositionGetString(POSITION_COMMENT), "OL Layer")==0) continue;
      if((PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)!=buy) continue;
      mt = t; break;
   }
   if(mt==0) { Note("IGNORED layer " + sym + " - no matching open trade"); return; }
   string gv = "OLWH_L_" + (string)mt;
   // Also look at the open trades themselves, so a second copy of the EA (another terminal) can never add a second layer
   bool hasLayer = false;
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      ulong t = PositionGetTicket(i);
      if(t==0) continue;
      if(PositionGetString(POSITION_COMMENT)=="OL Layer " + (string)mt) { hasLayer = true; break; }
   }
   if(hasLayer) GlobalVariableSet(gv, 1);
   if(hasLayer || GlobalVariableCheck(gv)) { Note("IGNORED layer " + sym + " - this trade already has its layer"); return; }
   PositionSelectByTicket(mt);
   double vol = PositionGetDouble(POSITION_VOLUME), sl = PositionGetDouble(POSITION_SL), tp = PositionGetDouble(POSITION_TP);
   double step = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP), mn = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN);
   double lots = vol * LayerLotPct / 100.0;
   if(step>0) lots = MathFloor(lots/step + 1e-9)*step;
   if(lots < mn) { Note("LAYER skipped " + sym + " - half lots is below the minimum lot"); GlobalVariableSet(gv, 1); return; }
   lots = MathMin(lots, SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX));
   double ask = SymbolInfoDouble(sym, SYMBOL_ASK), bid = SymbolInfoDouble(sym, SYMBOL_BID), margin = 0;
   if(!OrderCalcMargin(buy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL, sym, lots, buy ? ask : bid, margin) || margin > AccountInfoDouble(ACCOUNT_MARGIN_FREE))
   { Note("LAYER skipped " + sym + " - not enough free margin"); return; }
   string cm = "OL Layer " + (string)mt;
   bool ok = buy ? trade.Buy(lots, sym, 0, sl, tp, cm) : trade.Sell(lots, sym, 0, sl, tp, cm);
   int dg = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
   if(ok) { GlobalVariableSet(gv, 1); Note("LAYER " + (buy ? "BUY " : "SELL ") + sym + "  " + DoubleToString(lots,2) + " lots  SL " + DoubleToString(sl,dg) + "  TP " + DoubleToString(tp,dg)); }
   else   Note("LAYER FAILED " + sym + ": " + trade.ResultRetcodeDescription());
}

// Indicator says TP hit / SL hit: close that chart's trade (and its layer) right away.
// Only trades opened before the alert was sent are closed, so a newer trade is never hit by a late alert.
void HandleExit(const string sd, const string tv, const long age)
{
   if(!CloseOnAlert) return;
   string tf = "", s = sd;
   int at = StringFind(s, "@");
   if(at>0) { tf = StringSubstr(s, at+1); s = StringSubstr(s, 0, at); }
   if(!Allowed(tv)) return;
   string sym = Resolve(tv);
   if(sym=="") return;
   datetime cutoff = TimeTradeServer() - (datetime)age + 2;
   string mainCm = "Open Legacy " + tf;
   ulong mains[]; int nm = 0;
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      ulong t = PositionGetTicket(i);
      if(t==0) continue;
      if(PositionGetInteger(POSITION_MAGIC)!=MagicNumber || PositionGetString(POSITION_SYMBOL)!=sym) continue;
      string c = PositionGetString(POSITION_COMMENT);
      if(StringFind(c, "OL Layer")==0) continue;
      if(tf!="" && c!=mainCm) continue;
      if((datetime)PositionGetInteger(POSITION_TIME) > cutoff) continue;
      ArrayResize(mains, nm+1); mains[nm++] = t;
   }
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      ulong t = PositionGetTicket(i);
      if(t==0) continue;
      if(PositionGetInteger(POSITION_MAGIC)!=MagicNumber || PositionGetString(POSITION_SYMBOL)!=sym) continue;
      string c = PositionGetString(POSITION_COMMENT);
      bool hit = false;
      for(int j=0;j<nm;j++) if(t==mains[j] || c=="OL Layer " + (string)mains[j]) hit = true;
      if(!hit) continue;
      if(trade.PositionClose(t)) Note("CLOSED " + sym + " #" + (string)t + " - indicator said " + (s=="XTP" ? "TP hit" : "SL hit"));
      else Note("FAILED to close " + sym + ": " + trade.ResultRetcodeDescription());
   }
}

bool Block(const string side, const string tv, const string sym, const double sl, const double tp, const double lots, const string why, const bool fromQueue)
{
   if(!QueueSignals) { Note("IGNORED " + side + " " + sym + " - " + why); return false; }
   if(fromQueue) return true;           // already waiting, stay quiet
   QPush(side, tv, sl, tp, lots);
   Note("HELD " + side + " " + sym + " - " + why + ". Opens when a slot is free.");
   return true;
}

// Returns true while the signal is still waiting (held). open = trades currently open, kept current across a batch.
bool Handle(const string sideIn, const string tv, const double slD, const double tpD, const double lotsWanted, int &open, const bool fromQueue)
{
   string side = sideIn, sideTf = sideIn, tf = "";
   int at = StringFind(sideTf, "@");
   if(at>0) { tf = StringSubstr(sideTf, at+1); side = StringSubstr(sideTf, 0, at); }
   bool buy = (side=="BUY");
   if(!Allowed(tv)) { Note("IGNORED " + side + " " + tv + " - not in AllowedSymbols"); return false; }

   string sym = Resolve(tv);
   if(sym=="") { Note("IGNORED " + side + " " + tv + " - symbol not found on this broker (use SymbolMap)"); return false; }

   string nwhy;
   if(NewsBlock(sym, nwhy)) { Note("SKIPPED " + side + " " + sym + " - news pause: " + nwhy); return false; }

   ENUM_POSITION_TYPE pt;
   ulong t = FindOurs(sym, pt);
   if(t!=0)
   {
      bool same = ((pt==POSITION_TYPE_BUY)==buy);
      if(same) { Note("IGNORED " + side + " " + sym + " - already in that trade"); return false; }
      if(!CloseOnOpposite)
         return Block(sideTf, tv, sym, slD, tpD, lotsWanted, "opposite trade is running", fromQueue);
      if(!CloseAllOurs(sym)) return false;
      open--;
   }

   if(open >= MaxOpenTrades)
      return Block(sideTf, tv, sym, slD, tpD, lotsWanted, "max trades reached (" + (string)open + "/" + (string)MaxOpenTrades + ")", fromQueue);

   double lots = LotFor(sym, lotsWanted);
   double ask  = SymbolInfoDouble(sym, SYMBOL_ASK);
   double bid  = SymbolInfoDouble(sym, SYMBOL_BID);
   if(ask<=0 || bid<=0) { Note("IGNORED " + side + " " + sym + " - no price yet"); return false; }

   double margin = 0;
   if(!OrderCalcMargin(buy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL, sym, lots, buy ? ask : bid, margin) || margin > AccountInfoDouble(ACCOUNT_MARGIN_FREE))
      return Block(sideTf, tv, sym, slD, tpD, lotsWanted, "not enough free margin", fromQueue);

   double pnt  = SymbolInfoDouble(sym, SYMBOL_POINT);
   int    dg   = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
   double minD = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL)*pnt + (ask-bid);
   double sl = 0, tp = 0;
   // A buy closes at the bid and a sell closes at the ask, so measuring from that side
   // makes the trade move exactly the distance the indicator drew (no spread offset).
   double base = MatchChartMove ? (buy ? bid : ask) : (buy ? ask : bid);
   double mb = MapBuf(TPBufferMap, tv, sym), ms = MapBuf(SLBufferMap, tv, sym);
   double tpB = (mb!=EMPTY_VALUE) ? mb : TPBufferPoints*pnt, slB = (ms!=EMPTY_VALUE) ? ms : SLBufferPoints*pnt;
   if(slD>0) { double d = MathMax(slD + slB, minD); sl = NormalizeDouble(buy ? base-d : base+d, dg); }
   if(tpD>0) { double d = MathMax(tpD - tpB, minD); tp = NormalizeDouble(buy ? base+d : base-d, dg); }

   string ocm = (tf!="") ? "Open Legacy " + tf : "Open Legacy";
   bool ok = buy ? trade.Buy(lots, sym, 0, sl, tp, ocm) : trade.Sell(lots, sym, 0, sl, tp, ocm);
   if(ok) { open++; Note((fromQueue ? "OPENED (was waiting) " : "OPENED ") + side + " " + sym + "  " + DoubleToString(lots,2) + " lots  SL " + DoubleToString(sl,dg) + "  TP " + DoubleToString(tp,dg)); }
   else   Note("FAILED " + side + " " + sym + ": " + trade.ResultRetcodeDescription());
   return false;
}

void Poll()
{
   string url = Trim(RelayURL);
   while(StringLen(url)>0 && StringSubstr(url, StringLen(url)-1, 1)=="/") url = StringSubstr(url, 0, StringLen(url)-1);
   url += "/?key=" + SecretKey + "&since=" + (string)lastId;

   char post[], res[];
   string rh;
   ResetLastError();
   int code = WebRequest("GET", url, "", 5000, post, res, rh);
   if(code==-1)
   {
      int e = GetLastError();
      status = (e==4014) ? "Add your Relay URL in Tools > Options > Expert Advisors > Allow WebRequest"
                         : "Can't reach the relay (error " + (string)e + ")";
      return;
   }
   if(code==403) { status = "Wrong secret key"; return; }
   if(code!=200) { status = "Relay error " + (string)code; return; }
   status = "Connected";

   string body = CharArrayToString(res, 0, WHOLE_ARRAY, CP_UTF8);
   string lines[];
   int n = StringSplit(body, '\n', lines);
   int open = CountOpen();
   for(int i=0;i<n;i++)
   {
      string line = Trim(lines[i]);
      if(line=="") continue;
      string f[];
      int k = StringSplit(line, ';', f);
      if(k<2) continue;
      if(f[0]=="M")   // newest id on the relay; if it's behind ours the relay was reset
      {
         if(StringToInteger(f[1]) < lastId) { lastId = 0; GlobalVariableSet(gvName, 0); }
         continue;
      }
      if(k<6) continue;
      long   id  = StringToInteger(f[0]);
      string sd  = Up(Trim(f[1]));
      string tv  = Up(Trim(f[2]));
      double slD = StringToDouble(f[3]);
      double tpD = StringToDouble(f[4]);
      long   age = StringToInteger(f[5]);
      double lts = (k>=7) ? StringToDouble(f[6]) : 0;
      if(age > MaxSignalAge) Note("Skipped old " + NiceSide(sd) + " " + tv + " (" + (string)age + "s old)");
      else if(sd=="LBUY" || sd=="LSELL") HandleLayer(sd, tv);
      else if(StringFind(sd, "X")==0) HandleExit(sd, tv, age);
      else { QDropPair(tv); Handle(sd, tv, slD, tpD, lts, open, false); }
      lastId = id;
      GlobalVariableSet(gvName, (double)lastId);
   }
}

// Runs every cycle: hands out free slots to held signals, oldest first
void ProcessQueue()
{
   if(ArraySize(qTv)==0) return;
   int open = CountOpen();
   int i = 0;
   while(i < ArraySize(qTv))
   {
      if(TimeLocal() - qTime[i] > QueueExpiryMin*60)
      { Note("DROPPED held " + qSide[i] + " " + qTv[i] + " - no slot opened in time"); QRemove(i); continue; }
      string sd = qSide[i], tv = qTv[i];
      double sl = qSl[i], tp = qTp[i], lt = qLots[i];
      if(Handle(sd, tv, sl, tp, lt, open, true)) i++;
      else QRemove(i);
   }
}

void Panel()
{
   string pt = "";
   StringConcatenate(pt, "Open Legacy All-in-One EA\n",
           "Status: ", status, "\n",
           "Open trades: ", CountOpen(), " / ", MaxOpenTrades, "   Waiting: ", ArraySize(qTv), "\n",
           "Last signal: ", lastSig, (ShareToReceiver ? "\nCopy share: " + mStatus + "  (" + (string)ArraySize(kTk) + " trade(s), ch " + Channel + ")" : ""));
   OLComment(pt);
}


string OLBase()
{
   string u = Trim(RelayURL);
   while(StringLen(u)>0 && StringSubstr(u, StringLen(u)-1, 1)=="/") u = StringSubstr(u, 0, StringLen(u)-1);
   return u;
}

// ---- Copy Master (merged) ----
ulong    kTk[];
double   kVol[], kSl[], kTp[];
bool     mPrimed = false;
datetime mLastSnap = 0;
ulong    mNextTry = 0;
string   mStatus = "Starting...";
string   mLastEv = "none yet";


bool MSymbolOK(const string s)
{
   if(Trim(OnlySymbols)=="") return true;
   string parts[];
   int n = StringSplit(OnlySymbols, ',', parts);
   for(int i=0;i<n;i++) if(Up(Trim(parts[i]))==Up(s)) return true;
   return false;
}

int MFindKnown(const ulong t)
{
   for(int i=0;i<ArraySize(kTk);i++) if(kTk[i]==t) return i;
   return -1;
}

void MCommit(const int n, ulong &tk[], double &vol[], double &sl[], double &tp[])
{
   ArrayResize(kTk,n); ArrayResize(kVol,n); ArrayResize(kSl,n); ArrayResize(kTp,n);
   for(int i=0;i<n;i++){ kTk[i]=tk[i]; kVol[i]=vol[i]; kSl[i]=sl[i]; kTp[i]=tp[i]; }
}

bool MPost(const string body)
{
   string url = OLBase() + "/copy/push?key=" + SecretKey + "&ch=" + Channel;
   char data[], res[];
   string rh;
   StringToCharArray(body, data, 0, StringLen(body), CP_UTF8);
   ResetLastError();
   int code = WebRequest("POST", url, "Content-Type: text/plain\r\n", 5000, data, res, rh);
   if(code==-1)
   {
      int e = GetLastError();
      mStatus = (e==4014) ? "Add your Relay URL in Tools > Options > Expert Advisors > Allow WebRequest" : "Can't reach the relay (error " + (string)e + ")";
      return false;
   }
   if(code==403) { mStatus = "Wrong secret key"; return false; }
   if(code!=200) { mStatus = "Relay error " + (string)code; return false; }
   mStatus = "Connected";
   return true;
}

void MScan()
{
   if(GetTickCount64() < mNextTry) return;

   ulong  cTk[]; double cVol[], cSl[], cTp[], cOp[]; string cSym[]; int cTy[];
   int n = 0;
   for(int i=0;i<PositionsTotal();i++)
   {
      ulong t = PositionGetTicket(i);
      if(t==0) continue;
      if(OnlyMagic>=0 && PositionGetInteger(POSITION_MAGIC)!=OnlyMagic) continue;
      if(StringFind(PositionGetString(POSITION_COMMENT), "CP")==0 && PositionGetInteger(POSITION_MAGIC)==RMagic) continue;   // never re-share copied trades (stops copy loops)
      string s = PositionGetString(POSITION_SYMBOL);
      if(!MSymbolOK(s)) continue;
      ArrayResize(cTk,n+1); ArrayResize(cVol,n+1); ArrayResize(cSl,n+1); ArrayResize(cTp,n+1);
      ArrayResize(cOp,n+1); ArrayResize(cSym,n+1); ArrayResize(cTy,n+1);
      cTk[n]=t; cSym[n]=s; cTy[n]=(int)PositionGetInteger(POSITION_TYPE);
      cVol[n]=PositionGetDouble(POSITION_VOLUME); cSl[n]=PositionGetDouble(POSITION_SL);
      cTp[n]=PositionGetDouble(POSITION_TP);      cOp[n]=PositionGetDouble(POSITION_PRICE_OPEN);
      n++;
   }

   if(!mPrimed)
   {
      mPrimed = true;
      if(!ShareExisting) { MCommit(n, cTk, cVol, cSl, cTp); return; }
   }

   string body = "";
   int ev = 0;
   for(int j=0;j<n;j++)
   {
      int k = MFindKnown(cTk[j]);
      int dg = (int)SymbolInfoInteger(cSym[j], SYMBOL_DIGITS);
      string tk = (string)cTk[j];
      if(k<0)
      {
         body += "OPEN;" + tk + ";" + cSym[j] + ";" + (cTy[j]==POSITION_TYPE_BUY ? "BUY" : "SELL") + ";" + DoubleToString(cVol[j],4) + ";" +
                 DoubleToString(cSl[j],dg) + ";" + DoubleToString(cTp[j],dg) + ";" + DoubleToString(cOp[j],dg) + "\n";
         ev++;
      }
      else
      {
         if(MathAbs(cSl[j]-kSl[k])>1e-9 || MathAbs(cTp[j]-kTp[k])>1e-9)
         { body += "MODIFY;" + tk + ";" + DoubleToString(cSl[j],dg) + ";" + DoubleToString(cTp[j],dg) + ";" + DoubleToString(cOp[j],dg) + "\n"; ev++; }
         if(cVol[j] < kVol[k]-1e-9)
         { body += "REDUCE;" + tk + ";" + DoubleToString(kVol[k],4) + ";" + DoubleToString(cVol[j],4) + "\n"; ev++; }
      }
   }
   for(int k=0;k<ArraySize(kTk);k++)
   {
      bool found = false;
      for(int j=0;j<n;j++) if(cTk[j]==kTk[k]) { found = true; break; }
      if(!found) { body += "CLOSE;" + (string)kTk[k] + "\n"; ev++; }
   }

   bool snapDue = (TimeLocal() - mLastSnap >= SnapshotSeconds);
   if(ev==0 && !snapDue) return;
   if(snapDue)
   {
      string list = "";
      for(int j=0;j<n;j++) list += (j>0 ? "," : "") + (string)cTk[j];
      body += "SNAP;" + list + "\n";
   }

   if(MPost(body))
   {
      MCommit(n, cTk, cVol, cSl, cTp);
      if(snapDue) mLastSnap = TimeLocal();
      if(ev>0) mLastEv = TimeToString(TimeLocal(), TIME_DATE|TIME_SECONDS) + "  sent " + (string)ev + " update(s)";
   }
   else mNextTry = GetTickCount64() + 2000;
}


// ---- Copy Receiver (merged) ----
CTrade rTrade;
long   rLastId = 0;
bool   rNeedInit = false;
string rGv;
string rStatus = "Starting...";
string rLastEv = "none yet";

void   RNote(const string m){ rLastEv = TimeToString(TimeLocal(), TIME_DATE|TIME_SECONDS) + "  " + m; Print("Open Legacy Copy: ", m); }

string RListGet(const string list, const string key, const string def)
{
   string parts[];
   int n = StringSplit(list, ',', parts);
   for(int i=0;i<n;i++)
   {
      string kv[];
      if(StringSplit(parts[i], '=', kv)!=2) continue;
      if(Up(Trim(kv[0]))==key) return Trim(kv[1]);
   }
   return def;
}

bool RAllowed(const string msym)
{
   if(Trim(RAllowedSymbols)=="") return true;
   string parts[];
   int n = StringSplit(RAllowedSymbols, ',', parts);
   for(int i=0;i<n;i++) if(Up(Trim(parts[i]))==Up(msym)) return true;
   return false;
}

// Master symbol -> this broker's symbol (XAUUSD.s -> XAUUSD, US500 -> US500.cash, ...)
string RResolve(const string msym)
{
   string mapped = RListGet(RSymbolMap, Up(msym), "");
   if(mapped!="" && SymbolSelect(mapped, true)) return mapped;
   if(SymbolSelect(msym, true)) return msym;
   string bs = msym;
   int d = StringFind(bs, ".");
   if(d>0) bs = StringSubstr(bs, 0, d);
   if(SymbolSelect(bs + RSymbolSuffix, true)) return bs + RSymbolSuffix;
   if(SymbolSelect(bs, true)) return bs;
   int total = SymbolsTotal(false);
   for(int i=0;i<total;i++)
   {
      string s = SymbolName(i, false);
      if(StringFind(Up(s), Up(bs))==0 && SymbolSelect(s, true)) return s;
   }
   return "";
}

double RLotsFor(const string sym, const double masterVol)
{
   double v = (LotMode==LOT_FIXED) ? FixedLot : masterVol*LotMultiplier;
   if(MaxLotPerTrade>0) v = MathMin(v, MaxLotPerTrade);
   double step = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP);
   double mn   = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN);
   double mx   = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX);
   if(step>0) v = MathFloor(v/step + 1e-9)*step;
   if(v < mn) return 0;                 // too small for this broker -> skip, never round up
   return NormalizeDouble(MathMin(v, mx), 8);
}

int RCountOpen()
{
   int n = 0;
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      ulong t = PositionGetTicket(i);
      if(t!=0 && PositionGetInteger(POSITION_MAGIC)==RMagic) n++;
   }
   return n;
}

ulong RFindMirror(const ulong mt)
{
   string cm = "CP" + (string)mt;
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      ulong t = PositionGetTicket(i);
      if(t==0) continue;
      if(PositionGetInteger(POSITION_MAGIC)!=RMagic) continue;
      if(PositionGetString(POSITION_COMMENT)==cm) return t;
   }
   return 0;
}

void RCalcStops(const string sym, const bool buy, const double entry, const double mpr, const double msl, const double mtp, double &sl, double &tp)
{
   int    dg  = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
   double pnt = SymbolInfoDouble(sym, SYMBOL_POINT);
   double ask = SymbolInfoDouble(sym, SYMBOL_ASK), bid = SymbolInfoDouble(sym, SYMBOL_BID);
   double minD = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL)*pnt + (ask-bid);
   sl = 0; tp = 0;
   if(msl>0)
   {
      double r = SLTPFromEntry ? entry + (msl - mpr) : msl;
      sl = NormalizeDouble(buy ? MathMin(r, bid-minD) : MathMax(r, ask+minD), dg);
   }
   if(mtp>0)
   {
      double r = SLTPFromEntry ? entry + (mtp - mpr) : mtp;
      tp = NormalizeDouble(buy ? MathMax(r, ask+minD) : MathMin(r, bid-minD), dg);
   }
}

void RDoOpen(const ulong mt, const string msym, const string side, const double mvol, const double msl, const double mtp, const double mpr, const long age)
{
   bool buy = (side=="BUY");
   if(age > MaxOpenAgeSec) { RNote("SKIPPED " + side + " " + msym + " - opened " + (string)age + "s ago"); return; }
   if(RFindMirror(mt)!=0) return;
   if(!RAllowed(msym)) { RNote("IGNORED " + side + " " + msym + " - not in RAllowedSymbols"); return; }
   string sym = RResolve(msym);
   if(sym=="") { RNote("IGNORED " + side + " " + msym + " - symbol not found here (use RSymbolMap)"); return; }
   if(RMaxOpenTrades>0 && RCountOpen()>=RMaxOpenTrades) { RNote("IGNORED " + side + " " + sym + " - max trades reached"); return; }
   double lots = RLotsFor(sym, mvol);
   if(lots<=0) { RNote("IGNORED " + side + " " + sym + " - lot size too small for this broker"); return; }

   double ask = SymbolInfoDouble(sym, SYMBOL_ASK), bid = SymbolInfoDouble(sym, SYMBOL_BID);
   if(ask<=0 || bid<=0) { RNote("IGNORED " + side + " " + sym + " - no price yet"); return; }
   double entry = buy ? ask : bid, margin = 0;
   if(!OrderCalcMargin(buy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL, sym, lots, entry, margin) || margin > AccountInfoDouble(ACCOUNT_MARGIN_FREE))
   { RNote("IGNORED " + side + " " + sym + " - not enough free margin"); return; }

   double sl, tp;
   RCalcStops(sym, buy, entry, mpr, msl, mtp, sl, tp);
   string cm = "CP" + (string)mt;
   bool ok = buy ? rTrade.Buy(lots, sym, 0, sl, tp, cm) : rTrade.Sell(lots, sym, 0, sl, tp, cm);
   int dg = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
   if(ok) RNote("COPIED " + side + " " + sym + "  " + DoubleToString(lots,2) + " lots  SL " + DoubleToString(sl,dg) + "  TP " + DoubleToString(tp,dg));
   else   RNote("FAILED " + side + " " + sym + ": " + rTrade.ResultRetcodeDescription());
}

void RDoModify(const ulong mt, const double msl, const double mtp, const double mop)
{
   ulong t = RFindMirror(mt);
   if(t==0 || !PositionSelectByTicket(t)) return;
   string sym = PositionGetString(POSITION_SYMBOL);
   bool buy = (PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY);
   double sl, tp;
   RCalcStops(sym, buy, PositionGetDouble(POSITION_PRICE_OPEN), mop, msl, mtp, sl, tp);
   double pnt = SymbolInfoDouble(sym, SYMBOL_POINT);
   if(MathAbs(sl-PositionGetDouble(POSITION_SL))<pnt/2 && MathAbs(tp-PositionGetDouble(POSITION_TP))<pnt/2) return;
   if(rTrade.PositionModify(t, sl, tp)) RNote("UPDATED SL/TP " + sym);
   else RNote("FAILED SL/TP update " + sym + ": " + rTrade.ResultRetcodeDescription());
}

void RDoClose(const ulong mt)
{
   ulong t = RFindMirror(mt);
   if(t==0) return;
   string sym = PositionSelectByTicket(t) ? PositionGetString(POSITION_SYMBOL) : "";
   if(rTrade.PositionClose(t)) RNote("CLOSED " + sym + " (Master closed)");
   else RNote("FAILED to close " + sym + ": " + rTrade.ResultRetcodeDescription());
}

void RDoReduce(const ulong mt, const double oldv, const double newv)
{
   ulong t = RFindMirror(mt);
   if(t==0 || oldv<=0 || !PositionSelectByTicket(t)) return;
   string sym = PositionGetString(POSITION_SYMBOL);
   double cur = PositionGetDouble(POSITION_VOLUME);
   double step = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP), mn = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN);
   double cv = cur*(oldv-newv)/oldv;
   if(step>0) cv = MathFloor(cv/step + 1e-9)*step;
   if(cv < mn) return;
   bool ok = (cur-cv < mn) ? rTrade.PositionClose(t) : rTrade.PositionClosePartial(t, NormalizeDouble(cv,8));
   if(ok) RNote("PARTIAL CLOSE " + sym);
   else   RNote("FAILED partial close " + sym + ": " + rTrade.ResultRetcodeDescription());
}

// Close copies whose Master rTrade is gone (only trusts a fresh Master snapshot, and ignores copies < 30s old)
void RSweep(const string list)
{
   string ids[];
   int n = StringSplit(list, ',', ids);
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      ulong t = PositionGetTicket(i);
      if(t==0 || PositionGetInteger(POSITION_MAGIC)!=RMagic) continue;
      string cm = PositionGetString(POSITION_COMMENT);
      if(StringSubstr(cm,0,2)!="CP") continue;
      string mt = StringSubstr(cm,2);
      bool found = false;
      for(int k=0;k<n;k++) if(ids[k]==mt) { found = true; break; }
      if(found) continue;
      if(TimeCurrent() - (datetime)PositionGetInteger(POSITION_TIME) < 30) continue;
      string sym = PositionGetString(POSITION_SYMBOL);
      if(rTrade.PositionClose(t)) RNote("CLOSED " + sym + " (Master no longer has it)");
   }
}

void RPoll()
{
   string url = OLBase() + "/copy/pull?key=" + SecretKey + "&ch=" + Channel + "&since=" + (string)rLastId;
   char post[], res[];
   string rh;
   ResetLastError();
   int code = WebRequest("GET", url, "", 5000, post, res, rh);
   if(code==-1)
   {
      int e = GetLastError();
      rStatus = (e==4014) ? "Add your Relay URL in Tools > Options > Expert Advisors > Allow WebRequest" : "Can't reach the relay (error " + (string)e + ")";
      return;
   }
   if(code==403) { rStatus = "Wrong secret key"; return; }
   if(code!=200) { rStatus = "Relay error " + (string)code; return; }
   rStatus = "Connected";

   string lines[];
   int n = StringSplit(CharArrayToString(res, 0, WHOLE_ARRAY, CP_UTF8), '\n', lines);
   bool haveSnap = false; string snap = ""; long snapAge = 0;
   for(int i=0;i<n;i++)
   {
      string line = Trim(lines[i]);
      if(line=="") continue;
      string f[];
      int k = StringSplit(line, ';', f);
      if(k<2) continue;
      if(f[0]=="M")
      {
         long mx = StringToInteger(f[1]);
         if(rNeedInit) { rLastId = mx; GlobalVariableSet(rGv, (double)rLastId); rNeedInit = false; return; }  // first start: ignore history
         if(mx < rLastId) { rLastId = 0; GlobalVariableSet(rGv, 0); }
         continue;
      }
      if(f[0]=="S") { haveSnap = true; snapAge = StringToInteger(f[1]); snap = (k>=3) ? f[2] : ""; continue; }
      if(k<3) continue;
      long   id  = StringToInteger(f[0]);
      long   age = StringToInteger(f[1]);
      string ty  = f[2];
      if(ty=="OPEN" && k>=10)        RDoOpen((ulong)StringToInteger(f[3]), f[4], f[5], StringToDouble(f[6]), StringToDouble(f[7]), StringToDouble(f[8]), StringToDouble(f[9]), age);
      else if(ty=="MODIFY" && k>=7)  RDoModify((ulong)StringToInteger(f[3]), StringToDouble(f[4]), StringToDouble(f[5]), StringToDouble(f[6]));
      else if(ty=="CLOSE" && k>=4)   RDoClose((ulong)StringToInteger(f[3]));
      else if(ty=="REDUCE" && k>=6)  RDoReduce((ulong)StringToInteger(f[3]), StringToDouble(f[4]), StringToDouble(f[5]));
      rLastId = id;
      GlobalVariableSet(rGv, (double)rLastId);
   }
   if(SyncOrphans && haveSnap && snapAge<=60) RSweep(snap);
}


void RPanel()
{
   string pt = "";
   StringConcatenate(pt, "Open Legacy EA - Copy Receiver\n",
           "Status: ", rStatus, "\n",
           "Copied trades open: ", RCountOpen(), (RMaxOpenTrades>0 ? " / " + (string)RMaxOpenTrades : ""), "   Channel: ", Channel, "\n",
           "Last: ", rLastEv);
   OLComment(pt);
}

int RInit()
{
   if(StringLen(Trim(SecretKey))==0 || StringFind(RelayURL, "your-relay")>=0)
   { Alert("Open Legacy EA: fill in RelayURL and SecretKey."); return INIT_PARAMETERS_INCORRECT; }
   if(AccountInfoInteger(ACCOUNT_MARGIN_MODE)!=ACCOUNT_MARGIN_MODE_RETAIL_HEDGING)
   { Alert("Open Legacy Copy Receiver needs a hedging account."); return INIT_FAILED; }
   if(LotMode==LOT_MULTIPLIER && LotMultiplier<=0) { Alert("LotMultiplier must be above 0."); return INIT_PARAMETERS_INCORRECT; }
   if(LotMode==LOT_FIXED && FixedLot<=0)          { Alert("FixedLot must be above 0.");      return INIT_PARAMETERS_INCORRECT; }
   rTrade.SetExpertMagicNumber(RMagic);
   rTrade.SetDeviationInPoints(SlippagePoints);
   rGv = "OLCP_" + (string)AccountInfoInteger(ACCOUNT_LOGIN) + "_" + Channel;
   if(GlobalVariableCheck(rGv)) rLastId = (long)GlobalVariableGet(rGv); else { rLastId = 0; rNeedInit = true; }
   EventSetMillisecondTimer(MathMax(250, PollMs));
   RPanel();
   return INIT_SUCCEEDED;
}


// ---- info panel drawn as labels so it stays visible above the splash ----
#define OL_PNL "OLEA_P"
#define OL_PBG "OLEA_PanelBG"
int olPanelN = 0, pbW = 0, pbH = 0;

// rounded dark box behind the info text (same look as the splash card)
void OLPanelBG(const int W, const int H)
{
   uint px[];
   ArrayResize(px, W*H);
   ArrayInitialize(px, 0);
   double rad = 12.0, hx = W/2.0 - 1.0, hy = H/2.0 - 1.0;
   for(int y=0; y<H; y++)
      for(int x=0; x<W; x++)
      {
         double qx = MathAbs(x+0.5-W/2.0) - (hx-rad), qy = MathAbs(y+0.5-H/2.0) - (hy-rad);
         double ox = MathMax(qx,0.0), oy = MathMax(qy,0.0);
         double d = MathSqrt(ox*ox+oy*oy) + MathMin(MathMax(qx,qy),0.0) - rad;
         double c = SPClamp(0.5-d);
         if(c<=0) continue;
         uint fill = SPMix(0x0F1626, 0x060910, (double)y/H);
         px[y*W+x] = SPBlend(0, fill, c*0.9);
         double ring = c - SPClamp(0.5-(d+1.6));
         if(ring>0) px[y*W+x] = SPBlend(px[y*W+x], 0x2FD480, ring*0.6);
      }
   if(!ResourceCreate("olpanelbg", px, W, H, 0, 0, W, COLOR_FORMAT_ARGB_NORMALIZE)) return;
   ObjectDelete(0, OL_PBG);
   if(!ObjectCreate(0, OL_PBG, OBJ_BITMAP_LABEL, 0, 0, 0)) return;
   ObjectSetString(0, OL_PBG, OBJPROP_BMPFILE, "::olpanelbg");
   ObjectSetInteger(0, OL_PBG, OBJPROP_CORNER, CORNER_LEFT_UPPER);
   ObjectSetInteger(0, OL_PBG, OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
   ObjectSetInteger(0, OL_PBG, OBJPROP_XDISTANCE, 6);
   ObjectSetInteger(0, OL_PBG, OBJPROP_YDISTANCE, 16);
   ObjectSetInteger(0, OL_PBG, OBJPROP_BACK, false);
   ObjectSetInteger(0, OL_PBG, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, OL_PBG, OBJPROP_HIDDEN, true);
   ObjectSetInteger(0, OL_PBG, OBJPROP_ZORDER, 0);
}

void OLPanelClear()
{
   for(int i=0;i<olPanelN;i++) ObjectDelete(0, OL_PNL + (string)i);
   ObjectDelete(0, OL_PBG);
   olPanelN = 0; pbW = 0; pbH = 0;
}

void OLComment(const string txt)
{
   string raw[], ln[];
   int rn = StringSplit(txt, '\n', raw);
   if(rn<=0 || StringLen(txt)==0) { OLPanelClear(); return; }
   int n = 0;
   ArrayResize(ln, 16);
   for(int r=0; r<rn && n<14; r++)
   {
      string t = raw[r];
      while(StringLen(t)>52 && n<14)
      {
         int cut = 52;
         for(int c=52; c>20; c--) if(StringGetCharacter(t, c)==' ') { cut = c; break; }
         ln[n++] = StringSubstr(t, 0, cut);
         t = "  " + StringSubstr(t, cut);
         StringTrimRight(t);
      }
      if(n<14) ln[n++] = t;
   }
   int mx = 0;
   for(int i=0;i<n;i++) mx = MathMax(mx, StringLen(ln[i]));
   int bw = (int)(mx*9.3) + 32, bh = n*19 + 16;
   if(bw!=pbW || bh!=pbH || ObjectFind(0, OL_PBG)<0)
   {
      OLPanelClear();          // rebuild box first, then labels on top of it
      OLPanelBG(bw, bh);
      pbW = bw; pbH = bh;
   }
   for(int i=0;i<n;i++)
   {
      string nm = OL_PNL + (string)i;
      if(ObjectFind(0, nm)<0)
      {
         ObjectCreate(0, nm, OBJ_LABEL, 0, 0, 0);
         ObjectSetInteger(0, nm, OBJPROP_CORNER, CORNER_LEFT_UPPER);
         ObjectSetInteger(0, nm, OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
         ObjectSetInteger(0, nm, OBJPROP_XDISTANCE, 12);
         ObjectSetInteger(0, nm, OBJPROP_YDISTANCE, 24 + i*19);
         ObjectSetString(0, nm, OBJPROP_FONT, "Consolas");
         ObjectSetInteger(0, nm, OBJPROP_FONTSIZE, 10);
         ObjectSetInteger(0, nm, OBJPROP_COLOR, (i==0) ? 0x80D42F : 0xF5EBE0);
         ObjectSetInteger(0, nm, OBJPROP_SELECTABLE, false);
         ObjectSetInteger(0, nm, OBJPROP_HIDDEN, true);
         ObjectSetInteger(0, nm, OBJPROP_BACK, false);
         ObjectSetInteger(0, nm, OBJPROP_ZORDER, 0);
      }
      ObjectSetString(0, nm, OBJPROP_TEXT, ln[i]);
   }
   for(int i=n;i<olPanelN;i++) ObjectDelete(0, OL_PNL + (string)i);
   olPanelN = n;
}

// ================= Open Legacy splash screen (drawn in code, no image files) =================
#define OL_SPL "OLEA_Splash"
#define OL_VER "1.84"
datetime splEnd = 0;
bool     splOn  = false;

double SPClamp(const double v){ return v<0 ? 0 : (v>1 ? 1 : v); }

uint SPBlend(const uint dst, const uint col, double sa)
{
   if(sa<=0) return dst;
   if(sa>1) sa = 1;
   double da = ((dst>>24)&255)/255.0;
   double oa = sa + da*(1.0-sa);
   if(oa<=0) return dst;
   double k = da*(1.0-sa);
   uint r = (uint)((((col>>16)&255)*sa + ((dst>>16)&255)*k)/oa + 0.5);
   uint g = (uint)((((col>>8)&255)*sa  + ((dst>>8)&255)*k)/oa  + 0.5);
   uint b = (uint)(((col&255)*sa       + (dst&255)*k)/oa       + 0.5);
   uint a = (uint)(oa*255.0 + 0.5);
   return (a<<24)|(r<<16)|(g<<8)|b;
}

uint SPMix(const uint c1, const uint c2, double t)
{
   t = SPClamp(t);
   uint r = (uint)(((c1>>16)&255)*(1-t) + ((c2>>16)&255)*t + 0.5);
   uint g = (uint)(((c1>>8)&255)*(1-t)  + ((c2>>8)&255)*t  + 0.5);
   uint b = (uint)((c1&255)*(1-t)       + (c2&255)*t       + 0.5);
   return (r<<16)|(g<<8)|b;
}

// diamond (rotated square); ringW <= 0 = filled, otherwise an outline of that width
void SPDiamond(uint &px[], const int W, const int H, const double cx, const double cy, const double r, const uint col, const double alpha, const double ringW)
{
   int x0 = (int)MathMax(0, cx-r-3), x1 = (int)MathMin(W-1, cx+r+3);
   int y0 = (int)MathMax(0, cy-r-3), y1 = (int)MathMin(H-1, cy+r+3);
   for(int y=y0; y<=y1; y++)
      for(int x=x0; x<=x1; x++)
      {
         double d = MathAbs(x+0.5-cx) + MathAbs(y+0.5-cy);
         double c = SPClamp((r-d)/1.4142 + 0.5);
         if(ringW>0) c -= SPClamp((r-ringW*1.4142-d)/1.4142 + 0.5);
         if(c>0) px[y*W+x] = SPBlend(px[y*W+x], col, c*alpha);
      }
}

void SPGlow(uint &px[], const int W, const int H, const double cx, const double cy, const double r, const double reach, const uint col, const double alpha)
{
   int x0 = (int)MathMax(0, cx-r-reach-2), x1 = (int)MathMin(W-1, cx+r+reach+2);
   int y0 = (int)MathMax(0, cy-r-reach-2), y1 = (int)MathMin(H-1, cy+r+reach+2);
   for(int y=y0; y<=y1; y++)
      for(int x=x0; x<=x1; x++)
      {
         double d = MathAbs(x+0.5-cx) + MathAbs(y+0.5-cy);
         if(d<=r) continue;
         double g = 1.0 - (d-r)/reach;
         if(g>0) px[y*W+x] = SPBlend(px[y*W+x], col, g*g*alpha);
      }
}

void SPRoundCard(uint &px[], const int W, const int H)
{
   double a = MathMax(40, MathMin(100, SplashOpacity))/100.0;
   double rad = 26.0, hx = W/2.0 - 1.0, hy = H/2.0 - 1.0;
   for(int y=0; y<H; y++)
      for(int x=0; x<W; x++)
      {
         double qx = MathAbs(x+0.5-W/2.0) - (hx-rad), qy = MathAbs(y+0.5-H/2.0) - (hy-rad);
         double ox = MathMax(qx,0.0), oy = MathMax(qy,0.0);
         double d = MathSqrt(ox*ox+oy*oy) + MathMin(MathMax(qx,qy),0.0) - rad;
         double c = SPClamp(0.5-d);
         if(c<=0) continue;
         uint fill = SPMix(0x0F1626, 0x060910, (double)y/H);
         px[y*W+x] = SPBlend(0, fill, c*a);
         double ring = c - SPClamp(0.5-(d+1.8));
         if(ring>0) px[y*W+x] = SPBlend(px[y*W+x], 0x2FD480, ring*0.6);
      }
}

void SPText(uint &px[], const int W, const int H, const string txt, const int cx, const int y, const uint rgb)
{
   TextOut(txt, cx, y, TA_CENTER|TA_TOP, px, W, H, ColorToARGB((color)(((rgb&255)<<16)|(rgb&0xFF00)|((rgb>>16)&255)), 255), COLOR_FORMAT_ARGB_NORMALIZE);
}

void SplashRemove()
{
   if(!splOn) return;
   ObjectDelete(0, OL_SPL);
   ResourceFree("::olsplash");
   splOn = false; splEnd = 0;
   ChartRedraw();
}

void SplashShow()
{
   if(!ShowSplash) return;
   const int W = 540, H = 372;
   uint px[];
   ArrayResize(px, W*H);
   ArrayInitialize(px, 0);
   SPRoundCard(px, W, H);

   // logo: same diamonds as the site preload screen
   double cx = W/2.0, cy = 104.0, s = 1.35;
   SPGlow(px, W, H, cx, cy, 40*s, 28, 0x2FD480, 0.22);
   SPDiamond(px, W, H, cx, cy, 40*s, 0x2FD480, 0.92, 2.5*s);
   SPDiamond(px, W, H, cx, cy, 20*s, 0x0E1420, 1.0, 0);
   SPDiamond(px, W, H, cx, cy, 20*s, 0xF5B942, 1.0, 2.5*s);
   SPDiamond(px, W, H, cx, cy, 13*s, 0xF5B942, 0.22, 0);

   // title, white -> amber -> green like the site
   string title = "Open Legacy";
   TextSetFont("Segoe UI", 52, FW_BOLD);
   uint tw=0, th=0;
   TextGetSize(title, tw, th);
   int sx = (W - (int)tw)/2, n = StringLen(title);
   for(int i=0; i<n; i++)
   {
      uint pw=0, ph=0;
      if(i>0) TextGetSize(StringSubstr(title, 0, i), pw, ph);
      double t = (n>1) ? (double)i/(n-1) : 0;
      uint rgb = (t<0.6) ? SPMix(0xF4F7FB, 0xF5B942, t/0.6) : SPMix(0xF5B942, 0x2FD480, (t-0.6)/0.4);
      uint argb = ColorToARGB((color)(((rgb&255)<<16)|(rgb&0xFF00)|((rgb>>16)&255)), 255);
      TextOut(StringSubstr(title, i, 1), sx+(int)pw, 172, TA_LEFT|TA_TOP, px, W, H, argb, COLOR_FORMAT_ARGB_NORMALIZE);
   }

   TextSetFont("Consolas", 17, FW_NORMAL);
   SPText(px, W, H, "making trader's dreams into reality", W/2, 250, 0x9AA7BA);

   for(int x=70; x<W-70; x++) px[300*W+x] = SPBlend(px[300*W+x], 0x2FD480, 0.30);
   TextSetFont("Segoe UI", 14, FW_NORMAL);
   string role = (Role==ROLE_RECEIVER) ? "Copy Receiver" : (ShareToReceiver ? "Trader + Copy Master" : "Trader");
   SPText(px, W, H, "All-in-One EA  v" + OL_VER + "   |   " + role, W/2, 316, 0x7C8AA0);

   if(!ResourceCreate("olsplash", px, W, H, 0, 0, W, COLOR_FORMAT_ARGB_NORMALIZE)) return;
   ObjectDelete(0, OL_SPL);
   if(!ObjectCreate(0, OL_SPL, OBJ_BITMAP_LABEL, 0, 0, 0)) return;
   ObjectSetString(0, OL_SPL, OBJPROP_BMPFILE, "::olsplash");
   ObjectSetInteger(0, OL_SPL, OBJPROP_CORNER, CORNER_LEFT_UPPER);
   ObjectSetInteger(0, OL_SPL, OBJPROP_ANCHOR, ANCHOR_CENTER);
   ObjectSetInteger(0, OL_SPL, OBJPROP_XDISTANCE, (int)(ChartGetInteger(0, CHART_WIDTH_IN_PIXELS)/2));
   ObjectSetInteger(0, OL_SPL, OBJPROP_YDISTANCE, (int)(ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS)/2));
   ObjectSetInteger(0, OL_SPL, OBJPROP_BACK, false);
   ObjectSetInteger(0, OL_SPL, OBJPROP_SELECTABLE, !SplashStay);
   ObjectSetInteger(0, OL_SPL, OBJPROP_SELECTED, false);
   ObjectSetInteger(0, OL_SPL, OBJPROP_ZORDER, 100);
   splOn = true;
   splEnd = (SplashSeconds>0 && !SplashStay) ? TimeLocal() + SplashSeconds : 0;
   OLPanelClear();   // info panel labels are re-created on top of the splash
   ChartRedraw();
}

void SplashTick()
{
   if(splOn && splEnd>0 && TimeLocal()>=splEnd) SplashRemove();
}

void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
   if(!splOn) return;
   if(id==CHARTEVENT_OBJECT_CLICK && sparam==OL_SPL && !SplashStay) SplashRemove();
   else if(id==CHARTEVENT_CHART_CHANGE)
   {
      ObjectSetInteger(0, OL_SPL, OBJPROP_XDISTANCE, (int)(ChartGetInteger(0, CHART_WIDTH_IN_PIXELS)/2));
      ObjectSetInteger(0, OL_SPL, OBJPROP_YDISTANCE, (int)(ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS)/2));
   }
}

int OnInit()
{
   if(Role==ROLE_RECEIVER) { int rr = RInit(); if(rr==INIT_SUCCEEDED) { SplashShow(); RPanel(); } return rr; }
   if(ShareToReceiver && AccountInfoInteger(ACCOUNT_MARGIN_MODE)!=ACCOUNT_MARGIN_MODE_RETAIL_HEDGING) Print("Open Legacy EA: sharing by position ticket works best on hedging accounts.");
   if(StringLen(Trim(SecretKey))==0 || StringFind(RelayURL, "your-relay")>=0)
   { Alert("Open Legacy All-in-One EA: fill in RelayURL and SecretKey in the settings."); return INIT_PARAMETERS_INCORRECT; }
   if(MaxOpenTrades<1) { Alert("Open Legacy All-in-One EA: MaxOpenTrades must be 1 or more."); return INIT_PARAMETERS_INCORRECT; }
   if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED)) Print("Open Legacy Webhook: AutoTrading is OFF - turn it on to place trades.");

   trade.SetExpertMagicNumber(MagicNumber);
   trade.SetDeviationInPoints(SlippagePoints);

   gvName = "OLWH_" + (string)AccountInfoInteger(ACCOUNT_LOGIN);
   lastId = GlobalVariableCheck(gvName) ? (long)GlobalVariableGet(gvName) : 0;

   if(UseAutoSLTP && !AParse()) { Alert("Open Legacy EA: check AutoRules, e.g. XAUUSD=60/40, NAS100=1400/1000"); return INIT_PARAMETERS_INCORRECT; }
   EventSetMillisecondTimer(ShareToReceiver ? MathMax(100, ScanMs) : MathMax(1, PollSeconds)*1000);
   Panel();
   SplashShow();
   Panel();
   return INIT_SUCCEEDED;
}

void OnDeinit(const int reason){ EventKillTimer(); OLPanelClear(); Comment(""); SplashRemove(); }
void OnTimer()
{
   SplashTick();
   if(Role==ROLE_RECEIVER) { RPoll(); RPanel(); return; }
   if(ShareToReceiver) MScan();
   if(GetTickCount64() >= nextWh)
   {
      nextWh = GetTickCount64() + (ulong)MathMax(1, PollSeconds)*1000;
      FFLoad(); CloseForNews(); Poll(); ProcessQueue(); if(UseAutoSLTP) AutoApply(); Panel();
   }
}
void OnTick(){ if(Role==ROLE_TRADER && UseAutoSLTP) AutoApply(); }
void OnTradeTransaction(const MqlTradeTransaction &tr, const MqlTradeRequest &rq, const MqlTradeResult &rs){ if(Role==ROLE_TRADER && UseAutoSLTP) AutoApply(); }
