//+------------------------------------------------------------------+
//| Open Legacy Auto SL/TP                                           |
//| Adds your fixed SL and TP to every new trade — including trades  |
//| opened from the MT5 phone app. Run it on one chart in MT5 on a   |
//| VPS or a computer that stays on.                                 |
//+------------------------------------------------------------------+
#property copyright "Open Legacy"
#property version   "1.00"
#include <Trade\Trade.mqh>

input string Rules            = "XAUUSD=60/40, NAS100=1400/1000"; // Pair=SL/TP in pips, comma separated
input int    PointsPerPip     = 10;    // 10 for gold, indices, BTC and 5-decimal FX
input bool   ManualTradesOnly = true;  // Only touch trades you open yourself (app/manual)

CTrade trade;
string rSym[];
double rSl[];
double rTp[];
ulong  doneT[];
ulong  tryT[];
int    tryN[];

bool IsDone(ulong t){ for(int i=0;i<ArraySize(doneT);i++) if(doneT[i]==t) return true; return false; }
void MarkDone(ulong t){ int n=ArraySize(doneT); ArrayResize(doneT,n+1); doneT[n]=t; }
int  Tries(ulong t){ for(int i=0;i<ArraySize(tryT);i++) if(tryT[i]==t) return ++tryN[i]; int n=ArraySize(tryT); ArrayResize(tryT,n+1); ArrayResize(tryN,n+1); tryT[n]=t; tryN[n]=1; return 1; }

bool ParseRules()
{
   ArrayResize(rSym,0); ArrayResize(rSl,0); ArrayResize(rTp,0);
   string parts[];
   int n = StringSplit(Rules, ',', 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(rSym);
      ArrayResize(rSym,k+1); ArrayResize(rSl,k+1); ArrayResize(rTp,k+1);
      rSym[k] = key; rSl[k] = StringToDouble(v[0]); rTp[k] = StringToDouble(v[1]);
   }
   return ArraySize(rSym) > 0;
}

// Matches "XAUUSD" to XAUUSD, XAUUSD.s, XAUUSDm etc.
int FindRule(string sym)
{
   string s = sym; StringToUpper(s);
   for(int i=0;i<ArraySize(rSym);i++) if(StringFind(s, rSym[i])==0) return i;
   return -1;
}

void Apply()
{
   for(int i=PositionsTotal()-1;i>=0;i--)
   {
      ulong t = PositionGetTicket(i);
      if(t==0 || IsDone(t)) continue;
      if(ManualTradesOnly && PositionGetInteger(POSITION_MAGIC)!=0) { MarkDone(t); continue; }
      string sym = PositionGetString(POSITION_SYMBOL);
      int r = FindRule(sym);
      if(r<0) { MarkDone(t); continue; }
      double curSl = PositionGetDouble(POSITION_SL), curTp = PositionGetDouble(POSITION_TP);
      if(curSl!=0.0 && curTp!=0.0) { MarkDone(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   = rSl[r] * PointsPerPip * pt;
      double dTp   = rTp[r] * PointsPerPip * pt;
      double sl    = curSl!=0.0 ? curSl : (rSl[r]>0 ? (buy ? open-dSl : open+dSl) : 0.0);
      double tp    = curTp!=0.0 ? curTp : (rTp[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))
      {
         MarkDone(t);
         PrintFormat("Open Legacy Auto SL/TP: %s #%I64u  SL %s  TP %s", sym, t, DoubleToString(sl,dg), DoubleToString(tp,dg));
      }
      else if(Tries(t)>=10)
      {
         MarkDone(t);
         PrintFormat("Open Legacy Auto SL/TP: gave up on #%I64u (%s): %s", t, sym, trade.ResultRetcodeDescription());
      }
   }
}

int OnInit()
{
   if(!ParseRules()) { Alert("Open Legacy Auto SL/TP: check the Rules setting, e.g. XAUUSD=60/40, NAS100=1400/1000"); return INIT_PARAMETERS_INCORRECT; }
   string txt = "Open Legacy Auto SL/TP  ✅ running\n";
   for(int i=0;i<ArraySize(rSym);i++) txt += StringFormat("%s   SL %.1f  /  TP %.1f pips\n", rSym[i], rSl[i], rTp[i]);
   Comment(txt);
   EventSetMillisecondTimer(500);
   Apply();
   return INIT_SUCCEEDED;
}
void OnDeinit(const int reason){ EventKillTimer(); Comment(""); }
void OnTimer(){ Apply(); }
void OnTick(){ Apply(); }
void OnTradeTransaction(const MqlTradeTransaction &tr, const MqlTradeRequest &rq, const MqlTradeResult &rs){ Apply(); }
