//+------------------------------------------------------------------+
//| PipJourneySync.mq5                                               |
//| Sends this account's closed trades to your PipJourney journal.   |
//| Read-only: it never places, changes or closes a trade, and it    |
//| never sends your password. Attach to any one chart.              |
//| MT5: Tools > Options > Expert Advisors > Allow WebRequest for    |
//| https://pipjourney.com                                           |
//+------------------------------------------------------------------+
#property copyright "PipJourney"
#property link      "https://pipjourney.com"
#property version   "1.00"
#property description "Sends your closed trades to pipjourney.com. Read-only: it never trades and never sends your password."

input string SyncKey     = "";      // Sync key (pipjourney.com/connect)
input int    InpDays     = 90;      // Days of trade history to send
input int    InpEveryMin = 15;      // Check for new trades every N minutes

#define PJ_URL "https://pipjourney.com/api/sync"
#define PJ_KEY "sb_publishable_DFUUYp9ZfLCp9tBVzTk6SA_Fv9dUy_7"   // public key of the PipJourney site (safe to share)

struct Pos
  {
   long     id;
   string   sym;
   int      dir;
   double   vin, pinSum, vout, poutSum, pl, sl, tp;
   datetime tin, tout;
   long     magic;
   string   comment;
  };
Pos      g_pos[];
string   g_lastSig = "";
datetime g_lastSent = 0;
bool     g_warned = false;

int OnInit()
  {
   if(StringLen(SyncKey) < 20)
     {
      Alert("PipJourneySync: paste your sync key from pipjourney.com/connect into the SyncKey input.");
      return INIT_PARAMETERS_INCORRECT;
     }
   if(MQLInfoInteger(MQL_TESTER)) { Print("PipJourneySync does nothing in the Strategy Tester."); return INIT_SUCCEEDED; }
   EventSetTimer(20);   // first send soon after start, then every InpEveryMin
   return INIT_SUCCEEDED;
  }
void OnDeinit(const int reason) { EventKillTimer(); }
void OnTick() { }
void OnTimer()
  {
   EventKillTimer();
   Sync();
   EventSetTimer(60 * MathMax(5, InpEveryMin));
  }

string Esc(string s)
  {
   StringReplace(s, "\\", "\\\\"); StringReplace(s, "\"", "\\\"");
   StringReplace(s, "\r", " "); StringReplace(s, "\n", " "); StringReplace(s, "\t", " ");
   return s;
  }
int FindPos(long id) { for(int i = ArraySize(g_pos) - 1; i >= 0; i--) if(g_pos[i].id == id) return i; return -1; }

// ---- server time -> UTC. NY-close brokers (GMT+2 / GMT+3) follow US daylight saving; others use today's offset.
long NthSunday(int y, int mon, int n)
  {
   MqlDateTime d; ZeroMemory(d); d.year = y; d.mon = mon; d.day = 1;
   datetime t = StructToTime(d); TimeToStruct(t, d);
   int first = (7 - d.day_of_week) % 7 + 1;
   d.day = first + 7 * (n - 1);
   return (long)StructToTime(d);
  }
bool UsDst(long u)
  {
   MqlDateTime d; TimeToStruct((datetime)u, d);
   return u >= NthSunday(d.year, 3, 2) + 7 * 3600 && u < NthSunday(d.year, 11, 1) + 6 * 3600;
  }
long g_off = 0;
long ToUtc(datetime srv)
  {
   long s = (long)srv;
   if(g_off == 7200 || g_off == 10800) { long u = s - 7200; return s - (UsDst(u) ? 10800 : 7200); }
   return s - g_off;
  }

void Sync()
  {
   datetime now = TimeTradeServer();
   g_off = (long)MathRound((double)(now - TimeGMT()) / 1800.0) * 1800;
   if(!HistorySelect(now - (datetime)InpDays * 86400, now + 86400)) { Print("PipJourneySync: could not read the trade history"); return; }

   ArrayResize(g_pos, 0);
   int total = HistoryDealsTotal();
   ulong lastTicket = 0;
   for(int i = 0; i < total; i++)
     {
      ulong tk = HistoryDealGetTicket(i);
      if(tk == 0) continue;
      long type = HistoryDealGetInteger(tk, DEAL_TYPE);
      if(type != DEAL_TYPE_BUY && type != DEAL_TYPE_SELL) continue;
      lastTicket = tk;
      long entry = HistoryDealGetInteger(tk, DEAL_ENTRY), id = HistoryDealGetInteger(tk, DEAL_POSITION_ID);
      double vol = HistoryDealGetDouble(tk, DEAL_VOLUME), px = HistoryDealGetDouble(tk, DEAL_PRICE);
      double money = HistoryDealGetDouble(tk, DEAL_PROFIT) + HistoryDealGetDouble(tk, DEAL_COMMISSION) + HistoryDealGetDouble(tk, DEAL_SWAP);
      datetime t = (datetime)HistoryDealGetInteger(tk, DEAL_TIME);
      int k = FindPos(id);
      if(entry == DEAL_ENTRY_IN)
        {
         if(k < 0)
           {
            k = ArraySize(g_pos); ArrayResize(g_pos, k + 1, 256);
            g_pos[k].id = id; g_pos[k].sym = HistoryDealGetString(tk, DEAL_SYMBOL);
            g_pos[k].dir = (type == DEAL_TYPE_BUY) ? 1 : -1;
            g_pos[k].vin = 0; g_pos[k].pinSum = 0; g_pos[k].vout = 0; g_pos[k].poutSum = 0; g_pos[k].pl = 0;
            g_pos[k].tin = t; g_pos[k].tout = 0;
            g_pos[k].sl = HistoryDealGetDouble(tk, DEAL_SL); g_pos[k].tp = HistoryDealGetDouble(tk, DEAL_TP);
            g_pos[k].magic = HistoryDealGetInteger(tk, DEAL_MAGIC); g_pos[k].comment = HistoryDealGetString(tk, DEAL_COMMENT);
           }
         g_pos[k].vin += vol; g_pos[k].pinSum += vol * px; g_pos[k].pl += money;
        }
      else if(k >= 0)
        { g_pos[k].vout += vol; g_pos[k].poutSum += vol * px; g_pos[k].tout = t; g_pos[k].pl += money; }
     }

   string rows = ""; int n = 0; double plSum = 0;
   for(int i = 0; i < ArraySize(g_pos); i++)
     {
      if(g_pos[i].vin <= 0 || g_pos[i].vout < g_pos[i].vin - 0.0000001) continue;   // still open
      int dg = (int)SymbolInfoInteger(g_pos[i].sym, SYMBOL_DIGITS); if(dg <= 0) dg = 5;
      rows += (n ? "," : "") + "{\"id\":" + IntegerToString(g_pos[i].id) + ",\"sym\":\"" + Esc(g_pos[i].sym) + "\",\"dir\":" + IntegerToString(g_pos[i].dir) +
              ",\"lots\":" + DoubleToString(g_pos[i].vin, 2) + ",\"tin\":" + IntegerToString(ToUtc(g_pos[i].tin)) +
              ",\"pin\":" + DoubleToString(g_pos[i].pinSum / g_pos[i].vin, dg) + ",\"tout\":" + IntegerToString(ToUtc(g_pos[i].tout)) +
              ",\"pout\":" + DoubleToString(g_pos[i].poutSum / g_pos[i].vout, dg) + ",\"sl\":" + DoubleToString(g_pos[i].sl, dg) +
              ",\"tp\":" + DoubleToString(g_pos[i].tp, dg) + ",\"pl\":" + DoubleToString(g_pos[i].pl, 2) +
              ",\"magic\":" + IntegerToString(g_pos[i].magic) + ",\"comment\":\"" + Esc(g_pos[i].comment) + "\"}";
      n++; plSum += g_pos[i].pl;
     }

   // only send when something changed, or every 6 hours to refresh the balance
   string sig = IntegerToString(n) + "|" + IntegerToString((long)lastTicket) + "|" + DoubleToString(plSum, 2);
   if(sig == g_lastSig && now - g_lastSent < 6 * 3600) return;

   string body = "{\"p_key\":\"" + Esc(SyncKey) + "\",\"p_account\":{\"login\":" + IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN)) +
                 ",\"server\":\"" + Esc(AccountInfoString(ACCOUNT_SERVER)) + "\",\"name\":\"" + Esc(AccountInfoString(ACCOUNT_COMPANY)) +
                 "\",\"currency\":\"" + Esc(AccountInfoString(ACCOUNT_CURRENCY)) + "\",\"balance\":" + DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE), 2) +
                 ",\"equity\":" + DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY), 2) + ",\"gmtOffset\":" + IntegerToString(g_off) + "},\"p_trades\":[" + rows + "]}";
   char data[], res[]; string resHead;
   StringToCharArray(body, data, 0, StringLen(body), CP_UTF8);
   string head = "Content-Type: application/json\r\napikey: " + PJ_KEY + "\r\n";
   ResetLastError();
   int code = WebRequest("POST", PJ_URL, head, 15000, data, res, resHead);
   string reply = CharArrayToString(res, 0, WHOLE_ARRAY, CP_UTF8);
   if(code == -1)
     {
      int e = GetLastError();
      if(e == 4014 && !g_warned) { Alert("PipJourneySync: allow https://pipjourney.com in Tools > Options > Expert Advisors > Allow WebRequest, then re-attach the EA."); g_warned = true; }
      else PrintFormat("PipJourneySync: could not reach pipjourney.com (error %d). Will try again.", e);
      return;
     }
   if(code >= 200 && code < 300)
     {
      g_lastSig = sig; g_lastSent = now;
      PrintFormat("PipJourneySync: sent %d trades", n);
     }
   else if(StringFind(reply, "sync key") >= 0)
     {
      if(!g_warned) { Alert("PipJourneySync: the sync key was not recognised. Copy it again from pipjourney.com/connect."); g_warned = true; }
     }
   else PrintFormat("PipJourneySync: the site answered %d: %s", code, StringSubstr(reply, 0, 200));
  }
//+------------------------------------------------------------------+
