preview
Auditing an Expert Advisor From Its Trade History (Part 1): Rebuilding Positions From Deals

Auditing an Expert Advisor From Its Trade History (Part 1): Rebuilding Positions From Deals

MetaTrader 5 — Examples |
126 0
Solomon Anietie Sunday
Solomon Anietie Sunday

Contents

  1. Introduction
  2. Section 1: Building the TradeAudit Library
  3. Section 2: The Scripts
  4. Verification
  5. What This Part Does Not Do
  6. Conclusion


Introduction

When deciding whether to keep running an Expert Advisor, the first place to look is its history: how many trades it took, how many of them won, what an average trade earned. A program that computes those figures has to read the account's history in MQL5, where every entry, every partial exit and every reversal is stored as a separate deal. A trade is something the program has to rebuild from those deals.

This article uses the word trade for one unit: on a hedging account one position, and on a netting account one segment of a position, from its first entry until the volume returns to zero or a reversal turns it. The library builds one record for each. That unit is a choice. The terminal's report in the Verification section gives a trade count equal to its number of closing deals, and a close-by, one operation for the trader, is two trades here because it closes two positions. A figure counted per trade has to say which unit it uses.

This part implements the rebuild step and handles cases where a simple pass through the deals fails. Two cases—the scale-in by a second order and the reversal—exist only on netting accounts. Here, they are tested only on hand-built deals, so the code is verified against this article's interpretation of the documentation, not against real netting-account records. Any per-trade statistical computed later depends on the rebuild. An error here can propagate into those figures without being detected. The library reads history and prints to the log, and the export script writes one file. Nothing in either sends, modifies or closes an order.

By the end of this part, you will have:

  • AuditRecord.mqh and HistoryReader.mqh in MQL5\Include\TradeAudit\, which together rebuild one record per closed trade with its prices, volumes, costs and flags.

  • A script that rebuilds a date range and writes one CSV row per trade.
  • A script that runs hand-built netting and close-by deals through the same rebuild and checks the results.

Problem: One Row per Closing Deal

The obvious export walks the deals in a date range and writes one row for each deal that closes something. It looks right on an account where every trade opens once and closes once. A position closed in three parts produces three closing deals, so the export writes three rows for one trade, each with part of the volume and its own profit. A win rate computed from that file counts one trade three times. On a netting account, a position that was added to has entry deals at more than one price, and an export that reads the entry price from one of them reports a price the whole position never had. Grouping the deals by position ID repairs the first case and breaks on another. A netting reversal closes a long and opens a short in a single deal, and both keep the same position ID, so an export that groups by that ID alone turns two trades into one, with one profit figure that mixes both.

The money total of such a file can still match the History tab, because each deal's profit is in it once. The number of trades does not match, and neither does any figure counted per trade: a win rate, an average trade, a largest loss. Nothing in the file shows that.

Deals, Orders and Positions

MQL5 keeps three kinds of trade record. An order is a request to trade. A deal is an execution: a volume bought or sold at a price, at a time. A position is what the deals leave open. Once a position closes, only its orders and deals remain in history, so a closed trade has to be rebuilt from its deals. Each deal carries the properties the rebuild needs. DEAL_POSITION_ID identifies the position the deal opened, changed or closed. DEAL_ENTRY says what it did to that position: DEAL_ENTRY_IN added volume, DEAL_ENTRY_OUT removed volume, DEAL_ENTRY_INOUT reversed the position, and DEAL_ENTRY_OUT_BY closed it against an opposite position. DEAL_TYPE says whether it was a buy or a sell, or one of the non-trade types: balance, credit, commission, interest, dividends, tax and others. The full lists are in the deal properties documentation.

How these deals combine depends on the account's position accounting:


Hedging accountNetting account
Positions per symbolAny numberOne
A second buy while the position is openOpens a new position with a new ID
Adds to the same position, a scale-in
A sell while a buy is openOpens a separate sell position, unless it is sent to close the buy
Reduces or closes the buy; if larger, reverses it in one in-out deal under the same ID
Closing part of the volumeAn out deal for that partAn out deal for that part
Close-byAvailable, one out-by deal per position
Not available

So a second order adds to a position only on a netting account, reversals happen only there, and close-by exists only on hedging accounts. A partial close happens on both. On both, the server can also fill one order in more than one deal, so a position can have several entry deals or several exit deals without the trader having scaled in or closed in parts. The reader's walk covers each of these shapes.

Rebuild() prints the account's margin mode in its first line. It is one of three values: ACCOUNT_MARGIN_MODE_RETAIL_HEDGING, ACCOUNT_MARGIN_MODE_RETAIL_NETTING, or ACCOUNT_MARGIN_MODE_EXCHANGE, which the documentation describes by its margin calculation and not by how positions are kept.

Scope of This Article

Two headers go in MQL5\Include\TradeAudit\:

  • AuditRecord.mqh: the record for one closed trade, and the total for one type of non-trade deal.
  • HistoryReader.mqh: CHistoryReader, which rebuilds records for a date range.

Two scripts go in MQL5\Scripts\:

  • AuditExport.mq5: rebuilds a range and writes one CSV row per record.
  • AuditSelfTest.mq5: rebuilds hand-built deal sequences and checks the results against values worked out by hand.

The library computes no statistics in this part. It produces the records, the counts of what was left out, and the totals of non-trade deals. A position that has a deal in the range and is still open when the script runs is counted, not rebuilt. The first section covers the two headers, and the second covers the scripts.


Section 1: Building the TradeAudit Library

The Trade Record

AuditRecord.mqh holds the structure the reader fills and the scripts read.

//+------------------------------------------------------------------+
//| One closed trade: a hedging position, or one netting segment     |
//+------------------------------------------------------------------+
struct SAuditRecord
  {
   long               positionId;        // DEAL_POSITION_ID shared by every deal of the position
   int                segment;           // 1, then 2, 3... after each netting reversal
   string             symbol;
   long               magic;             // Magic number of the deal that opened this segment
   ENUM_POSITION_TYPE type;              // Direction of the segment
   datetime           openTime;
   datetime           closeTime;         // Time of the deal that brought the volume back to zero
   int                entryDeals;        // More than one: a scale-in, or an order filled in several deals
   int                exitDeals;         // More than one: closed in parts, or an order filled in several deals
   double             volumeIn;
   double             volumeOut;
   double             entryPrice;        // Volume-weighted over the entry deals
   double             exitPrice;         // Volume-weighted over the exit deals
   bool               closedBy;          // At least one exit was a close-by
   bool               openedByReversal;
   bool               closedByReversal;
   double             profit;            // Sum of DEAL_PROFIT: price movement only
   double             commission;
   double             swap;
   double             fee;

   double             Net(void) const { return(profit + commission + swap + fee); }
  };

A record is one trade. On a hedging account that is one position. On a netting account it is one segment of a position: the stretch from the moment the position opens until its volume returns to zero, or until a reversal turns it the other way. positionId and segment together identify a record. In the terminal's own history, segment goes past 1 only after a reversal, because the documentation gives each re-opened position a new identifier. The walk itself would also start a new segment on an entry that followed a full close under the same ID.

entryDeals and exitDeals are counted as the deals are read. A value above one means more than one deal built that side of the trade: a scale-in or a close in parts, or one order that the server filled in several deals. The record does not tell these apart.

entryPrice and exitPrice are weighted by volume across those deals. magic comes from the deal that opened the segment, one number for the whole record, so on a netting account that several EAs share, the record carries the opener's magic number and holds the deals the others sent. A record per magic number would need a rule for sharing one running volume, and this part has none. Profit is DEAL_PROFIT summed over the trade's deals, which leaves commission, swap and fee out, and Net() adds those three to it. A reversal deal is the exception to the summing, and Netting Reversals says how its money is divided.

The second structure in the file holds a total for one type of deal that belongs to no trade:

//+------------------------------------------------------------------+
//| Account-level total for one type of non-trade deal               |
//+------------------------------------------------------------------+
struct SNonTradeTotal
  {
   ENUM_DEAL_TYPE     type;
   int                count;
   double             amount;            // Profit, commission, swap and fee of those deals
  };

HistoryReader.mqh includes AuditRecord.mqh and declares one class, CHistoryReader. Its public methods are few:

MethodWhat it does
Rebuild(from, to, magic, symbol)Reads history for the range and builds the records that close in it and pass both filters
Prepare(from, to, magic, symbol)Sets the range and filters and clears every count; Rebuild() calls it first
BuildFromDeals(positionId, symbol, deals[])Rebuilds one position from deals already in memory
Total(), RecordAt(index, rec)Read the records back
PrintSummary()Prints what was built, left out and skipped

Prepare() and BuildFromDeals() are public so that deals can be passed to the rebuild without reading history, which is how the self-test script in the second section works. Calling them directly has two conditions that Rebuild() otherwise takes care of. The deals have to be passed oldest first, since the sort is a private step, and Prepare() has to be called first, since a reader that was never given a range keeps no record.

The reader copies each deal it needs into a structure of its own, because deals have to be sorted before they are read:

//+------------------------------------------------------------------+
//| One deal, copied out of history so it can be sorted              |
//+------------------------------------------------------------------+
struct SAuditDeal
  {
   ulong              ticket;
   long               timeMsc;
   datetime           time;
   ENUM_DEAL_TYPE     type;
   ENUM_DEAL_ENTRY    entry;
   long               magic;
   double             volume;
   double             price;
   double             profit;
   double             commission;
   double             swap;
   double             fee;
  };

What the reader cannot use is counted under one of these reasons: a deal, a whole position, or a record it could not store.

//+------------------------------------------------------------------+
//| Why a deal, a whole position or a record was left out            |
//+------------------------------------------------------------------+
enum ENUM_AUDIT_SKIP
  {
   AUDIT_SKIP_DEAL_UNREADABLE,
   AUDIT_SKIP_DEAL_NO_POSITION,
   AUDIT_SKIP_DEAL_CANCELED,
   AUDIT_SKIP_DEAL_NON_TRADE,
   AUDIT_SKIP_DEAL_UNKNOWN_ENTRY,
   AUDIT_SKIP_POSITION_NO_HISTORY,
   AUDIT_SKIP_POSITION_INCONSISTENT,
   AUDIT_SKIP_RECORD_NOT_STORED,
   AUDIT_SKIP_REASON_COUNT
  };

The last value is not a reason. It sizes the array of counters, so adding a reason above it grows the array, and the new reason then needs only its wording in SkipText(). Positions still open, segments closed outside the range and records removed by a filter are not skips, and each has a counter of its own.

Collecting Positions Before Rebuilding Them

A date range often starts or ends while a position is open. A position opened last month and closed yesterday has its entry deals outside the range and its exit deals inside it. Rebuilding only from the deals in the range would give that trade an exit and no entry. The reader therefore works in two passes. The first reads every deal in the range and collects the position ID of each trade deal. The second asks history for every deal of each of those positions, whenever it happened, and rebuilds the position in full.

The reader keeps the two passes apart. HistorySelect() creates the program's list of deals for a period, and the documentation describes HistorySelectByPosition() as building a list of deals for one position, read through the same HistoryDealsTotal() and HistoryDealGetTicket() calls. 

Therefore, the reader does not assume the first list remains available after loading a position. It collects all position IDs before loading any position.Selecting the range again after each position would also work, at the price of one more history query per position.
//+------------------------------------------------------------------+
//| Rebuild every trade closed inside the range                      |
//+------------------------------------------------------------------+
bool CHistoryReader::Rebuild(const datetime from, const datetime to, const long magic, const string symbol)
  {
   Prepare(from, to, magic, symbol);

//--- Check the range before touching history
   if(from >= to)
     {
      PrintFormat("TradeAudit: invalid range, %s is not before %s",
                  TimeToString(from, TIME_DATE | TIME_MINUTES), TimeToString(to, TIME_DATE | TIME_MINUTES));
      return(false);
     }

   ENUM_ACCOUNT_MARGIN_MODE mode = (ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE);
   PrintFormat("TradeAudit: range %s to %s, magic %s, symbol %s, account %s",
               TimeToString(from, TIME_DATE | TIME_MINUTES), TimeToString(to, TIME_DATE | TIME_MINUTES),
               (magic == 0) ? "all" : IntegerToString(magic), (symbol == "") ? "all" : symbol,
               EnumToString(mode));

//--- Pass 1: every deal in the range, for position IDs and non-trade totals
   if(!HistorySelect(from, to))
     {
      PrintFormat("TradeAudit: HistorySelect() failed, error %d", GetLastError());
      return(false);
     }

   long ids[];
   int  total = HistoryDealsTotal();
   m_dealsInRange = total;
   ArrayResize(ids, 0, total);

   for(int i = 0; i < total; i++)
     {
      ulong ticket = HistoryDealGetTicket(i);
      if(ticket == 0)
        {
         m_skips[AUDIT_SKIP_DEAL_UNREADABLE]++;
         continue;
        }

      ENUM_DEAL_TYPE type = (ENUM_DEAL_TYPE)HistoryDealGetInteger(ticket, DEAL_TYPE);
      bool tradeDeal = (type == DEAL_TYPE_BUY || type == DEAL_TYPE_SELL ||
                        type == DEAL_TYPE_BUY_CANCELED || type == DEAL_TYPE_SELL_CANCELED);
      if(!tradeDeal)
        {
         CountNonTrade(type, HistoryDealGetDouble(ticket, DEAL_PROFIT) + HistoryDealGetDouble(ticket, DEAL_COMMISSION) +
                             HistoryDealGetDouble(ticket, DEAL_SWAP) + HistoryDealGetDouble(ticket, DEAL_FEE));
         continue;
        }

      long positionId = HistoryDealGetInteger(ticket, DEAL_POSITION_ID);
      if(positionId == 0)
        {
         m_skips[AUDIT_SKIP_DEAL_NO_POSITION]++;
         continue;
        }

      int n = ArraySize(ids);
      ArrayResize(ids, n + 1, total);
      ids[n] = positionId;
     }

//--- One ID per position, however many of its deals fall in the range
   m_positionsFound = CollapseIds(ids);

//--- Pass 2: each position from all of its deals. HistorySelectByPosition() builds a list
//--- of its own, so every ID was collected before the first position is loaded.
   for(int p = 0; p < m_positionsFound; p++)
     {
      SAuditDeal deals[];
      string     positionSymbol;
      if(!LoadPositionDeals(ids[p], deals, positionSymbol))
        {
         m_skips[AUDIT_SKIP_POSITION_NO_HISTORY]++;
         continue;
        }
      OrderDeals(deals);
      BuildFromDeals(ids[p], positionSymbol, deals);
     }
   return(true);
  }

A range whose start is not before its end is refused with a line of its own before anything else. The start line reports the range, both filters and the account's margin mode, so the log of a rebuild says which rules its deals followed. If HistorySelect() then fails, the function prints the terminal's error code and stops. In the first pass, a deal that is not a buy, a sell, or a canceled buy or sell goes to the non-trade totals and adds nothing to a record. CollapseIds() sorts the collected IDs and keeps one of each, since a position with several deals in the range was collected several times.

LoadPositionDeals() calls HistorySelectByPosition() for one ID and copies each of its deals into an SAuditDeal. It also takes the position's symbol from its first buy or sell deal. It is a straight copy of deal properties, one line each, and it returns false when the selection fails or holds no readable deal for the ID. The ID is cast to ulong on the way in, because HistorySelectByPosition() takes an unsigned value while DEAL_POSITION_ID is read as a long.

Deals in Time Order

The rebuild reads a position's deals in the order they happened. The reader does not rely on the index order of the history list for that, and sorts the copies itself:

//+------------------------------------------------------------------+
//| Oldest first by DEAL_TIME_MSC, then by ticket; never index order |
//+------------------------------------------------------------------+
void CHistoryReader::OrderDeals(SAuditDeal &deals[]) const
  {
   int total = ArraySize(deals);
   for(int i = 1; i < total; i++)
     {
      SAuditDeal key = deals[i];
      int        j   = i - 1;
      while(j >= 0 && (deals[j].timeMsc > key.timeMsc ||
                       (deals[j].timeMsc == key.timeMsc && deals[j].ticket > key.ticket)))
        {
         deals[j + 1] = deals[j];
         j--;
        }
      deals[j + 1] = key;
     }
  }

DEAL_TIME_MSC is the deal time in milliseconds. Two deals of one position in the same millisecond are ordered by ticket. That is an assumption: the documentation calls the ticket a unique number assigned to each deal and says nothing about order of execution, and it does not describe the order of the history list either. If the assumption is wrong for two entries or two exits, the volumes, prices and money come out the same. For an entry and an exit, or a reversal and another deal, a wrong order can end a segment in a different place: the walk refuses the position when that produces an exit larger than what is open, and otherwise can build a wrong record with no sign of it.

An insertion sort is used because a position usually has a handful of deals. Its running time grows with the square of the count, so a netting position built from thousands of deals would sort slowly.

The Running Volume

The rebuild rests on one rule: a trade ends when the running volume returns to zero. An entry deal adds its volume, an exit deal subtracts it, and the deal that brings the total back to zero closes the record. Applied to deals in time order, that rule handles a single exit, a close in several parts and a scale-in the same way, with no special case for any of them. The reversal is the one case that needs its own branch, because it crosses zero within a single deal.

The self-test script uses this netting sequence, all under position ID 9001:

DealType and entryVolumePriceRunning volume after
101buy, in1.01.100001.0
102buy, in0.51.102001.5
103sell, out0.71.105000.8
104sell, in-out1.81.10300−1.0: 0.8 closes the long, 1.0 opens a short
105buy, out1.01.100000

Running volume

The long, segment 1, opens with deal 101, is added to by 102 and closes in two parts, 103 and the closing share of 104. The short, segment 2, opens with the rest of 104 and closes with 105. Worked out by hand from those deals, segment 1's entry price is (1.0 × 1.10000 + 0.5 × 1.10200) / 1.5 = 1.100667 and its exit price is (0.7 × 1.10500 + 0.8 × 1.10300) / 1.5 = 1.103933.

Volumes are compared with a small tolerance, because a sum such as 0.1 + 0.2 − 0.3 is not exactly zero in floating point. The tolerance is a fixed 1e-8 lots, chosen so that the walk needs nothing from the symbol. On a symbol whose volume step is 1e-8 lots or smaller, a remainder of one step can be taken for zero and close a segment early. Half the symbol's SYMBOL_VOLUME_STEP would fit each symbol and would need the symbol to be available:

#define TRADEAUDIT_VOLUME_EPS 1e-8

The whole walk for one position:

//+------------------------------------------------------------------+
//| Walk one position's sorted deals and emit its records            |
//+------------------------------------------------------------------+
void CHistoryReader::BuildFromDeals(const long positionId, const string symbol, const SAuditDeal &deals[])
  {
   SAuditRecord rec;
   ZeroMemory(rec);
   bool         open       = false;
   int          segment    = 0;
   double       openVolume = 0.0;
   double       entryValue = 0.0;   // Price times volume, summed over entries
   double       exitValue  = 0.0;   // Price times volume, summed over exits
   int          total      = ArraySize(deals);

   for(int i = 0; i < total; i++)
     {
      //--- Only buy and sell deals build a trade; anything else is counted and passed over
      if(deals[i].type == DEAL_TYPE_BUY_CANCELED || deals[i].type == DEAL_TYPE_SELL_CANCELED)
        {
         m_skips[AUDIT_SKIP_DEAL_CANCELED]++;
         continue;
        }
      if(deals[i].type != DEAL_TYPE_BUY && deals[i].type != DEAL_TYPE_SELL)
        {
         m_skips[AUDIT_SKIP_DEAL_NON_TRADE]++;
         continue;
        }

      ENUM_POSITION_TYPE side   = (deals[i].type == DEAL_TYPE_BUY) ? POSITION_TYPE_BUY : POSITION_TYPE_SELL;
      double             volume = deals[i].volume;
      double             price  = deals[i].price;

      switch(deals[i].entry)
        {
         case DEAL_ENTRY_IN:
            if(!open)
              {
               StartSegment(rec, positionId, ++segment, symbol, side, deals[i]);
               open       = true;
               openVolume = 0.0;
               entryValue = 0.0;
               exitValue  = 0.0;
              }
            else
               if(side != rec.type)
                 {
                  m_skips[AUDIT_SKIP_POSITION_INCONSISTENT]++;
                  return;
                 }
            //--- The first entry, or a later one: a scale-in, or more of one order's fill
            rec.entryDeals++;
            rec.volumeIn += volume;
            entryValue   += price * volume;
            openVolume   += volume;
            AddCosts(rec, deals[i]);
            break;

         case DEAL_ENTRY_OUT:
         case DEAL_ENTRY_OUT_BY:
            if(!open || side == rec.type || volume > openVolume + TRADEAUDIT_VOLUME_EPS)
              {
               m_skips[AUDIT_SKIP_POSITION_INCONSISTENT]++;
               return;
              }
            rec.exitDeals++;
            rec.volumeOut += volume;
            exitValue     += price * volume;
            openVolume    -= volume;
            AddCosts(rec, deals[i]);
            if(deals[i].entry == DEAL_ENTRY_OUT_BY)
               rec.closedBy = true;
            //--- The segment ends when the running volume is back to zero
            if(openVolume <= TRADEAUDIT_VOLUME_EPS)
              {
               rec.closeTime = deals[i].time;
               FinishSegment(rec, entryValue, exitValue);
               open = false;
              }
            break;

         case DEAL_ENTRY_INOUT:
           {
            double closing = openVolume;
            double opening = volume - closing;
            if(!open || side == rec.type || opening <= TRADEAUDIT_VOLUME_EPS)
              {
               m_skips[AUDIT_SKIP_POSITION_INCONSISTENT]++;
               return;
              }
            double share = closing / volume;

            //--- The closing part ends the current segment: profit and swap are its own
            rec.exitDeals++;
            rec.volumeOut        += closing;
            exitValue            += price * closing;
            rec.profit           += deals[i].profit;
            rec.swap             += deals[i].swap;
            rec.commission       += deals[i].commission * share;
            rec.fee              += deals[i].fee * share;
            rec.closedByReversal  = true;
            rec.closeTime         = deals[i].time;
            FinishSegment(rec, entryValue, exitValue);

            //--- The rest opens the next segment under the same position ID
            StartSegment(rec, positionId, ++segment, symbol, side, deals[i]);
            rec.openedByReversal = true;
            rec.entryDeals       = 1;
            rec.volumeIn         = opening;
            rec.commission       = deals[i].commission * (1.0 - share);
            rec.fee              = deals[i].fee * (1.0 - share);
            entryValue           = price * opening;
            exitValue            = 0.0;
            openVolume           = opening;
            break;
           }

         default:
            //--- An unknown entry type may have changed the volume: leave the rest of the position
            m_skips[AUDIT_SKIP_DEAL_UNKNOWN_ENTRY]++;
            return;
        }
     }

   if(open)
      m_stillOpen++;
  }

Canceled deals and non-trade deals inside a position's history are counted and passed over. For every buy or sell, the entry type decides what happens.

An entry deal with nothing open starts a segment through StartSegment(), which resets the record and fills in the ID, the segment number, the symbol, the direction, the open time and the opening deal's magic number. Every entry deal, the first one or a later one, then adds one to entryDeals, adds its volume to the record and to the running volume, and adds price times volume to entryValue.

An exit deal subtracts its volume from the running volume and adds price times volume to exitValue. DEAL_ENTRY_OUT_BY takes the same path and also marks the record as closed by. When the running volume reaches zero, within the tolerance, the deal's time becomes the close time and FinishSegment() prices the record. The two value sums divided by the two volumes give the volume-weighted entry and exit prices, however many deals made up each side. A position that is still open when its last deal has been read never reaches zero. It is counted as still open, and its open segment produces no record. Exits it has already made stay out of the file until the position closes.

The walk also refuses five things: an exit or a reversal with nothing open, an exit larger than the open volume, a reversal deal no larger than the open volume, a deal on the wrong side for the segment, such as a buy entry while a sell segment is open, and a buy or sell whose entry type is none of the four. Each stops the rebuild of that position, and segments it closed before that deal are kept. The first four are counted as a position whose deals do not add up, and the fifth under a reason of its own. One cause is history the account no longer holds, where the first deal still available is an exit. A record built past such a deal could be wrong without any sign of it, so the reader gives up the rest of that position and says so in the summary.

Closing a Segment

//+------------------------------------------------------------------+
//| Price the closed segment, then keep it only if it passes scope   |
//+------------------------------------------------------------------+
void CHistoryReader::FinishSegment(SAuditRecord &rec, const double entryValue, const double exitValue)
  {
   rec.entryPrice = (rec.volumeIn > 0.0) ? entryValue / rec.volumeIn : 0.0;
   rec.exitPrice  = (rec.volumeOut > 0.0) ? exitValue / rec.volumeOut : 0.0;

//--- A record belongs to the range by its close time: from m_from up to, not including, m_to
   if(rec.closeTime < m_from || rec.closeTime >= m_to)
     {
      m_outsideRange++;
      return;
     }
//--- Magic number first, then symbol
   if(m_magic != 0 && rec.magic != m_magic)
     {
      m_filteredOut++;
      return;
     }
   if(m_symbol != "" && StringCompare(rec.symbol, m_symbol, false) != 0)
     {
      m_filteredOut++;
      return;
     }

   int n = ArraySize(m_records);
   if(ArrayResize(m_records, n + 1, 256) != n + 1)
     {
      PrintFormat("TradeAudit: out of memory storing position %I64d, segment %d", rec.positionId, rec.segment);
      m_skips[AUDIT_SKIP_RECORD_NOT_STORED]++;
      return;
     }
   m_records[n] = rec;

   if(rec.exitDeals > 1)
      m_multiExit++;
   if(rec.entryDeals > 1)
      m_multiEntry++;
   if(rec.closedBy)
      m_withCloseBy++;
   if(rec.openedByReversal || rec.closedByReversal)
      m_withReversal++;
  }

After pricing the segment, FinishSegment() decides whether it belongs in the results. A record belongs to the range by its close time: it is kept when the segment closed at or after the start of the range and before its end, so two exports whose ranges meet cannot both hold it. A trade opened before the range and closed inside it is kept, rebuilt from all of its deals, and one that closed at or after its end is counted as closed outside it. This keeps each trade whole and in a single export. However, a kept record may include exits made before the range began, while exits made inside the range for positions that close later (or remain open) appear in no row. As a result, the file total can differ from profit realized within the range. Assigning money by each deal's own time would give the period's result and cut one trade across two exports.

The magic number filter compares the magic number of the deal that opened the segment, and the symbol filter ignores case. A record that passes is stored, and four counters are updated for the summary: records with more than one exit deal, with more than one entry deal, with a close-by exit, and with a reversal at either end. If the array of records cannot grow, the record is dropped with a line that names its position and segment, and the drop is counted among the skips.

The money fields come from the trade's own deals, entry and exit alike. A reversal deal is handled separately, as the next section describes:

//+------------------------------------------------------------------+
//| Add a deal's profit and costs to the record                      |
//+------------------------------------------------------------------+
void CHistoryReader::AddCosts(SAuditRecord &rec, const SAuditDeal &deal) const
  {
   rec.profit     += deal.profit;
   rec.commission += deal.commission;
   rec.swap       += deal.swap;
   rec.fee        += deal.fee;
  }

Commission can be charged on the entry deal, on the exit deal or on both, depending on the broker, and a position has no property of its own for it. Reading all four fields from every deal of the trade collects every cost booked on those deals. A cost the broker books as a deal of its own, such as a daily or monthly commission or an interest charge, is in the non-trade totals and in no record, so Net() can be higher than what the trade left once that cost is counted. DEAL_FEE is a separate charge made immediately after a deal, and it is added the same way.

Netting Reversals

On a netting account, a deal larger than the open volume and in the opposite direction reverses the position. It is recorded as one DEAL_ENTRY_INOUT deal. The position properties documentation states that a reversal keeps POSITION_IDENTIFIER and changes the position ticket, and that reversal does not exist on hedging accounts. The long and the short that replaced it therefore share one position ID, and grouping deals by ID alone would merge them. The DEAL_ENTRY_INOUT case in BuildFromDeals() splits the deal. The part equal to the open volume closes the current segment, and the rest opens the next segment under the same ID with segment one higher. In the sequence above, deal 104 is 1.8 lots against 0.8 open, so 0.8 closes the long and 1.0 opens the short.

The deal's money has to be divided between the two segments, and the reader divides it this way:

  • Profit and swap go to the segment being closed. This is an assumption: the part that opens the new segment has realized nothing yet, and the documentation describes DEAL_SWAP as the cumulative swap on close and DEAL_PROFIT only as the deal's profit. No netting account's history was read to confirm it. If a server booked either field differently, the difference would sit in the wrong segment, and the two segments together would still carry what the deal carried.
  • Commission and fee are split by volume. In the example, 0.8/1.8 of deal 104's commission goes to segment 1 and 1.0/1.8 to segment 2.

The terminal books the commission and the fee on one deal. Splitting them by volume is the library's model, not something the deal's data shows, and giving the whole amount to either segment would be as easy to defend. The two shares add up to the deal's amounts, so a total over both segments is what the terminal booked. Per segment, the figure is not one the terminal shows, and where a broker charges a fixed amount per deal the split is arbitrary.

This branch has not been run on a netting account. It follows the documented deal properties, and the self-test script in the second section runs it on hand-built deals made to the same reading, which shows what the code does and not what a server records. A scale-in by a second order is netting-only as well: on a hedging account a second buy opens a new position with a new ID.

Close-By Pairs

On a hedging account, a close-by closes a buy and a sell on the same symbol against each other. MetaQuotes' description of the hedging system gives its shape: two DEAL_ENTRY_OUT_BY deals, one for each position, each leg closed at the other leg's open price, and the pair's combined result booked on one of the two deals. When the volumes differ, the larger position stays open with the difference. Profit computed from prices counts the result twice. The Verification section shows one such pair on a demo account.

In the self-test pair, a buy opened at 1.10000 and a sell opened at 1.10500, 1.0 lot each of a 100,000-unit contract, are closed by each other. The buy closes at 1.10500, which is 500.00 by price, and the sell closes at 1.10000, which is also 500.00 by price. That makes 1,000.00. The hand-built deals carry 500.00 on one deal and 0.00 on the other, which is the shape described above.

The reader takes profit only from DEAL_PROFIT, so the pair totals 500.00 and nothing is counted twice. An out-by deal takes the same path as an ordinary exit in the walk, so each leg becomes its own record, both with closedBy set. Under this article's unit the pair is two trades, because it is two positions.

That choice has a cost for any figure counted per trade. One leg shows the pair's whole result and the other shows zero, and each leg's exit price is the other leg's open price, not the market price at the time of the close, so a win rate or an average trade counted per record can be shifted by each pair. One merged record per pair is the alternative, and this part does not build it: the record does not hold which position was the other leg. The close_by column marks both rows, so a statistic can set them aside.

Deals That Belong to No Trade

Balance operations, credit, charges, interest, dividends and tax are deals too, and they appear in the same history list as trades. The reader puts none of them into a record. That is a choice, and it has a cost for the ones that can come from holding a position, such as interest or a dividend adjustment: their money is in the account totals and missing from the trade. The first pass sends each one in the range to CountNonTrade(), which keeps a count and a total per deal type:
//+------------------------------------------------------------------+
//| Add one non-trade deal to the total for its type                 |
//+------------------------------------------------------------------+
void CHistoryReader::CountNonTrade(const ENUM_DEAL_TYPE type, const double amount)
  {
   int total = ArraySize(m_nonTrade);
   for(int i = 0; i < total; i++)
     {
      if(m_nonTrade[i].type != type)
         continue;
      m_nonTrade[i].count++;
      m_nonTrade[i].amount += amount;
      return;
     }

   ArrayResize(m_nonTrade, total + 1);
   m_nonTrade[total].type   = type;
   m_nonTrade[total].count  = 1;
   m_nonTrade[total].amount = amount;
  }

The amount is the deal's profit, commission, swap and fee added together. The reader adds all four because it does not assume which field a given type uses. The totals cover the whole account in the range: the magic and symbol filters are tested on records, and a non-trade deal is part of no record.

Canceled deals, DEAL_TYPE_BUY_CANCELED and DEAL_TYPE_SELL_CANCELED, are a separate case. The documentation says that when a deal is canceled, its profit is set to zero and the amount is charged or credited through a separate balance operation. The reader therefore skips the canceled deal inside its position and counts it. The correction shows up among the non-trade totals as the balance operation it is, when it falls inside the range. A position that loses a deal this way can then fail to add up, or look still open, and it is counted under that reason as well.

The Summary Log

//+------------------------------------------------------------------+
//| Print what was built, left out, counted and skipped              |
//+------------------------------------------------------------------+
void CHistoryReader::PrintSummary(void) const
  {
   PrintFormat("TradeAudit: %d deals in range, %d positions found, %d records built",
               m_dealsInRange, m_positionsFound, ArraySize(m_records));
   PrintFormat("TradeAudit: records with more than one exit deal %d, more than one entry deal %d, close-by %d, reversal splits %d",
               m_multiExit, m_multiEntry, m_withCloseBy, m_withReversal);
   PrintFormat("TradeAudit: not exported: %d still open, %d closed outside the range, %d filtered out",
               m_stillOpen, m_outsideRange, m_filteredOut);

//--- Deals that belong to no trade: balance, credit, charges, interest, dividends, taxes
   int types = ArraySize(m_nonTrade);
   if(types == 0)
      Print("TradeAudit: no non-trade deals in the range");
   for(int i = 0; i < types; i++)
      PrintFormat("TradeAudit: non-trade %s: %d deal(s), total %.2f",
                  EnumToString(m_nonTrade[i].type), m_nonTrade[i].count, m_nonTrade[i].amount);

//--- Every skip, by reason
   bool skipped = false;
   for(int r = 0; r < AUDIT_SKIP_REASON_COUNT; r++)
     {
      if(m_skips[r] == 0)
         continue;
      PrintFormat("TradeAudit: skipped %d: %s", m_skips[r], SkipText((ENUM_AUDIT_SKIP)r));
      skipped = true;
     }
   if(!skipped)
      Print("TradeAudit: nothing skipped");
  }

Every line begins with TradeAudit:, so the run can be filtered in the Experts tab. What each line tells you:

LineWhat it counts
deals in range, positions found, records builtDeals the range selected and distinct positions among them, both counted before the filters. Then the records that passed the range and the filters
records with more than one exit deal, more than one entry deal, close-by, reversal splits
Counts of what the deals show, not of why. More than one exit deal is a close in parts, or one closing order filled in several deals. More than one entry deal is a scale-in, or one order filled in several deals. Close-by counts each leg, so one pair adds two. A reversal can produce two records, and each one that is built is counted
not exportedPositions still open, segments closed outside the range, and records the magic or symbol filter removed
non-tradeOne line per non-trade deal type, with its count and total, or a line saying there were none. They cover the whole account in the range, whatever the filters are set to
skippedOne line per skip reason that occurred, in plain words from SkipText(), or "nothing skipped"
Each deal, position or record the reader meets and leaves out is in one of these counts. A position with no readable deal inside the range is never met, and its records would not belong to the file either, because a record is kept by its close time. A closing deal the reader could not read, or one with no position ID, is counted as a skipped deal. When the number of records is not what you expected, the skip and not-exported lines show where the difference went.


Section 2: The Scripts

Installing the Files

Both headers go in MQL5\Include\TradeAudit\, and both scripts go in MQL5\Scripts\. Each script includes the reader with angle brackets, which also brings in the record file:

#include <TradeAudit/HistoryReader.mqh>

The Export Script

input group "Range"
input datetime InpRangeFrom = 0;                        // From, server time (0 = first deal on the account)
input datetime InpRangeTo   = 0;                        // To, server time (0 = now)

input group "Filters"
input long     InpMagicNumber = 0;                      // Magic number (0 = all)
input string   InpSymbolName  = "";                     // Symbol (empty = all)

input group "Output"
input string   InpExportFile      = "TradeAudit.csv";   // CSV file name
input bool     InpUseCommonFolder = false;              // Write to the terminal's common Files folder

The script has six inputs in three groups. Both dates are in server time, the time the deals are stamped with. With both left at zero the script covers every deal the terminal has for the account up to now, and with both filters left at their defaults it keeps every magic number and every symbol. The script has #property script_show_inputs, so the inputs dialog opens each time it is dropped on a chart.

The magic-number filter uses the opening deal's magic number. On a shared netting account, it selects segments opened by an EA, not the deals submitted by that EA. Zero means all magic numbers, so trades whose own magic number is zero, such as the positions opened by hand for the Verification run, cannot be selected by the filter: export with the filter at zero and keep the rows whose magic column is 0. A separate on/off input would remove that limit at the price of a seventh input. The symbol filter ignores case and otherwise needs the symbol's exact name, including any suffix the broker adds.

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   datetime to = (InpRangeTo == 0) ? TimeTradeServer() : InpRangeTo;

   CHistoryReader reader;
   if(!reader.Rebuild(InpRangeFrom, to, InpMagicNumber, InpSymbolName))
      return;
   reader.PrintSummary();

   string path;
   int    written = WriteCsv(reader, path);
   if(written >= 0)
      PrintFormat("TradeAudit: %d records written to %s", written, path);
  }

A zero end date becomes the current trade server time. The script rebuilds, prints the summary, writes the file, and prints the full path of the file it wrote.

//+------------------------------------------------------------------+
//| One row per record; returns rows written, or -1 on failure       |
//+------------------------------------------------------------------+
int WriteCsv(const CHistoryReader &reader, string &path)
  {
   int flags = FILE_WRITE | FILE_CSV | FILE_ANSI;
   if(InpUseCommonFolder)
      flags |= FILE_COMMON;

   path = (InpUseCommonFolder ? TerminalInfoString(TERMINAL_COMMONDATA_PATH) + "\\Files\\"
                              : TerminalInfoString(TERMINAL_DATA_PATH) + "\\MQL5\\Files\\") + InpExportFile;

   int handle = FileOpen(InpExportFile, flags, ',');
   if(handle == INVALID_HANDLE)
     {
      PrintFormat("TradeAudit: cannot open %s, error %d", path, GetLastError());
      return(-1);
     }

   FileWrite(handle, "position_id", "segment", "symbol", "magic", "direction", "open_time", "close_time",
             "entry_deals", "exit_deals", "volume_in", "volume_out", "entry_price", "exit_price",
             "close_by", "reversal", "profit", "commission", "swap", "fee", "net");

   SAuditRecord rec;
   int          total   = reader.Total();
   int          written = 0;
   int          failed  = 0;
   for(int i = 0; i < total; i++)
     {
      if(!reader.RecordAt(i, rec))
         continue;
      //--- Volumes, prices and money go through NumberText()
      uint bytes = FileWrite(handle, rec.positionId, rec.segment, rec.symbol, rec.magic,
                             (rec.type == POSITION_TYPE_BUY) ? "buy" : "sell",
                             TimeToString(rec.openTime, TIME_DATE | TIME_SECONDS),
                             TimeToString(rec.closeTime, TIME_DATE | TIME_SECONDS),
                             rec.entryDeals, rec.exitDeals,
                             NumberText(rec.volumeIn), NumberText(rec.volumeOut),
                             NumberText(rec.entryPrice), NumberText(rec.exitPrice),
                             rec.closedBy ? 1 : 0, (rec.openedByReversal || rec.closedByReversal) ? 1 : 0,
                             NumberText(rec.profit), NumberText(rec.commission), NumberText(rec.swap),
                             NumberText(rec.fee), NumberText(rec.Net()));
      if(bytes > 0)
         written++;
      else
         failed++;
     }

   FileClose(handle);
   if(failed > 0)
      PrintFormat("TradeAudit: %d row(s) could not be written to %s", failed, path);
   return(written);
  }

The file goes to MQL5\Files\ in the terminal's data folder, or to the Files folder shared by all terminals on the computer when InpUseCommonFolder is on. A file of the same name is overwritten without a prompt. If the file cannot be opened, for example because a spreadsheet has it open, the script prints the path and the error code and writes nothing. A row that cannot be written is counted, and one line reports how many.

The separator is a comma, numbers use a dot as the decimal mark, and the file is single-byte ANSI text in the computer's Windows code page. All three are fixed, so that the script needs no settings for them. A spreadsheet whose regional settings use a comma for decimals may need to bring the file in through its import dialog, and a symbol name with a character outside the code page may not be written faithfully.

Volumes, prices and money go through NumberText(), which writes at most eight decimals and drops trailing zeros. A double printed at full precision can carry noise in its last digits, and a volume-weighted price rounded to eight decimals does not. The file has twenty columns:

//+------------------------------------------------------------------+
//| A number as text: eight decimals at most, trailing zeros dropped |
//+------------------------------------------------------------------+
string NumberText(const double value)
  {
   string text = DoubleToString(value, 8);
   int    last = StringLen(text) - 1;
   while(last > 0 && StringGetCharacter(text, last) == '0')
      last--;
   if(StringGetCharacter(text, last) == '.')
      last--;
   text = StringSubstr(text, 0, last + 1);
   return((text == "-0") ? "0" : text);
  }
ColumnsMeaning
position_id, segmentWhich trade: the position ID, and the segment within it after a reversal
symbol, magic, directionThe symbol, the magic number of the opening deal, and buy or sell
open_time, close_timeServer time of the first entry and of the deal that brought the volume to zero
entry_deals, exit_dealsAbove 1: more than one deal on that side. A scale-in or a close in parts, or one order filled in several deals
volume_in, volume_outLots in and lots out, equal within the walk's tolerance for every exported record
entry_price, exit_priceVolume-weighted over the entry deals and over the exit deals
close_by, reversal1 when an exit was a close-by, or when a reversal opened or closed the segment
profit, commission, swap, feeSummed over the trade's deals, in the account currency, with a reversal deal divided as Section 1 describes. profit leaves the other three out
netprofit + commission + swap + fee

On a first run, open the file and compare it with the summary lines: the number of data rows equals the records-built count, and volume_in matches volume_out on every row.

The Self-Test Script

The netting branches, the scale-in and the reversal, cannot be exercised on a hedging account, and close-by cannot be exercised on a netting one. The walk, however, only reads the deal fields it is given, so hand-built deals in the documented shape can go through the same walk a real rebuild uses: BuildFromDeals() and the functions it calls. The two history passes and the sort come before the walk, and the script exercises neither. That is why Prepare() and BuildFromDeals() are public.

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   CHistoryReader reader;
//--- A wide range and no filters, so every hand-built segment is kept
   reader.Prepare(0, D'3000.01.01', 0, "");

//--- Netting: open 1.0, add 0.5, close 0.7, reverse with 1.8, close the 1.0 short.
//--- Profits are what a 100,000-unit contract would book against the position's average price.
   SAuditDeal netting[];
   AddDeal(netting, 101, D'2026.01.05 10:00', DEAL_TYPE_BUY,  DEAL_ENTRY_IN,    1.0, 1.10000,   0.00, -3.50,  0.00);
   AddDeal(netting, 102, D'2026.01.05 11:00', DEAL_TYPE_BUY,  DEAL_ENTRY_IN,    0.5, 1.10200,   0.00, -1.75,  0.00);
   AddDeal(netting, 103, D'2026.01.05 12:00', DEAL_TYPE_SELL, DEAL_ENTRY_OUT,   0.7, 1.10500, 303.33, -2.45,  0.00);
   AddDeal(netting, 104, D'2026.01.06 09:00', DEAL_TYPE_SELL, DEAL_ENTRY_INOUT, 1.8, 1.10300, 186.67, -6.30, -1.20);
   AddDeal(netting, 105, D'2026.01.06 15:00', DEAL_TYPE_BUY,  DEAL_ENTRY_OUT,   1.0, 1.10000, 300.00, -3.50,  0.00);
   reader.BuildFromDeals(9001, "EURUSD", netting);

//--- Hedging close-by: each leg closes at the other's open price, and one deal carries the whole result
   SAuditDeal legA[];
   AddDeal(legA, 201, D'2026.01.07 10:00', DEAL_TYPE_BUY,  DEAL_ENTRY_IN,     1.0, 1.10000,   0.00, 0.00, 0.00);
   AddDeal(legA, 203, D'2026.01.07 14:00', DEAL_TYPE_SELL, DEAL_ENTRY_OUT_BY, 1.0, 1.10500, 500.00, 0.00, 0.00);
   reader.BuildFromDeals(9002, "EURUSD", legA);

   SAuditDeal legB[];
   AddDeal(legB, 202, D'2026.01.07 11:00', DEAL_TYPE_SELL, DEAL_ENTRY_IN,     1.0, 1.10500,   0.00, 0.00, 0.00);
   AddDeal(legB, 204, D'2026.01.07 14:00', DEAL_TYPE_BUY,  DEAL_ENTRY_OUT_BY, 1.0, 1.10000,   0.00, 0.00, 0.00);
   reader.BuildFromDeals(9003, "EURUSD", legB);

//--- What was rebuilt
   SAuditRecord rec;
   for(int i = 0; i < reader.Total(); i++)
     {
      if(!reader.RecordAt(i, rec))
         continue;
      PrintFormat("TradeAudit self-test: position %I64d segment %d %s, in %.2f @ %.5f (%d deal(s)), out %.2f @ %.5f (%d deal(s)), profit %.2f, commission %.2f, swap %.2f",
                  rec.positionId, rec.segment, (rec.type == POSITION_TYPE_BUY) ? "buy" : "sell",
                  rec.volumeIn, rec.entryPrice, rec.entryDeals, rec.volumeOut, rec.exitPrice, rec.exitDeals,
                  rec.profit, rec.commission, rec.swap);
     }

//--- The expected values, worked out by hand from the deals above
   int failures = Check(reader.Total() == 4, "four records: two netting segments, two close-by legs");

   reader.RecordAt(0, rec);
   failures += Check(rec.segment == 1 && rec.type == POSITION_TYPE_BUY && rec.entryDeals == 2 && rec.exitDeals == 2,
                     "segment 1 is the long: one scale-in, closed in two parts");
   failures += Check(Near(rec.volumeIn, 1.5, 1e-8) && Near(rec.volumeOut, 1.5, 1e-8), "segment 1: 1.5 lots in, 1.5 lots out");
   failures += Check(Near(rec.entryPrice, 1.1006667, 1e-7) && Near(rec.exitPrice, 1.1039333, 1e-7),
                     "segment 1: volume-weighted entry and exit");
   failures += Check(Near(rec.profit, 490.00, 0.005) && Near(rec.commission, -10.50, 0.005) && Near(rec.swap, -1.20, 0.005),
                     "segment 1: profit and swap in full, 0.8/1.8 of the reversal's commission");

   reader.RecordAt(1, rec);
   failures += Check(rec.segment == 2 && rec.type == POSITION_TYPE_SELL && rec.openedByReversal && Near(rec.volumeIn, 1.0, 1e-8),
                     "segment 2 is the short the reversal opened, same position ID");
   failures += Check(Near(rec.entryPrice, 1.10300, 1e-7) && Near(rec.profit, 300.00, 0.005) && Near(rec.commission, -7.00, 0.005),
                     "segment 2: the reversal price, its own profit, 1.0/1.8 of the reversal's commission");

   SAuditRecord other;
   reader.RecordAt(2, rec);
   reader.RecordAt(3, other);
   failures += Check(rec.closedBy && other.closedBy && Near(rec.profit + other.profit, 500.00, 0.005),
                     "close-by: 500.00 across both legs, not counted twice");

   PrintFormat("TradeAudit self-test: %s, %d check(s) failed", (failures == 0) ? "all checks passed" : "FAILED", failures);
  }

Prepare() sets a range wide enough to keep every hand-built segment and switches both filters off. AddDeal() appends one deal with the given ticket, time, type, entry type, volume, price, profit, commission and swap; its fee is zero and its magic number is zero. The netting sequence is the one in the table under The Running Volume in Section 1, with profits set to what a 100,000-unit contract would book against the position's average price. The close-by pair is the one under Close-By Pairs.

The expected values in the checks were worked out by hand from those deals:

RecordExpectedHow it follows from the deals
Segment 1, long2 entries, 2 exits, 1.5 lots in and outDeals 101 and 102 in; 103 and the 0.8 closing share of 104 out
Entry 1.1006667, exit 1.1039333The weighted averages shown under The Running Volume in Section 1
Profit 490.00, commission −10.50, swap −1.20303.33 + 186.67; −3.50 − 1.75 − 2.45 − 6.30 × 0.8/1.8; the in-out deal's swap
Segment 2, shortOpened by reversal, 1.0 lot at 1.10300The 1.0 opening share of 104
Profit 300.00, commission −7.00Deal 105's profit; −6.30 × 1.0/1.8 − 3.50
Close-by legsBoth flagged, profits summing to 500.00500.00 on deal 203 and 0.00 on deal 204

The script prints each record, then one PASS or FAIL line per check, eight in all, then a final line that says whether every check passed. It reads no history and trades nothing, so it can run on any account, demo or live. Its output is real output from the real walk, run on hand-built input.

It is not a test on a netting account's own records. The deals and the expected values rest on the same reading of the documentation, so on that point the check is circular: a pass shows that the code does what this article describes, not that the description matches what a broker records. The checks also cover accepted paths only. The script does not exercise the two history passes, the sort, the range test, the filters, the refusals, a position left open, canceled deals, the fee split or a failed allocation.


Verification

Two runs stand behind this article, and they do not show the same kind of thing. Run 1 compares the export with the terminal's own report on a hedging demo account, so it tests the reader against records the platform made. Run 2 is the self-test, which tests the code against this article's reading of the documentation, and it is the only place the netting branches were run. Both were made after the four files compiled with no errors and no warnings. What stands behind each path:

What the reader has to handleWhat stands behind it here
A position with one entry deal and one exit deal124 positions across 11 symbols, compared with the terminal's report in Run 1
A close in partsOne position in Run 1, and the hand-built long in Run 2
A close-by pair of equal volumesOne pair in Run 1, and one hand-built pair in Run 2
A scale-in by a second order, a reversal, and the split of its commissionHand-built deals in Run 2 only
Swap8 records in Run 1. On a reversal: hand-built in Run 2 only
Commission and feeThe account in Run 1 charged neither. Hand-built commissions are summed in Run 2, and no fee was run
More than one entry deal from one order, a close-by of unequal volumes, a canceled deal, a position that crosses either end of the rangeDid not occur in Run 1, and not hand-built
The two filters, the refusals of the walk, the tie-break of the sortNot tested

Run 1: the export against the terminal's report. AuditExport was run on a MetaQuotes-Demo hedging account over 2026.07.15 to 2026.10.13, with both filters off. Before the run, one position was closed in two parts and one pair of positions was closed by each other, so that the range held both shapes. The lines the run printed:

TradeAudit: range 2026.07.15 00:00 to 2026.10.13 00:00, magic all, symbol all, account ACCOUNT_MARGIN_MODE_RETAIL_HEDGING
TradeAudit: 255 deals in range, 127 positions found, 127 records built
TradeAudit: records with more than one exit deal 1, more than one entry deal 0, close-by 2, reversal splits 0
TradeAudit: not exported: 0 still open, 0 closed outside the range, 0 filtered out
TradeAudit: no non-trade deals in the range
TradeAudit: nothing skipped
TradeAudit: 127 records written to MetaQuotes\Terminal\Common\Files\TradeAudit.csv

The last line is shown with the start of its path cut. The History tab was then set to the same period and its report saved. The report describes the period three ways: a Positions table, where the terminal groups each position's deals into one row, a Deals table, and a Results block.

The reader and the terminal do not choose positions by the same rule. The terminal's help says the positions view includes a position when its opening or its closing date falls in the selected period, and the reader keeps a trade by its close time alone. In this run nothing straddles either end of the range: the summary reports 0 still open and 0 closed outside the range. The two counts should therefore be equal.

Run 1ReaderTerminal's reportDifference
Positions127 records built127 rows in the Positions tableNone. The same 127 position IDs
Deals255 deals in range255 rows in the Deals tableNone
Profit4,623.964,623.96None
Commission and fee0.00 and 0.000.00 and 0.00None
Swap−24.57−24.57None
Net4,599.394,599.39, as Total Net ProfitNone
Trade count127 records128, as Total TradesOne, explained below

The money rows are the weakest evidence in that table: an export with one row per closing deal would match them as well. What tests the records is the comparison row by row. Each of the 127 rows of the file was compared with its row in the report's Positions table on ten fields: symbol, direction, open time, close time, volume, entry price, exit price, commission, swap and profit. All of them agree, with prices compared to the digits the report prints. This is one account on one broker's server, and the agreement covers the shapes in the table above and no others.

The one difference is in the Results block. It reports 128 trades, where the same report's Positions table has 127 rows. The report's Deals table holds 128 closing deals, 126 out and 2 out-by, and the position closed in two parts accounts for two of them. The block's count of long trades is 62, against 61 long positions in the file. A trade count taken from that block counts that position twice. The two counts use different units: the block's equals the number of closing deals, and the file's is the number of positions.

The position closed in parts is 10914462523, a 1.00 lot buy at 1.11567 closed by two deals of 0.50 at 1.11576. Its row in the file:

10914462523,1,EURUSD,0,buy,2026.10.12 19:51:31,2026.10.12 19:55:54,1,2,1,1,1.11567,1.11576,0,0,9,0,0,0,9

exit_deals is 2, and the profit of 9.00 is the sum of 4.50 from each of the two deals. The report's Positions table shows the same position as one row, with the same prices and 9.00. The close-by pair is a 1.00 lot sell opened at 1.11579 and a 1.00 lot buy opened at 1.11587:

10914532509,1,EURUSD,0,sell,2026.10.12 19:56:21,2026.10.12 19:58:54,1,1,1,1,1.11579,1.11587,1,0,-8,0,0,0,-8
10914565599,1,EURUSD,0,buy,2026.10.12 19:58:41,2026.10.12 19:58:54,1,1,1,1,1.11587,1.11579,1,0,0,0,0,0,0

Both rows have close_by at 1, and each row's exit price is the other row's entry price. The pair's result of −8.00 is on one row and the other shows 0, which is how the terminal booked it on the two out-by deals. Computed from prices, each leg would show −8.00, which is −16.00 for a pair that lost 8.00.

Run 2: the self-test. AuditSelfTest was run on the same account. It printed the four records, the eight checks and the final line:

TradeAudit self-test: position 9001 segment 1 buy, in 1.50 @ 1.10067 (2 deal(s)), out 1.50 @ 1.10393 (2 deal(s)), profit 490.00, commission -10.50, swap -1.20
TradeAudit self-test: position 9001 segment 2 sell, in 1.00 @ 1.10300 (1 deal(s)), out 1.00 @ 1.10000 (1 deal(s)), profit 300.00, commission -7.00, swap 0.00
TradeAudit self-test: position 9002 segment 1 buy, in 1.00 @ 1.10000 (1 deal(s)), out 1.00 @ 1.10500 (1 deal(s)), profit 500.00, commission 0.00, swap 0.00
TradeAudit self-test: position 9003 segment 1 sell, in 1.00 @ 1.10500 (1 deal(s)), out 1.00 @ 1.10000 (1 deal(s)), profit 0.00, commission 0.00, swap 0.00
TradeAudit self-test: PASS  four records: two netting segments, two close-by legs
TradeAudit self-test: PASS  segment 1 is the long: one scale-in, closed in two parts
TradeAudit self-test: PASS  segment 1: 1.5 lots in, 1.5 lots out
TradeAudit self-test: PASS  segment 1: volume-weighted entry and exit
TradeAudit self-test: PASS  segment 1: profit and swap in full, 0.8/1.8 of the reversal's commission
TradeAudit self-test: PASS  segment 2 is the short the reversal opened, same position ID
TradeAudit self-test: PASS  segment 2: the reversal price, its own profit, 1.0/1.8 of the reversal's commission
TradeAudit self-test: PASS  close-by: 500.00 across both legs, not counted twice
TradeAudit self-test: all checks passed, 0 check(s) failed

Every check passed. The four record lines carry the values worked out by hand in Section 2, with prices printed to five decimals. A pass means the code computes what this article says it should for these deals, and it cannot show that a broker's netting records have that shape.


What This Part Does Not Do

Each limit is stated where its design is introduced. In short:

  • Netting. The scale-in and reversal branches were run only on hand-built deals made to the same reading of the documentation as the expected values, not on a netting account's records. That a reversal deal's profit and swap belong to the closing segment, and that deals in one millisecond ran in ticket order, are assumptions.
  • Evidence. The comparison with the terminal is one run on one hedging demo account, for the shapes its history held, with no commission or fee charged.
  • The unit. A trade is a position or a netting segment. A close-by pair is two, one with the pair's whole result and one with zero, and the record does not link them.
  • Magic number. One per record, the opener's. On a netting account, deals other EAs added count toward that record. Zero cannot be selected by the filter.
  • Deal counts. More than one entry or exit deal can be a scale-in or a close in parts, or one order filled in several deals.
  • Reversal costs. Commission and fee are divided between the two segments by volume, a model the library chose.
  • The range. A record belongs by its close time, the end of the range excluded. Positions still open and segments closed outside the range are counted and left out with their exits, so a file's total can differ from the profit realized in the range.
  • Whole-account figures. The non-trade totals and the counts of deals and positions ignore the filters. A cost booked as a deal of its own is in those totals and in no record.
  • History. What the account no longer holds cannot be rebuilt. A position whose deals do not add up, or that meets an unknown entry type, is left out from that deal on. A canceled deal can put its position there, or leave it counted as still open.
  • Mechanics. One history query per position and an insertion sort suit a script, not every tick. The volume tolerance is a fixed 1e-8 lots. BuildFromDeals(), called directly, expects deals oldest first and Prepare() first.
  • The file. Commas, decimal dots and single-byte ANSI text are fixed, and the export overwrites a file of the same name. Times are server time, and money is in the account currency.

Conclusion

The account stores deals, and a trade is something a program rebuilds from them. This part built that rebuild as a small include library. It collects every position that has a buy or sell deal in the range, loads all the deals history still holds for each, sorts them by time, and walks them with a running volume: entries add, exits subtract, and the deal that brings the volume back to zero closes the record. Prices come out volume-weighted, and every deal's profit, commission, swap and fee is added to the trade it belongs to.

Each case named in this part has a place in that walk. A close in parts and a scale-in are ordinary steps of the running volume. A netting reversal is split into two records under one position ID, with its commission and fee divided by volume, which is a model the library chose. A close-by pair becomes two records that take their result from the deals, so the result is counted once and sits on one of the two. Non-trade deals go to account totals, canceled deals are counted and passed over, and a position whose deals do not add up is left out from that deal on, with a reason.

The library comes with two scripts. The export writes one CSV row per record, and on one hedging demo account its 127 rows agreed with the terminal's own report, position by position. The self-test runs the netting and close-by paths of the walk on hand-built deals, so that code can be run on any account. It does not compare them with a netting account's records.

The source files are attached below.

FilenameDescription
AuditRecord.mqhThe record for one rebuilt trade, and the total for one type of non-trade deal.
HistoryReader.mqhCHistoryReader: rebuilds closed trades from deal history, with partial closes, scale-ins, netting reversals, close-by pairs and a count for what it leaves out.
AuditExport.mq5Script that rebuilds a date range and writes one CSV row per trade.
AuditSelfTest.mq5Script that runs hand-built netting and close-by deals through the same rebuild and checks the results.
MQL5.zipArchive containing the four source files, arranged in the required MQL5 terminal directory structure.
Attached files |
AuditRecord.mqh (2.7 KB)
HistoryReader.mqh (22.52 KB)
AuditExport.mq5 (4.95 KB)
AuditSelfTest.mq5 (6.64 KB)
MQL5.zip (11.16 KB)
Features of Custom Indicators Creation Features of Custom Indicators Creation
Creation of Custom Indicators in the MetaTrader trading system has a number of features.
Aggregating Economic Calendar Events into a Structured MQL5 Data Feed Aggregating Economic Calendar Events into a Structured MQL5 Data Feed
The package builds a news feed from CalendarValueHistory(): it filters by impact and currency, maps events to a symbol universe, and stores them in a time‑sorted array with minutes to event. You can query GetNextEvent() and IsInNewsWindow() to implement deterministic news filtering in an EA. An abstract source and clock, plus terminal and fake implementations, enable testing when calendar functions are unavailable in the Strategy Tester.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Building a PDF Creation Library in MQL5 (Part 4): Lines Boxes and Color Building a PDF Creation Library in MQL5 (Part 4): Lines Boxes and Color
The article turns drawing primitives into PDF output: one cm flip installs a top‑left, y‑down system, while CPdfPage writes m/l/c/h/re, S/f/B, W n, and transforms from calls on CPdfSurface. PdfColor keeps RGB bytes and fixes MQL5 byte order when writing fractions. It also covers caps, joins, dashes, clipping, and Bezier circles. Demos include a printable ruler, a feature sampler, and a ready letterhead script.