preview
Practical MQL5 Utilities (Part 1): Trade Journal Analytics Panel

Practical MQL5 Utilities (Part 1): Trade Journal Analytics Panel

MetaTrader 5 — Trading systems |
63 0
Syed Jawad Hussain Naqvi
Syed Jawad Hussain Naqvi

Introduction

The History tab in MetaTrader 5 lists every deal on the account, but it does not answer the questions a trader asks after a month of trading. Which hours produce the losses? How far does the account fall from its best point before it recovers? Is the average trade worth taking? Answering these questions by hand means exporting the history and building a spreadsheet, which most traders do not do regularly. A small tool that reads the history and shows these numbers on the chart removes that step.

In practice, a journal built from account history comes with three specific challenges:

  1. A position can be opened by one deal and closed by several deals, and commissions and swaps can appear on any of them. Counting deals as trades gives wrong results.
  2. Drawdown and streaks depend on the order in which trades are closed. The history is sorted by deal time, but a position is finished only when its last exit deal arrives, so the closed trades must be ordered again.
  3. The panel must stay current as new deals arrive, without scanning the whole history on every tick.

This article works through all three. It groups deals by position identifier and adds the monetary fields of each buy and sell deal to one net value per position. It sorts the closed positions by closing time before calculating drawdown and streaks. It refreshes the panel on a timer and after each new deal. It never calls trading functions, so the tool cannot place or close an order.


What the Tool Shows

Attach the TradeJournal Expert Advisor to any chart and leave it running. The panel appears in the top-left corner of the chart and refreshes every 60 seconds by default, or immediately after a new deal. The title bar is dark blue, and the net result and expectancy are shown in green when positive and red when negative. The first lines show the scope, which is the chart symbol by default, and the magic number filter. The next lines show the closed-position count, the win rate, the net result, and the gross profit and loss that make up that result.

The profit factor is the gross profit divided by the gross loss. A value above 1.0 means the closed positions made more money than they lost. The expectancy is the net result divided by the number of closed positions, which gives the average money made per trade after costs. The maximum drawdown is the largest fall of the cumulative closed-trade result from an earlier peak. It does not include floating profit or loss on open positions.

The lower part of the panel shows the best and worst entry hour and weekday, using server time. These lines help to spot a pattern, but a pattern in a small sample is not proof of an edge. A bucket with only a few trades can look strong or weak by chance, so the position count is printed next to each hour

Input Default Purpose
InpMagicFilter -1 Counts only positions whose entry deal has this magic number. -1 counts all
InpCurrentSymbolOnly true Counts only the chart symbol. False counts every symbol
InpFromDate 0 Start of the journal. 0 uses the full available history
InpRefreshSeconds 60 Timer interval for refreshing the panel, minimum 5
InpPanelX, InpPanelY 10, 20 Panel position from the top-left corner of the chart
InpFontSize 9 Panel font size, between 6 and 20
InpExportCSV true Writes the closed positions to TradeJournal_trades.csv

Table 1. Inputs of the TradeJournal Expert Advisor.

Figure 1. Trade Journal panel showing the closed-position statistics on a demo account.


Concepts Behind the Tool

Idea 1: From Deals to Positions

MetaTrader 5 records every buy and sell as a deal. A deal has an entry type. DEAL_ENTRY_IN opens exposure, DEAL_ENTRY_OUT closes exposure, and DEAL_ENTRY_OUT_BY closes a position with an opposite one. All deals of the same position share a DEAL_POSITION_ID. A trader thinks in positions, so the journal groups deals by this identifier first.

The money result of a position is the sum of the profit, commission, swap, and fee of every buy and sell deal that belongs to it. Commission is often charged on the entry deal, so the entry deal must be included. Other history entries, such as broker charges that are not buy or sell deals, are not added.

Position net = sum over its buy and sell deals of (DEAL_PROFIT + DEAL_COMMISSION + DEAL_SWAP + DEAL_FEE)
Closed when = an entry deal exists, at least one DEAL_ENTRY_OUT or DEAL_ENTRY_OUT_BY deal exists, and the absolute value of the open volume is zero
Open volume = sum of DEAL_VOLUME over entry deals minus sum of DEAL_VOLUME over exit deals
Direction = +1 if the entry deal is DEAL_TYPE_BUY, -1 if it is DEAL_TYPE_SELL

Only positions with a known entry, at least one exit, and no open volume are counted as closed. A position that is still open or partly closed has a net value that changes with the market, so it stays out of the statistics until its last exit deal. Balance, credit, and other non-trading deals have no position identifier and are skipped.

A position whose entry deal lies before the selected history start has no known direction and no known opening time. Such positions are excluded from the journal, because their net would be incomplete. They are not counted in the closed count, the money totals, or the statistics.

Idea 2: Closed-Position Statistics

Once the closed positions are known, the statistics follow from a few formulas. The gross profit is the sum of the nets of winning positions, and the gross loss is the sum of the absolute nets of losing positions. A position with a net of exactly zero counts as a loss, because it did not add to the account.

Profit factor = Gross profit / Gross loss (N/A when there are no losses)
Expectancy     = Net result / Number of closed positions
Average win    = Gross profit / Number of wins
Average loss   = Gross loss / Number of losses
Max drawdown   = largest value of (running peak - cumulative net), in closing order

The profit factor and expectancy summarize the whole sample in one number each. The average win and average loss show the size of a typical trade on each side, which matters because a high win rate with small wins and large losses can still have a negative expectancy. The streaks are counted in closing order, so they show how long a run of good or bad results lasted.

The holding time is the difference between the closing time and the opening time of a position, averaged over the positions where both are known, and it is shown in minutes.

Idea 3: Breakdown by Hour and Weekday

Each closed position with a known entry time is placed in one hour bucket and one weekday bucket, using the server time of the entry deal. Each bucket stores the sum of the nets and the number of positions. The panel reports the bucket with the highest net and the bucket with the lowest net, among buckets that contain at least one position.

The breakdown is descriptive. It shows where the money came from in the past, and it does not prove that the same hour will behave the same way in the future. A single good hour with three trades carries much less information than the same result over one hundred trades, Therefore, the position count is shown beside each hour.


Setup

The tool needs a standard MetaTrader 5 installation. Save TradeJournal.mq5 in the MQL5 Experts folder, compile it in MetaEditor, and attach it to any chart. The EA does not place orders, so it can run on a demo or a live account. The CSV file is written to the MQL5 Files folder of the terminal data directory, under the name set by TJ_CSV_FILE.

The journal depends on the account history that the broker keeps. Some brokers keep a limited history, so the statistics may cover a shorter period than expected. InpFromDate sets the start of the journal, and the panel shows the period that was actually read. No include files are needed.


Code Walkthrough

The code is explained in the order it appears in the file. Each block is followed by a description of what the code does, what it receives, and what it returns.

Inputs, Structures, and Global State

//--- input parameters
input long     InpMagicFilter       = -1;     // Magic number of the entry deal, -1 means all magic numbers
input bool     InpCurrentSymbolOnly = true;   // Count only the symbol of the chart the EA is attached to
input datetime InpFromDate          = 0;      // Start of the journal, 0 means full available history
input int      InpRefreshSeconds    = 60;     // Timer refresh interval in seconds
input int      InpPanelX            = 10;     // Panel distance from the left edge
input int      InpPanelY            = 20;     // Panel distance from the top edge
input int      InpFontSize          = 9;      // Panel font size
input bool     InpExportCSV         = true;   // Write the closed-trade list to a CSV file

//--- constants
#define TJ_PREFIX    "TJ_"
#define TJ_CSV_FILE  "TradeJournal_trades.csv"
#define TJ_LINES     20
#define TJ_VOLUME_EPS 0.0000001

//--- one record per position, built from all of its deals
struct SPosRec
  {
   ulong    pos_id;        // position identifier shared by its entry and exit deals
   string   symbol;        // symbol of the position
   int      dir;           // +1 long, -1 short, 0 when no entry deal was found
   double   net;           // profit plus commission, swap and fee over all deals of the position
   double   open_volume;   // volume still open: entry volume minus exit volume read so far
   datetime open_time;     // time of the entry deal, 0 when unknown
   datetime close_time;    // time of the last exit deal
   bool     has_entry;     // true when an entry deal was found
   bool     has_exit;      // true when at least one exit deal was found
   long     magic;         // magic number of the entry deal, used by the magic filter
  };

//--- summary statistics of the closed positions
struct SStats
  {
   int    trades;              // number of closed positions
   int    wins;                // positions with net above zero
   int    losses;              // positions with net zero or below
   int    longs;               // closed long positions with a known entry
   int    shorts;              // closed short positions with a known entry
   int    long_wins;           // winning long positions
   int    short_wins;          // winning short positions
   double gross_profit;        // sum of positive nets
   double gross_loss;          // sum of absolute negative nets, stored as a positive value
   double net;                 // sum of all nets
   double max_drawdown;        // largest peak-to-trough fall of the cumulative net, positive value
   double avg_win;             // gross profit divided by number of wins
   double avg_loss;            // gross loss divided by number of losses, positive value
   double expectancy;          // average net per closed position
   int    max_win_streak;      // longest run of consecutive winners
   int    max_loss_streak;     // longest run of consecutive losers
   double avg_duration_min;    // average holding time in minutes
  };

//--- global state
SStats   g_stats;
SPosRec  g_closed[];
int      g_closed_count = 0;
double   g_hour_net[24];
int      g_hour_count[24];
double   g_day_net[7];
int      g_day_count[7];
string   g_status = "starting";

The inputs control the filters, the refresh rate, the panel layout, and the CSV output. SPosRec holds one position built from its deals, and SStats holds the summary of the closed positions. The global variables keep the last statistics and the hour and weekday buckets, so the panel can be redrawn without rebuilding the data.

DayName

//+------------------------------------------------------------------+
//| Returns the name of a weekday, index 0 is Sunday                 |
//+------------------------------------------------------------------+
string DayName(const int index)
  {
   string names[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
   if(index < 0 || index > 6)
     {
      return("?");
     }
   return(names[index]);
  }

DayName converts a weekday index into a three-letter label. It receives an integer from 0 to 6, where 0 is Sunday, and returns the label. Any other value returns a question mark, so an unexpected index does not break the panel.

PctText

//+------------------------------------------------------------------+
//| Formats a value in the 0 to 1 range as a percentage string       |
//+------------------------------------------------------------------+
string PctText(const double value)
  {
   return(DoubleToString(value * 100.0, 2) + "%");
  }

PctText formats a value between 0 and 1 as a percentage with two decimal places. It receives a fraction and returns text such as 48.31%. The win rates use this function, so the format is the same everywhere in the panel.

DealPasses

//+------------------------------------------------------------------+
//| Returns true when a history deal passes the symbol filter        |
//| set in the inputs                                                |
//+------------------------------------------------------------------+
bool DealPasses(const ulong ticket)
  {
//--- symbol filter, the chart symbol or every symbol
   if(InpCurrentSymbolOnly)
     {
      if(HistoryDealGetString(ticket, DEAL_SYMBOL) != _Symbol)
        {
         return(false);
        }
     }
   return(true);
  }

DealPasses decides whether a history deal belongs to the journal. It receives a deal ticket and returns true when the symbol matches the chart, if the symbol filter is on. The magic filter is not applied here, because it applies to the whole position, as described for CollectClosed. The check reads the history deal properties directly.

FindOrAddPos

//+------------------------------------------------------------------+
//| Finds the record of a position, or adds an empty one             |
//| Returns the index of the record, or -1 when the array cannot grow|
//+------------------------------------------------------------------+
int FindOrAddPos(SPosRec &recs[], int &count, const ulong pos_id, const string symbol)
  {
//--- linear search, simple to read, its cost grows with the number of positions
   for(int i = 0; i < count; i++)
     {
      if(recs[i].pos_id == pos_id)
        {
         return(i);
        }
     }
   if(ArrayResize(recs, count + 1) < 0)
     {
      Print("ArrayResize failed while adding a position, error ", GetLastError());
      return(-1);
     }
   recs[count].pos_id = pos_id;
   recs[count].symbol = symbol;
   recs[count].dir = 0;
   recs[count].net = 0.0;
   recs[count].open_volume = 0.0;
   recs[count].open_time = 0;
   recs[count].close_time = 0;
   recs[count].has_entry = false;
   recs[count].has_exit = false;
   recs[count].magic = 0;
   count++;
   return(count - 1);
  }

FindOrAddPos returns the index of the record for a position, and adds an empty record when the position is new. It receives the record array, its count, the position identifier, and the symbol. It returns the index, or -1 when the array cannot grow. The search is linear, which keeps the code simple, and its cost grows with the number of positions.

BuildRecords

//+------------------------------------------------------------------+
//| Reads the account history and groups its trading deals by        |
//| position. Returns false when the history cannot be read          |
//+------------------------------------------------------------------+
bool BuildRecords(SPosRec &recs[], int &count)
  {
   count = 0;
   ArrayFree(recs);
//--- select the history up to a day ahead of the server time, so that no deal is missed
   datetime to_time = TimeCurrent() + 86400;
   if(!HistorySelect(InpFromDate, to_time))
     {
      Print("HistorySelect failed, error ", GetLastError());
      return(false);
     }
   int total = HistoryDealsTotal();
   for(int i = 0; i < total; i++)
     {
      ulong ticket = HistoryDealGetTicket(i);
      if(ticket == 0)
        {
         Print("HistoryDealGetTicket failed at index ", i, ", error ", GetLastError());
         return(false);
        }
      //--- only buy and sell deals belong to trades, balance and credit deals are skipped
      long deal_type = HistoryDealGetInteger(ticket, DEAL_TYPE);
      if(deal_type != DEAL_TYPE_BUY && deal_type != DEAL_TYPE_SELL)
        {
         continue;
        }
      //--- deals without a position identifier are not part of a position
      ulong pos_id = (ulong)HistoryDealGetInteger(ticket, DEAL_POSITION_ID);
      if(pos_id == 0)
        {
         continue;
        }
      if(!DealPasses(ticket))
        {
         continue;
        }
      string symbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
      int idx = FindOrAddPos(recs, count, pos_id, symbol);
      if(idx < 0)
        {
         return(false);
        }
      //--- every deal of the position adds its money result, entry commission included
      recs[idx].net += HistoryDealGetDouble(ticket, DEAL_PROFIT)
                     + HistoryDealGetDouble(ticket, DEAL_COMMISSION)
                     + HistoryDealGetDouble(ticket, DEAL_SWAP)
                     + HistoryDealGetDouble(ticket, DEAL_FEE);
      long entry = HistoryDealGetInteger(ticket, DEAL_ENTRY);
      datetime deal_time = (datetime)HistoryDealGetInteger(ticket, DEAL_TIME);
      if(entry == DEAL_ENTRY_IN)
        {
         //--- the entry deal gives the direction, the opening time and the magic number of the position
         if(!recs[idx].has_entry)
           {
            recs[idx].magic = HistoryDealGetInteger(ticket, DEAL_MAGIC);
           }
         recs[idx].has_entry = true;
         recs[idx].dir = (deal_type == DEAL_TYPE_BUY) ? 1 : -1;
         //--- entry volume opens the position, so the open volume grows
         recs[idx].open_volume += HistoryDealGetDouble(ticket, DEAL_VOLUME);
         if(recs[idx].open_time == 0 || deal_time < recs[idx].open_time)
           {
            recs[idx].open_time = deal_time;
           }
        }
      else
        {
         //--- exit deals, including closing by an opposite position
         if(entry == DEAL_ENTRY_OUT || entry == DEAL_ENTRY_OUT_BY)
           {
            recs[idx].has_exit = true;
            //--- an exit removes its volume, a partial exit leaves the rest open
            recs[idx].open_volume -= HistoryDealGetDouble(ticket, DEAL_VOLUME);
            if(deal_time > recs[idx].close_time)
              {
               recs[idx].close_time = deal_time;
              }
           }
        }
     }
   return(true);
  }

BuildRecords reads the history and fills the record array. It receives the array and a count by reference, and returns false when the history cannot be selected or a deal cannot be read. It selects the history up to a day ahead of the server time, so the newest deals are included even when the server clock is slightly behind. It then loops over every deal, keeps only buy and sell deals with a position identifier that pass the filters, and adds each deal's money result to its position. An entry deal sets the direction and the opening time, and an exit deal sets the closing time.

CollectClosed

//+------------------------------------------------------------------+
//| Copies the positions that have an exit into the closed array and |
//| sorts them by closing time. Returns the number of closed         |
//| positions, or -1 on failure                                      |
//+------------------------------------------------------------------+
int CollectClosed(const SPosRec &recs[], const int count, SPosRec &closed[])
  {
   int n = 0;
   ArrayFree(closed);
   for(int i = 0; i < count; i++)
     {
      //--- a position counts as closed only with a known entry, at least one exit and no volume left open
      //--- positions opened before InpFromDate have no entry deal here, so their net would be incomplete
      //--- a negative open volume means the exits exceed the entries, so the history is not consistent
      if(!recs[i].has_entry || !recs[i].has_exit || MathAbs(recs[i].open_volume) > TJ_VOLUME_EPS)
        {
         continue;
        }
      //--- the magic filter applies to the whole position, through the magic number of its entry deal
      if(InpMagicFilter >= 0 && recs[i].magic != InpMagicFilter)
        {
         continue;
        }
      if(ArrayResize(closed, n + 1) < 0)
        {
         Print("ArrayResize failed while collecting closed positions, error ", GetLastError());
         return(-1);
        }
      closed[n] = recs[i];
      n++;
     }
//--- selection sort by closing time, so that the drawdown follows the real sequence
   for(int a = 0; a < n - 1; a++)
     {
      int best = a;
      for(int b = a + 1; b < n; b++)
        {
         if(closed[b].close_time < closed[best].close_time)
           {
            best = b;
           }
        }
      if(best != a)
        {
         SPosRec tmp = closed[a];
         closed[a] = closed[best];
         closed[best] = tmp;
        }
     }
   return(n);
  }

CollectClosed copies the fully closed positions that pass the magic filter into a second array and sorts that array by closing time. It receives the record array, its count, and the closed array by reference. It returns the number of closed positions, or -1 when memory cannot be allocated. The sort is a selection sort, which is simple to read. Its cost grows with the square of the number of closed positions, so very large histories take longer to process.

ComputeStats

//+------------------------------------------------------------------+
//| Computes the summary statistics of the sorted closed positions   |
//+------------------------------------------------------------------+
void ComputeStats(const SPosRec &closed[], const int n, SStats &s)
  {
//--- reset every field before the new calculation
   s.trades = n;
   s.wins = 0;
   s.losses = 0;
   s.longs = 0;
   s.shorts = 0;
   s.long_wins = 0;
   s.short_wins = 0;
   s.gross_profit = 0.0;
   s.gross_loss = 0.0;
   s.net = 0.0;
   s.max_drawdown = 0.0;
   s.avg_win = 0.0;
   s.avg_loss = 0.0;
   s.expectancy = 0.0;
   s.max_win_streak = 0;
   s.max_loss_streak = 0;
   s.avg_duration_min = 0.0;

   double cumulative = 0.0;
   double peak = 0.0;
   int win_run = 0;
   int loss_run = 0;
   double duration_sum = 0.0;
   int duration_count = 0;

   for(int i = 0; i < n; i++)
     {
      const SPosRec r = closed[i];
      s.net += r.net;
      cumulative += r.net;
      //--- drawdown is the distance from the highest cumulative value reached so far
      if(cumulative > peak)
        {
         peak = cumulative;
        }
      if(peak - cumulative > s.max_drawdown)
        {
         s.max_drawdown = peak - cumulative;
        }
      //--- direction counts use only positions whose entry is known
      if(r.dir > 0)
        {
         s.longs++;
        }
      else
        {
         if(r.dir < 0)
           {
            s.shorts++;
           }
        }
      if(r.net > 0.0)
        {
         s.wins++;
         s.gross_profit += r.net;
         win_run++;
         loss_run = 0;
         if(r.dir > 0)
           {
            s.long_wins++;
           }
         else
           {
            if(r.dir < 0)
              {
               s.short_wins++;
              }
           }
         if(win_run > s.max_win_streak)
           {
            s.max_win_streak = win_run;
           }
        }
      else
        {
         s.losses++;
         s.gross_loss += -r.net;
         loss_run++;
         win_run = 0;
         if(loss_run > s.max_loss_streak)
           {
            s.max_loss_streak = loss_run;
           }
        }
      //--- holding time needs both the entry and the exit
      if(r.has_entry && r.open_time > 0 && r.close_time >= r.open_time)
        {
         duration_sum += (double)(r.close_time - r.open_time) / 60.0;
         duration_count++;
        }
     }

   if(s.wins > 0)
     {
      s.avg_win = s.gross_profit / s.wins;
     }
   if(s.losses > 0)
     {
      s.avg_loss = s.gross_loss / s.losses;
     }
   if(n > 0)
     {
      s.expectancy = s.net / n;
     }
   if(duration_count > 0)
     {
      s.avg_duration_min = duration_sum / duration_count;
     }
  }

ComputeStats fills the SStats structure from the sorted closed positions. It receives the closed array, the count, and the structure by reference. It resets every field first, so a second call starts from zero. It walks the positions once, accumulating totals, tracking the running peak for the drawdown, counting the streaks, and summing the holding times. The averages and the expectancy are computed at the end, with guards against division by zero.

ComputeBuckets

//+------------------------------------------------------------------+
//| Fills the hour and weekday buckets from the entry time of each   |
//| closed position, using server time                               |
//+------------------------------------------------------------------+
void ComputeBuckets(const SPosRec &closed[], const int n)
  {
   ArrayInitialize(g_hour_net, 0.0);
   ArrayInitialize(g_hour_count, 0);
   ArrayInitialize(g_day_net, 0.0);
   ArrayInitialize(g_day_count, 0);
   for(int i = 0; i < n; i++)
     {
      const SPosRec r = closed[i];
      //--- positions with an unknown entry time have no hour or weekday
      if(!r.has_entry || r.open_time == 0)
        {
         continue;
        }
      MqlDateTime dt;
      if(!TimeToStruct(r.open_time, dt))
        {
         Print("TimeToStruct failed, error ", GetLastError());
         continue;
        }
      g_hour_net[dt.hour] += r.net;
      g_hour_count[dt.hour]++;
      g_day_net[dt.day_of_week] += r.net;
      g_day_count[dt.day_of_week]++;
     }
  }

ComputeBuckets fills the hour and weekday buckets. It receives the closed array and its count. It clears the buckets, then places each position with a known entry time into one hour bucket and one weekday bucket. If a time conversion fails, the error is printed and that position is skipped, so the other buckets stay correct.

BestAndWorst

//+------------------------------------------------------------------+
//| Finds the bucket with the highest and the lowest net among the   |
//| buckets that have at least one trade. Returns false when empty   |
//+------------------------------------------------------------------+
bool BestAndWorst(const double &net[], const int &cnt[], const int size, int &best, int &worst)
  {
   best = -1;
   worst = -1;
   for(int i = 0; i < size; i++)
     {
      if(cnt[i] <= 0)
        {
         continue;
        }
      if(best < 0 || net[i] > net[best])
        {
         best = i;
        }
      if(worst < 0 || net[i] < net[worst])
        {
         worst = i;
        }
     }
   return(best >= 0);
  }

BestAndWorst finds the bucket with the highest and the lowest net among buckets that contain trades. It receives the net array, the count array, the size, and two indices by reference. It returns true when at least one bucket has a trade. Empty buckets are ignored, so an hour without trades can never be reported as the worst.

ExportCSV

//+------------------------------------------------------------------+
//| Writes the closed positions to the CSV file in the terminal      |
//| Files folder. Returns false when the file cannot be written      |
//+------------------------------------------------------------------+
bool ExportCSV(const SPosRec &closed[], const int n)
  {
   int handle = FileOpen(TJ_CSV_FILE, FILE_WRITE | FILE_TXT | FILE_ANSI);
   if(handle == INVALID_HANDLE)
     {
      Print("FileOpen failed for ", TJ_CSV_FILE, ", error ", GetLastError());
      return(false);
     }
   string header = "position_id;symbol;direction;open_time;close_time;net;duration_min\r\n";
   if(FileWriteString(handle, header) == 0)
     {
      Print("FileWriteString failed for the header, error ", GetLastError());
      FileClose(handle);
      return(false);
     }
   for(int i = 0; i < n; i++)
     {
      const SPosRec r = closed[i];
      string direction = "UNKNOWN";
      if(r.dir > 0)
        {
         direction = "LONG";
        }
      else
        {
         if(r.dir < 0)
           {
            direction = "SHORT";
           }
        }
      string open_text = "";
      string duration_text = "";
      if(r.has_entry && r.open_time > 0)
        {
         open_text = TimeToString(r.open_time, TIME_DATE | TIME_MINUTES);
         duration_text = DoubleToString((double)(r.close_time - r.open_time) / 60.0, 1);
        }
      string line = StringFormat("%I64u;%s;%s;%s;%s;%s;%s\r\n",
                                 r.pos_id, r.symbol, direction, open_text,
                                 TimeToString(r.close_time, TIME_DATE | TIME_MINUTES),
                                 DoubleToString(r.net, 2), duration_text);
      if(FileWriteString(handle, line) == 0)
        {
         Print("FileWriteString failed at row ", i, ", error ", GetLastError());
         FileClose(handle);
         return(false);
        }
     }
   FileClose(handle);
   return(true);
  }

ExportCSV writes the closed positions to the CSV file. It receives the closed array and its count, and returns false when the file cannot be opened or a write fails. Fields are separated by semicolons. The position identifier is written with the %I64u format, which is the correct format for an unsigned 64-bit value.

CreatePanel

//+------------------------------------------------------------------+
//| Creates the background and the text lines of the panel           |
//| Returns false when an object cannot be created                   |
//+------------------------------------------------------------------+
bool CreatePanel()
  {
   string bg = TJ_PREFIX + "BG";
   if(!ObjectCreate(0, bg, OBJ_RECTANGLE_LABEL, 0, 0, 0))
     {
      Print("ObjectCreate failed for the panel background, error ", GetLastError());
      return(false);
     }
   int line_height = InpFontSize + 8;
   ObjectSetInteger(0, bg, OBJPROP_CORNER, CORNER_LEFT_UPPER);
   ObjectSetInteger(0, bg, OBJPROP_XDISTANCE, InpPanelX);
   ObjectSetInteger(0, bg, OBJPROP_YDISTANCE, InpPanelY);
   int panel_width = 48 * InpFontSize + 60;   // wide enough for the longest line at this font size
   ObjectSetInteger(0, bg, OBJPROP_XSIZE, panel_width);
   ObjectSetInteger(0, bg, OBJPROP_YSIZE, TJ_LINES * line_height + 12);
   ObjectSetInteger(0, bg, OBJPROP_BGCOLOR, C'248,249,251');
   ObjectSetInteger(0, bg, OBJPROP_BORDER_TYPE, BORDER_FLAT);
   ObjectSetInteger(0, bg, OBJPROP_COLOR, C'200,205,215');
   ObjectSetInteger(0, bg, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, bg, OBJPROP_HIDDEN, true);
//--- dark header bar behind the title line
   string head = TJ_PREFIX + "HEAD";
   if(!ObjectCreate(0, head, OBJ_RECTANGLE_LABEL, 0, 0, 0))
     {
      Print("ObjectCreate failed for the panel header, error ", GetLastError());
      return(false);
     }
   ObjectSetInteger(0, head, OBJPROP_CORNER, CORNER_LEFT_UPPER);
   ObjectSetInteger(0, head, OBJPROP_XDISTANCE, InpPanelX);
   ObjectSetInteger(0, head, OBJPROP_YDISTANCE, InpPanelY);
   ObjectSetInteger(0, head, OBJPROP_XSIZE, panel_width);
   ObjectSetInteger(0, head, OBJPROP_YSIZE, line_height + 10);
   ObjectSetInteger(0, head, OBJPROP_BGCOLOR, C'31,56,100');
   ObjectSetInteger(0, head, OBJPROP_BORDER_TYPE, BORDER_FLAT);
   ObjectSetInteger(0, head, OBJPROP_COLOR, C'31,56,100');
   ObjectSetInteger(0, head, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, head, OBJPROP_HIDDEN, true);
   for(int i = 0; i < TJ_LINES; i++)
     {
      string name = TJ_PREFIX + "L" + IntegerToString(i);
      if(!ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0))
        {
         Print("ObjectCreate failed for panel line ", i, ", error ", GetLastError());
         return(false);
        }
      ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_UPPER);
      ObjectSetInteger(0, name, OBJPROP_XDISTANCE, InpPanelX + 8);
      ObjectSetInteger(0, name, OBJPROP_YDISTANCE, InpPanelY + 6 + i * line_height);
      //--- the title line is bold and white on the dark header, the rest are monospaced
      ObjectSetInteger(0, name, OBJPROP_FONTSIZE, (i == 0) ? InpFontSize + 1 : InpFontSize);
      ObjectSetString(0, name, OBJPROP_FONT, (i == 0) ? "Arial Bold" : "Consolas");
      ObjectSetInteger(0, name, OBJPROP_COLOR, (i == 0) ? clrWhite : C'35,35,35');
      ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
      ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
     }
   return(true);
  }

CreatePanel builds the panel. It creates one background rectangle and TJ_LINES text labels, and sets their position, font, colors, and visibility. It returns false if any object cannot be created. The line height depends on the font size, so the background is sized from the same value as the labels.

ValueColor

//+------------------------------------------------------------------+
//| Returns the panel color for the sign of a value                  |
//+------------------------------------------------------------------+
color ValueColor(const double value)
  {
//--- green for a positive value, red for a negative one, dark grey for zero
   if(value > 0.0)
     {
      return(C'22,120,60');
     }
   if(value < 0.0)
     {
      return(C'178,34,34');
     }
   return(C'35,35,35');
  }

ValueColor returns the panel color for a value: green for a positive value, red for a negative one, and dark grey for zero. UpdatePanel uses it for the net result and the expectancy lines, so a loss is visible at a glance. The function receives one value, returns one color, and has no side effects.

SetPanelLine

//+------------------------------------------------------------------+
//| Writes one text line into the panel                              |
//+------------------------------------------------------------------+
void SetPanelLine(const int index, const string text, const color clr = C'35,35,35')
  {
   string name = TJ_PREFIX + "L" + IntegerToString(index);
   ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
   if(!ObjectSetString(0, name, OBJPROP_TEXT, text))
     {
      Print("ObjectSetString failed for panel line ", index, ", error ", GetLastError());
     }
  }

SetPanelLine writes one text line into a label of the panel. It receives the line index and the text. If the label cannot be updated, the error is printed, but the calculation continues, because a missing label should not block the statistics.

UpdatePanel

//+------------------------------------------------------------------+
//| Fills every line of the panel from the current statistics        |
//+------------------------------------------------------------------+
void UpdatePanel()
  {
   string scope = InpCurrentSymbolOnly ? _Symbol : "all symbols";
   string magic = (InpMagicFilter < 0) ? "all magic" : ("magic " + IntegerToString(InpMagicFilter));

   SetPanelLine(0, "TRADE JOURNAL", clrWhite);
   SetPanelLine(1, "Scope: " + scope + " | " + magic);
   SetPanelLine(2, "Closed positions: " + IntegerToString(g_stats.trades)
                   + "   Wins: " + IntegerToString(g_stats.wins)
                   + "   Losses: " + IntegerToString(g_stats.losses));
   double win_rate = (g_stats.trades > 0) ? (double)g_stats.wins / g_stats.trades : 0.0;
   SetPanelLine(3, "Win rate: " + PctText(win_rate));
   SetPanelLine(4, "Net result: " + DoubleToString(g_stats.net, 2), ValueColor(g_stats.net));
   SetPanelLine(5, "Gross profit: " + DoubleToString(g_stats.gross_profit, 2)
                   + "   Gross loss: " + DoubleToString(g_stats.gross_loss, 2));
   string pf = (g_stats.gross_loss > 0.0)
               ? DoubleToString(g_stats.gross_profit / g_stats.gross_loss, 2)
               : "n/a (no losses)";
   SetPanelLine(6, "Profit factor: " + pf);
   SetPanelLine(7, "Expectancy per trade: " + DoubleToString(g_stats.expectancy, 2), ValueColor(g_stats.expectancy));
   SetPanelLine(8, "Average win: " + DoubleToString(g_stats.avg_win, 2)
                   + "   Average loss: " + DoubleToString(g_stats.avg_loss, 2));
   SetPanelLine(9, "Max drawdown (closed): " + DoubleToString(g_stats.max_drawdown, 2));
   SetPanelLine(10, "Max win streak: " + IntegerToString(g_stats.max_win_streak)
                    + "   Max loss streak: " + IntegerToString(g_stats.max_loss_streak));
   double long_rate = (g_stats.longs > 0) ? (double)g_stats.long_wins / g_stats.longs : 0.0;
   double short_rate = (g_stats.shorts > 0) ? (double)g_stats.short_wins / g_stats.shorts : 0.0;
   SetPanelLine(11, "Long: " + IntegerToString(g_stats.longs) + " trades, win " + PctText(long_rate));
   SetPanelLine(12, "Short: " + IntegerToString(g_stats.shorts) + " trades, win " + PctText(short_rate));
   SetPanelLine(13, "Average holding time: " + DoubleToString(g_stats.avg_duration_min, 1) + " min");

   int best_h = -1, worst_h = -1;
   if(BestAndWorst(g_hour_net, g_hour_count, 24, best_h, worst_h))
     {
      SetPanelLine(14, "Best hour: " + StringFormat("%02d:00", best_h)
                       + " net " + DoubleToString(g_hour_net[best_h], 2)
                       + " (" + IntegerToString(g_hour_count[best_h]) + " trades)");
      SetPanelLine(15, "Worst hour: " + StringFormat("%02d:00", worst_h)
                       + " net " + DoubleToString(g_hour_net[worst_h], 2)
                       + " (" + IntegerToString(g_hour_count[worst_h]) + " trades)");
     }
   else
     {
      SetPanelLine(14, "Best hour: no data");
      SetPanelLine(15, "Worst hour: no data");
     }

   int best_d = -1, worst_d = -1;
   if(BestAndWorst(g_day_net, g_day_count, 7, best_d, worst_d))
     {
      SetPanelLine(16, "Best weekday: " + DayName(best_d)
                       + " net " + DoubleToString(g_day_net[best_d], 2));
      SetPanelLine(17, "Worst weekday: " + DayName(worst_d)
                       + " net " + DoubleToString(g_day_net[worst_d], 2));
     }
   else
     {
      SetPanelLine(16, "Best weekday: no data");
      SetPanelLine(17, "Worst weekday: no data");
     }
   SetPanelLine(18, "Last refresh: " + TimeToString(TimeCurrent(), TIME_DATE | TIME_SECONDS));
   SetPanelLine(19, g_status);
   ChartRedraw(0);
  }

UpdatePanel fills all twenty lines from the current statistics and buckets. It receives nothing, because it reads the global state. It builds the scope line from the symbol and magic filters, computes the win rates with a guard for empty groups, and writes the profit factor as N/A when there are no losses. It then sets the best and worst buckets, the refresh time, and the status line, and calls ChartRedraw so the changes appear at once.

Recalculate

//+------------------------------------------------------------------+
//| Rebuilds the journal from the history and refreshes the panel    |
//+------------------------------------------------------------------+
void Recalculate()
  {
   SPosRec recs[];
   int rec_count = 0;
   if(!BuildRecords(recs, rec_count))
     {
      g_status = "History could not be read, see Experts log";
      UpdatePanel();
      return;
     }
   g_closed_count = CollectClosed(recs, rec_count, g_closed);
   if(g_closed_count < 0)
     {
      g_status = "Sorting failed, see Experts log";
      UpdatePanel();
      return;
     }
   ComputeStats(g_closed, g_closed_count, g_stats);
   ComputeBuckets(g_closed, g_closed_count);
   if(InpExportCSV)
     {
      if(ExportCSV(g_closed, g_closed_count))
        {
         g_status = "CSV written: " + TJ_CSV_FILE;
        }
      else
        {
         g_status = "CSV export failed, see Experts log";
        }
     }
   else
     {
      g_status = "CSV export is off";
     }
   UpdatePanel();
  }

Recalculate is the single entry point for a full refresh. It receives nothing. It runs the steps in order: build the records, collect and sort the closed positions, compute the statistics and buckets, write the CSV when enabled, and update the panel. Each failed step sets a status message and redraws the panel, so the reason is visible on the chart as well as in the Experts log.

OnInit

//+------------------------------------------------------------------+
//| Creates the panel and starts the refresh timer                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- validate the inputs that the panel layout depends on
   if(InpRefreshSeconds < 5)
     {
      Print("Refresh interval must be at least 5 seconds, got ", InpRefreshSeconds);
      return(INIT_PARAMETERS_INCORRECT);
     }
   if(InpFontSize < 6 || InpFontSize > 20)
     {
      Print("Font size must be between 6 and 20, got ", InpFontSize);
      return(INIT_PARAMETERS_INCORRECT);
     }
//--- remove panel objects left by an earlier run, then create them again
   ObjectsDeleteAll(0, TJ_PREFIX);
   if(!CreatePanel())
     {
      return(INIT_FAILED);
     }
   if(!EventSetTimer(InpRefreshSeconds))
     {
      Print("EventSetTimer failed, error ", GetLastError());
      return(INIT_FAILED);
     }
   Recalculate();
   return(INIT_SUCCEEDED);
  }

OnInit validates the refresh interval and font size, removes panel objects left by an earlier run, creates the panel, starts the timer, and performs the first calculation. It returns INIT_PARAMETERS_INCORRECT for invalid inputs and INIT_FAILED when the panel or the timer cannot be created.

OnDeinit

//+------------------------------------------------------------------+
//| Stops the timer and removes the panel objects                    |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   EventKillTimer();
   ObjectsDeleteAll(0, TJ_PREFIX);
  }

OnDeinit stops the timer and removes every object whose name starts with the panel prefix. It receives the reason code, which this tool does not need, and leaves the chart clean when the EA is removed or the chart is closed.

OnTimer

//+------------------------------------------------------------------+
//| Refreshes the journal at the interval set in the inputs          |
//+------------------------------------------------------------------+
void OnTimer()
  {
   Recalculate();
  }

OnTimer runs at the interval set by the input and calls Recalculate. It has no parameters and no return value. The timer keeps the panel current even when no trade occurs, for example after a deposit or withdrawal.

OnTradeTransaction

//+------------------------------------------------------------------+
//| Refreshes the journal when a new deal appears in the history     |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &result)
  {
   if(trans.type == TRADE_TRANSACTION_DEAL_ADD)
     {
      Recalculate();
     }
  }

OnTradeTransaction runs when the terminal reports a trade transaction. It receives the transaction, the request, and the result, and calls Recalculate only when the transaction adds a deal to the history. Other transaction types are ignored, which avoids unnecessary work when orders are placed or modified.


Testing Notes

The grouping rules were checked with ten hand-made deal scenarios, listed in Table 2. The scenarios were run through a Python mirror of the grouping code, not in the MetaTrader terminal, and the table shows the result before and after the magic and volume corrections. The statistical formulas were checked against a hand-made list of six closed positions. The nets were 100, -50, 30, -20, -10, and 80, in that order. The hand calculation gives a net of 130, three wins with a gross profit of 210, three losses with a gross loss of 80, a profit factor of 2.625, an expectancy of 21.67, a maximum drawdown of 50, and a longest losing streak of two. The same formulas, written in Python, produce these values

Scenario Expected result Before this correction After this correction
S1 entry commission, one exit closed, net 113.00 closed, net 113.00 closed, net 113.00
S2 partial closes, closed after last exit closed, net 22.00 closed, net 22.00 closed, net 22.00
S3 partial close only, still open not closed not closed not closed
S4 swap and fee on exit deal closed, net 27.00 closed, net 27.00 closed, net 27.00
S5 exit with other magic, entry matches closed, net 33.00 not closed closed, net 33.00
S6 entry with other magic not closed not closed not closed
S7 exit only, entry before InpFromDate not closed not closed not closed
S8 balance deal with no position skipped (no position identifier) skipped (no position identifier) skipped (no position identifier)
S9 closed by opposite position closed, net 33.00 closed, net 33.00 closed, net 33.00
S10 exit volume larger than entry not closed closed, net 33.00 not closed

Table 2. Hand-made deal scenarios for the grouping rules, run through a Python mirror of the code.

The data functions use the documented history and deal properties of MetaTrader 5. The final check on the terminal is to open the History tab for the same period and compare the number of closed positions and the net result with the panel. The CSV file can be opened next to the History tab for a line-by-line comparison.


Limitations

The tool is designed for hedging accounts. On a netting account, a single deal can close one position and open a new one in the opposite direction, and this code does not split that deal. Such positions may carry the wrong result, so traders on netting accounts should compare the panel with the History tab before relying on it.

The drawdown is measured on closed positions only. A large floating loss on an open position is not shown, so the panel can understate the risk that was present while a trade was open. Read the drawdown together with the account's own equity curve.

A partly closed position stays open until its volume reaches zero, and its net includes every deal of the position. A position that was partly closed and then added to may show a holding time that starts at its first entry. This follows the MetaTrader 5 position model, but it may not match how a trader thinks about the trade.

The money values are in the account currency, and the tool does not convert them. Commission, swap, and fee depend on the broker, and some brokers report them on separate deals. The code adds the cash fields of BUY and SELL deals only. Separate accrual or fee deals that the broker reports without a BUY or SELL type are not added, so the net can differ from the broker's statement.

The hour and weekday buckets use the server time of the entry deal, so a broker's daylight-saving change can move a trade into a different hour. In short histories a bucket holds few positions, so one unusual trade can change the best or worst line.

The linear search in FindOrAddPos and the selection sort in CollectClosed are simple, and their cost grows with the number of deals and positions. The article does not include a timing benchmark. InpFromDate is the simplest way to limit the work on a long history.


Conclusion

TradeJournal reconstructs positions from their deals, sorts fully closed positions by closing time, and calculates the statistics shown on the chart. It also breaks results down by entry hour and weekday and can export the closed-position records to CSV.

To check the output on your account, compile and attach the EA to a hedging-account chart, set the symbol, magic-number, and date filters, then compare selected position IDs and their net results in the CSV with the corresponding deals in account history. Finally, check that the CSV’s closed-position count and net total agree with the panel. The synthetic Python checks described in the article test the grouping rules and formulas; they do not test the MQL5 code in a terminal or replace this account-level check.

Use the results as a summary of closed-position performance, not as a measure of floating risk. Hour and weekday breakdowns describe the selected sample and do not, by themselves, establish a trading edge.

Attached files |
TradeJournal.mq5 (28.77 KB)
Adaptive Bar Replay Tool in MQL5: Using MFE and MAE Percentile Analysis Adaptive Bar Replay Tool in MQL5: Using MFE and MAE Percentile Analysis
We implement a bar replay indicator in MQL5 that uses historical MFE and MAE percentiles to compute adaptive Stop Loss and Take Profit levels. The article covers data collection, excursion calculation, percentile interpolation, and an event-driven engine that replays candles and manages multiple simulated positions. Readers can test decisions against statistically derived risk thresholds rather than fixed offsets.
Neural Networks in Trading: Spatially Guided Aggregation of Market Events (STFlow) Neural Networks in Trading: Spatially Guided Aggregation of Market Events (STFlow)
The article introduces the STFlow framework, which can generate a robust joint representation of the current market state and the dynamics of recent events, ensuring high sensitivity to micro-impulses while maintaining stable processing. The core ICE module has been implemented; it accumulates price and event streams, creating a reliable foundation for further aggregation and analysis.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Streaming Percentiles in MQL5: Testing the P-Square Algorithm on Real Tick Data Streaming Percentiles in MQL5: Testing the P-Square Algorithm on Real Tick Data
An EA can set spread and tick-gap thresholds by percentile without storing every tick. CPSquare implements the P-Square algorithm, and two order-independent classes serve as alternatives: CCountQuantile returns exact percentiles of rounded spreads, and CLogQuantile keeps a chosen relative error within a set range. Unit tests, mutation runs, and a Python consistency check cover the code. On EURUSD and XAUUSD ticks in time order, the P-Square estimates of high percentiles stayed far from the exact values.