//+------------------------------------------------------------------+
//|                                          CP_Export_History.mq5   |
//|        CP Trading Journal - ekspor riwayat trade MT5 ke CSV      |
//|                                                                  |
//|  Cara pakai:                                                     |
//|  1. Taruh file ini di: MQL5\Scripts  (File > Open Data Folder)   |
//|  2. Buka di MetaEditor lalu tekan Compile (F7)                   |
//|  3. Di MT5: Navigator > Scripts > seret CP_Export_History ke     |
//|     chart mana saja > atur jumlah hari > OK                      |
//|  4. File CSV tersimpan di MQL5\Files (nama ada di tab Experts)   |
//|  5. CP Trading Journal > Jurnal > Impor Excel / CSV > pilih file |
//+------------------------------------------------------------------+
#property copyright "CP Trading Journal"
#property version   "1.00"
#property script_show_inputs

input int    InpDays      = 90;    // Ambil riwayat berapa hari ke belakang
input string InpSymbol    = "";    // Filter simbol (kosong = semua, mis. XAUUSD)
input bool   InpNetProfit = false; // true = Profit sudah termasuk komisi & swap

struct PosRow
  {
   ulong    pos_id;
   datetime open_time;
   datetime close_time;
   string   symbol;
   int      type;        // 0 = buy, 1 = sell
   double   volume;
   double   open_price;
   double   close_price;
   double   close_volume;
   double   sl;
   double   tp;
   double   commission;
   double   swap;
   double   profit;
   string   comment;
   bool     has_entry;
   bool     has_exit;
  };

PosRow rows[];

int FindRow(const ulong pid)
  {
   for(int i = 0; i < ArraySize(rows); i++)
      if(rows[i].pos_id == pid)
         return i;
   int n = ArraySize(rows);
   ArrayResize(rows, n + 1);
   rows[n].pos_id       = pid;
   rows[n].open_time    = 0;
   rows[n].close_time   = 0;
   rows[n].symbol       = "";
   rows[n].type         = 0;
   rows[n].volume       = 0;
   rows[n].open_price   = 0;
   rows[n].close_price  = 0;
   rows[n].close_volume = 0;
   rows[n].sl           = 0;
   rows[n].tp           = 0;
   rows[n].commission   = 0;
   rows[n].swap         = 0;
   rows[n].profit       = 0;
   rows[n].comment      = "";
   rows[n].has_entry    = false;
   rows[n].has_exit     = false;
   return n;
  }

string Num(const double v, const int digits)
  {
   return DoubleToString(v, digits);
  }

string Clean(string s)
  {
   StringReplace(s, "\t", " ");
   StringReplace(s, "\r", " ");
   StringReplace(s, "\n", " ");
   return s;
  }

void OnStart()
  {
   datetime to   = TimeCurrent() + 86400;
   int      days = (InpDays < 1) ? 1 : InpDays;
   datetime from = TimeCurrent() - (datetime)days * 86400;

   if(!HistorySelect(from, to))
     {
      Print("CP Export: gagal membaca riwayat akun.");
      return;
     }

   int deals = HistoryDealsTotal();
   for(int i = 0; i < deals; i++)
     {
      ulong ticket = HistoryDealGetTicket(i);
      if(ticket == 0)
         continue;

      long dtype = HistoryDealGetInteger(ticket, DEAL_TYPE);
      if(dtype != DEAL_TYPE_BUY && dtype != DEAL_TYPE_SELL)
         continue; // lewati deposit, withdrawal, bonus, dll

      string sym = HistoryDealGetString(ticket, DEAL_SYMBOL);
      if(InpSymbol != "" && StringFind(sym, InpSymbol) < 0)
         continue;

      ulong    pid   = (ulong)HistoryDealGetInteger(ticket, DEAL_POSITION_ID);
      long     entry = HistoryDealGetInteger(ticket, DEAL_ENTRY);
      datetime t     = (datetime)HistoryDealGetInteger(ticket, DEAL_TIME);
      double   vol   = HistoryDealGetDouble(ticket, DEAL_VOLUME);
      double   price = HistoryDealGetDouble(ticket, DEAL_PRICE);

      int r = FindRow(pid);
      rows[r].symbol      = sym;
      rows[r].commission += HistoryDealGetDouble(ticket, DEAL_COMMISSION) + HistoryDealGetDouble(ticket, DEAL_FEE);
      rows[r].swap       += HistoryDealGetDouble(ticket, DEAL_SWAP);
      rows[r].profit     += HistoryDealGetDouble(ticket, DEAL_PROFIT);

      if(entry == DEAL_ENTRY_IN)
        {
         if(!rows[r].has_entry || t < rows[r].open_time)
            rows[r].open_time = t;
         // harga entry rata-rata tertimbang (kalau posisi ditambah)
         double newVol = rows[r].volume + vol;
         if(newVol > 0)
            rows[r].open_price = (rows[r].open_price * rows[r].volume + price * vol) / newVol;
         rows[r].volume    = newVol;
         rows[r].type      = (dtype == DEAL_TYPE_BUY) ? 0 : 1;
         rows[r].has_entry = true;
         string c = HistoryDealGetString(ticket, DEAL_COMMENT);
         if(c != "")
            rows[r].comment = c;
        }
      else
         if(entry == DEAL_ENTRY_OUT || entry == DEAL_ENTRY_OUT_BY || entry == DEAL_ENTRY_INOUT)
           {
            double newCv = rows[r].close_volume + vol;
            if(newCv > 0)
               rows[r].close_price = (rows[r].close_price * rows[r].close_volume + price * vol) / newCv;
            rows[r].close_volume = newCv;
            if(t > rows[r].close_time)
               rows[r].close_time = t;
            rows[r].has_exit = true;
            double dsl = HistoryDealGetDouble(ticket, DEAL_SL);
            double dtp = HistoryDealGetDouble(ticket, DEAL_TP);
            if(dsl > 0)
               rows[r].sl = dsl;
            if(dtp > 0)
               rows[r].tp = dtp;
           }
     }

   long offset = (long)(TimeLocal() - TimeTradeServer());
   offset = (long)MathRound(offset / 900.0) * 900;   // tampilkan dalam waktu PC kamu

   string fname = "CP_Journal_" + IntegerToString((long)AccountInfoInteger(ACCOUNT_LOGIN)) + "_" +
                  TimeToString(TimeLocal(), TIME_DATE) + ".csv";
   StringReplace(fname, ".", "-");
   StringReplace(fname, "-csv", ".csv");

   int fh = FileOpen(fname, FILE_WRITE | FILE_TXT | FILE_ANSI);
   if(fh == INVALID_HANDLE)
     {
      Print("CP Export: gagal membuat file ", fname, " (error ", GetLastError(), ")");
      return;
     }

   FileWriteString(fh, "Open Time\tSymbol\tType\tVolume\tEntry Price\tS/L\tT/P\tClose Time\tExit Price\tCommission\tSwap\tProfit\tComment\r\n");

   int written = 0;
   for(int i = 0; i < ArraySize(rows); i++)
     {
      if(!rows[i].has_entry || !rows[i].has_exit)
         continue; // hanya posisi yang sudah ditutup
      int digits = (int)SymbolInfoInteger(rows[i].symbol, SYMBOL_DIGITS);
      if(digits <= 0)
         digits = 5;
      double prof = rows[i].profit;
      if(InpNetProfit)
         prof += rows[i].commission + rows[i].swap;
      double comm = InpNetProfit ? 0.0 : rows[i].commission;
      double swp  = InpNetProfit ? 0.0 : rows[i].swap;

      string line = TimeToString(rows[i].open_time + (datetime)offset, TIME_DATE | TIME_MINUTES) + "\t" +
                    rows[i].symbol + "\t" +
                    (rows[i].type == 0 ? "buy" : "sell") + "\t" +
                    Num(rows[i].volume, 2) + "\t" +
                    Num(rows[i].open_price, digits) + "\t" +
                    Num(rows[i].sl, digits) + "\t" +
                    Num(rows[i].tp, digits) + "\t" +
                    TimeToString(rows[i].close_time + (datetime)offset, TIME_DATE | TIME_MINUTES) + "\t" +
                    Num(rows[i].close_price, digits) + "\t" +
                    Num(comm, 2) + "\t" +
                    Num(swp, 2) + "\t" +
                    Num(prof, 2) + "\t" +
                    Clean(rows[i].comment) + "\r\n";
      FileWriteString(fh, line);
      written++;
     }
   FileClose(fh);

   string path = TerminalInfoString(TERMINAL_DATA_PATH) + "\\MQL5\\Files\\" + fname;
   Print("CP Export: ", written, " trade diekspor ke ", path);
   Alert("CP Trading Journal: ", written, " trade diekspor.\nFile: MQL5\\Files\\", fname,
         "\nBuka CP Trading Journal > Jurnal > Impor Excel / CSV, lalu pilih file ini.");
  }
//+------------------------------------------------------------------+
