preview
Building a Price Ladder Aggregator for Depth-of-Market Analysis in MQL5

Building a Price Ladder Aggregator for Depth-of-Market Analysis in MQL5

MetaTrader 5 — Trading systems |
132 0
Ushana Kevin Iorkumbul
Ushana Kevin Iorkumbul

Introduction

The terminal exposes the Depth of Market (DOM) through MarketBookGet(), which fills an array of MqlBookInfo structures. Each entry carries a type, a price, and a volume. The array is flat, so the same price can appear in several entries, and the documentation page does not promise any order.

A flat array is hard to read. Useful questions need a price ladder: volume grouped by price level, cumulative volume outward from the best prices, and the largest levels marked. This article builds that aggregation and shows it on a live panel drawn with CCanvas.

Before the code, note two constraints. First, a server may provide no DOM data for a symbol. The subscription can fail with error 4901. The snapshot may be empty or may contain too few valid levels. The indicator reports these cases on the panel as "DOM unavailable" or "No DOM data", and it does not draw an empty ladder as if it were real data. The minimum number of levels is the input InpMinLevels, and it counts both sides together.

Second, the Strategy Tester does not replay DOM data in the way the live terminal provides it. The demonstration is therefore live only, and this article does not suggest backtesting the result.

A DOM snapshot is a list of price levels with volumes, mostly limit orders resting in the book. The structure also has entry types for market orders, which this code counts but does not draw. A snapshot is not a record of trades, and the panel draws no conclusion about intent. In this article, the book is the depth of market of one symbol, and a snapshot is one reading of it with MarketBookGet().

The solution subscribes via MarketBookAdd(). It reads a snapshot in OnInit() and on every OnBookEvent() update, then releases the subscription with MarketBookRelease(). Logic classes are separated from terminal-facing code. The logic is covered by a dedicated test script.


How the Ladder Is Built

What the snapshot contains

Each MqlBookInfo entry has a type from ENUM_BOOK_TYPE, a price, a volume stored as a long integer, and a more precise field named volume_real. BOOK_TYPE_BUY entries become bid levels and BOOK_TYPE_SELL entries become ask levels. Market-order entries are counted in the footer but not drawn, because a market order does not rest at a price level, and the documentation does not describe their fields.

The code uses volume_real when it is nonzero and volume otherwise, in the units the broker reports. A snapshot lists price levels and not trades, so the panel never states why a level appeared or disappeared.

Building the ladder

The builder sorts entries by price and sums volumes for identical prices. The input InpLevelTicks groups prices into buckets of that many ticks. Bids round down and asks round up. For prices on the tick grid and a book that is not crossed, a bucket therefore stays on its own side of the spread. With five ticks per level, bid tick indexes 10 through 14 map to 10, and ask tick indexes 11 through 15 map to 15.

Bucketing with five ticks per level

Figure 1: Bucketing with five ticks per level. Blue bids round down to bucket 10, and orange asks round up to bucket 15.

Cumulative volume runs outward from the best price on each side. The spread strip uses the unbucketed best bid and ask. If a side is missing or the snapshot is unavailable, the panel shows it as unavailable (not zero). Entries with unusable price or volume are skipped and counted in the footer.

Synthetic volumes and cumulative values

Figure 2: Synthetic volumes and cumulative values. The dark segment is the volume added by each level, and the light bar is the running total growing away from the spread.

Clusters

A cluster is one of the three largest levels by volume on one side of the book. When two volumes are equal within 1e-9, the level closer to the market ranks first. A side with fewer than three levels gets fewer clusters.

Clusters

Figure 3: The three largest levels on each side are marked C1 to C3 by volume. The smallest level is not a cluster.

The ranking is a heuristic about the snapshot. It does not identify support, resistance, or liquidity.

Class structure

ProcessBook() asks the reader for a snapshot, and it is called from OnInit() and from OnBookEvent(). The change detector, builder, cluster finder, and panel then run in that order. The indicator wires them together in OnInit(), OnDeinit(), and OnChartEvent().

Only the reader class calls the book and symbol functions. The ladder, builder, cluster finder, and change detector call no terminal functions, so they can be tested without a feed. The panel draws on the chart, so it is terminal-facing code.

The class structure

Figure 4: The class structure. A snapshot passes from MarketBookGet() through the reader, change detector, ladder builder, ladder, cluster finder, and panel. The indicator on the left creates and wires the classes.


Shared Types: DomTypes.mqh

The first file defines the status enumeration, the level structure, and the statistics structure. The status values separate "no book yet", "subscription failed", "read failed", "no usable data", and "data OK", so the panel does not have to guess which condition it is showing.

The level structure stores the price both as a double and as a tick index, so sorting and bucket comparisons are integer comparisons. The index is exact only when the price lies on the tick grid. The statistics structure carries the counters of accepted and skipped entries that the panel footer reports.

//+------------------------------------------------------------------+
//|                                                     DomTypes.mqh |
//+------------------------------------------------------------------+
#ifndef DOM_TYPES_MQH
#define DOM_TYPES_MQH

//--- tolerance used when two volumes are compared for a tie
#define DOM_VOLUME_EPS     1.0e-9
//--- number of clusters marked on each side of the book
#define DOM_CLUSTER_COUNT  3

//+------------------------------------------------------------------+
//| Data status shown in the panel header                            |
//+------------------------------------------------------------------+
enum ENUM_DOM_STATUS
  {
   DOM_STATUS_WAITING          = 0,   // no book has been processed yet
   DOM_STATUS_SUBSCRIBE_FAILED = 1,   // ::MarketBookAdd() returned false
   DOM_STATUS_READ_FAILED      = 2,   // ::MarketBookGet() failed or data could not be processed
   DOM_STATUS_NO_DATA          = 3,   // empty book or too few valid levels
   DOM_STATUS_OK               = 4    // a usable ladder was built
  };

//+------------------------------------------------------------------+
//| One price level of the ladder                                    |
//| cluster_rank: 0 is a placeholder meaning "not a cluster"         |
//+------------------------------------------------------------------+
struct SDomLevel
  {
   long              tick_index;      // price level expressed as a tick count
   double            price;           // price of the level
   double            volume;          // summed volume at the level
   double            cum_volume;      // cumulative volume outward from the best price of its side
   bool              is_bid;          // true for the bid side, false for the ask side
   int               cluster_rank;    // 0 = not a cluster, 1..3 = rank within its side
  };

//+------------------------------------------------------------------+
//| Counters filled while one snapshot is aggregated                 |
//+------------------------------------------------------------------+
struct SDomStats
  {
   int               total_entries;   // entries in the raw snapshot
   int               used_entries;    // entries accepted for aggregation, counted before equal prices are merged into levels
   int               skipped_price;   // invalid or non-positive price
   int               skipped_volume;  // negative or non-finite volume
   int               skipped_zero;    // zero volume
   int               market_orders;   // BOOK_TYPE_SELL_MARKET and BOOK_TYPE_BUY_MARKET entries
   int               unknown_type;    // type value outside ENUM_BOOK_TYPE
  };

#endif
//+------------------------------------------------------------------+


Storing Levels and Cumulative Volume: CDomLadder

CDomLadder is a container. It stores the levels in display order, with all asks first and then all bids, so one array represents the whole ladder. The class declaration follows, and then each method.

//+------------------------------------------------------------------+
//|                                                    DomLadder.mqh |
//+------------------------------------------------------------------+
#ifndef DOM_LADDER_MQH
#define DOM_LADDER_MQH

#include "DomTypes.mqh"

//+------------------------------------------------------------------+
//| Container for one aggregated ladder                              |
//| Levels are stored in display order: asks first (highest price    |
//| to best ask), then bids (best bid to lowest price).              |
//+------------------------------------------------------------------+
class CDomLadder
  {
private:
   //--- levels in display order: asks first, then bids
   SDomLevel         m_levels[];
   int               m_count;
   int               m_ask_count;
   int               m_bid_count;
   //--- counters of the last aggregation, shown in the panel footer
   SDomStats         m_stats;
   //--- unbucketed best prices, kept so the spread is not changed by bucketing
   long              m_raw_best_bid;    // valid only when m_has_raw_bid is true
   long              m_raw_best_ask;    // valid only when m_has_raw_ask is true
   bool              m_has_raw_bid;
   bool              m_has_raw_ask;
public:
                     CDomLadder(void);
                    ~CDomLadder(void);
   bool              Clear(void);
   bool              ClearLevels(void);
   bool              AppendLevel(const SDomLevel &level);
   bool              SetStats(const SDomStats &stats);
   bool              GetStats(SDomStats &stats) const;
   bool              SetRawBest(const bool has_bid,const long bid_index,const bool has_ask,const long ask_index);
   int               Count(void) const;
   int               AskCount(void) const;
   int               BidCount(void) const;
   bool              GetLevel(const int index,SDomLevel &level) const;
   bool              SetClusterRank(const int index,const int rank);
   bool              ComputeCumulative(void);
   bool              GetSpreadTicks(long &ticks) const;
   bool              IsCrossed(void) const;
   bool              VisibleRows(const int max_rows,int &ask_rows,int &bid_rows) const;
   int               HiddenClusters(const int ask_rows,const int bid_rows) const;
  };

The constructor clears the object. The destructor has nothing to release.

//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CDomLadder::CDomLadder(void)
  {
//--- start empty, so no member is left uninitialized
   Clear();
  }
//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CDomLadder::~CDomLadder(void)
  {
  }

Clear() removes the levels, the raw best prices, and the statistics.

//+------------------------------------------------------------------+
//| Remove levels, best prices and statistics                        |
//+------------------------------------------------------------------+
bool CDomLadder::Clear(void)
  {
//--- levels and best prices first, then the counters
   ClearLevels();
   m_stats.total_entries  = 0;
   m_stats.used_entries   = 0;
   m_stats.skipped_price  = 0;
   m_stats.skipped_volume = 0;
   m_stats.skipped_zero   = 0;
   m_stats.market_orders  = 0;
   m_stats.unknown_type   = 0;
   return(true);
  }

ClearLevels() removes the levels and the raw best prices but keeps the statistics. The builder uses it when a snapshot turns out to have too few levels, so the footer counters survive while no ladder is drawn.

//+------------------------------------------------------------------+
//| Remove levels and best prices but keep the statistics            |
//+------------------------------------------------------------------+
bool CDomLadder::ClearLevels(void)
  {
//--- only the counts are reset; the array keeps its memory for the next build
   m_count        = 0;
   m_ask_count    = 0;
   m_bid_count    = 0;
   m_raw_best_bid = 0;
   m_raw_best_ask = 0;
   m_has_raw_bid  = false;
   m_has_raw_ask  = false;
   return(true);
  }

AppendLevel() adds one level. It refuses an ask after a bid has been added, which protects the asks-first order. The array grows with ArrayResize(), which returns the new size or -1 on failure, and ArraySize() tells the method when growth is needed.

//+------------------------------------------------------------------+
//| Append a level; asks must be appended before bids                |
//+------------------------------------------------------------------+
bool CDomLadder::AppendLevel(const SDomLevel &level)
  {
//--- an ask after a bid would break the asks-first order that the rest of the code relies on
   if(!level.is_bid && m_bid_count>0)
      return(false);
//--- grow in blocks of 64 elements, so the array is not resized for every level
   if(m_count>=::ArraySize(m_levels))
     {
      if(::ArrayResize(m_levels,m_count+1,64)<0)
         return(false);
     }
//--- store the level and update the count of its side
   m_levels[m_count]=level;
   m_count++;
   if(level.is_bid)
      m_bid_count++;
   else
      m_ask_count++;
   return(true);
  }

SetStats() and GetStats() store and copy the counters of the last aggregation.

//+------------------------------------------------------------------+
//| Store the counters of the last aggregation                       |
//+------------------------------------------------------------------+
bool CDomLadder::SetStats(const SDomStats &stats)
  {
   m_stats=stats;
   return(true);
  }
//+------------------------------------------------------------------+
//| Copy the counters of the last aggregation                        |
//+------------------------------------------------------------------+
bool CDomLadder::GetStats(SDomStats &stats) const
  {
   stats=m_stats;
   return(true);
  }

SetRawBest() stores the unbucketed best bid and best ask as tick indexes, together with flags that say whether each side exists. The indexes are meaningful only when the matching flag is true.

//+------------------------------------------------------------------+
//| Store the unbucketed best bid and best ask as tick indexes       |
//+------------------------------------------------------------------+
bool CDomLadder::SetRawBest(const bool has_bid,const long bid_index,const bool has_ask,const long ask_index)
  {
   m_has_raw_bid  = has_bid;
   m_has_raw_ask  = has_ask;
   m_raw_best_bid = bid_index;
   m_raw_best_ask = ask_index;
   return(true);
  }

The three count methods return the number of levels in total, on the ask side, and on the bid side.

//+------------------------------------------------------------------+
//| Number of levels                                                 |
//+------------------------------------------------------------------+
int CDomLadder::Count(void) const
  {
   return(m_count);
  }
//+------------------------------------------------------------------+
//| Number of ask levels                                             |
//+------------------------------------------------------------------+
int CDomLadder::AskCount(void) const
  {
   return(m_ask_count);
  }
//+------------------------------------------------------------------+
//| Number of bid levels                                             |
//+------------------------------------------------------------------+
int CDomLadder::BidCount(void) const
  {
   return(m_bid_count);
  }

GetLevel() copies one level out and returns false for an index that is out of range, so a caller can tell a missing level from a real one.

//+------------------------------------------------------------------+
//| Copy one level out; false when the index is out of range         |
//+------------------------------------------------------------------+
bool CDomLadder::GetLevel(const int index,SDomLevel &level) const
  {
//--- an invalid index is reported, so the caller can tell a missing level from a real one
   if(index<0 || index>=m_count)
      return(false);
   level=m_levels[index];
   return(true);
  }

SetClusterRank() writes the rank of one level. In this code only the cluster finder calls it.

//+------------------------------------------------------------------+
//| Set the cluster rank of one level                                |
//+------------------------------------------------------------------+
bool CDomLadder::SetClusterRank(const int index,const int rank)
  {
   if(index<0 || index>=m_count)
      return(false);
   m_levels[index].cluster_rank=rank;
   return(true);
  }

ComputeCumulative() runs two passes. The first starts at the best ask, which is the last ask in the array, and moves toward the highest ask. The second starts at the best bid, which is the first bid, and moves toward the lowest bid. The two sums are independent.

//+------------------------------------------------------------------+
//| Cumulative volume outward from the best ask and the best bid     |
//| The level itself is included in its own cumulative value         |
//+------------------------------------------------------------------+
bool CDomLadder::ComputeCumulative(void)
  {
//--- asks: start at the best ask, which is the last ask in the array, and move outward
   double running=0.0;
   for(int i=m_ask_count-1; i>=0; i--)
     {
      running+=m_levels[i].volume;
      m_levels[i].cum_volume=running;
     }
//--- bids: the running sum restarts, because each side is cumulated on its own
   running=0.0;
   for(int i=m_ask_count; i<m_count; i++)
     {
      running+=m_levels[i].volume;
      m_levels[i].cum_volume=running;
     }
   return(true);
  }

GetSpreadTicks() returns the distance between the unbucketed best ask and best bid. It returns false when either side is missing, so a missing spread is not confused with a spread of zero. A crossed book gives a negative value.

//+------------------------------------------------------------------+
//| Spread in ticks between the unbucketed best ask and best bid     |
//| Returns false when one side is missing                           |
//+------------------------------------------------------------------+
bool CDomLadder::GetSpreadTicks(long &ticks) const
  {
//--- a missing side means no spread, which is different from a spread of zero
   if(!m_has_raw_bid || !m_has_raw_ask)
      return(false);
//--- negative when the book is crossed, zero when it is locked
   ticks=m_raw_best_ask-m_raw_best_bid;
   return(true);
  }

IsCrossed() reports a best bid at or above the best ask, which covers both crossed and locked books. The panel labels the strip when this is true.

//+------------------------------------------------------------------+
//| True when the best bid is at or above the best ask               |
//+------------------------------------------------------------------+
bool CDomLadder::IsCrossed(void) const
  {
   return(m_has_raw_bid && m_has_raw_ask && m_raw_best_bid>=m_raw_best_ask);
  }

VisibleRows() splits a row budget between the two sides. Each side gets half of the rows, and a side with fewer levels than its half hands the unused rows to the other side. The rows kept are the ones nearest the spread. The method uses MathMin() and MathMax().

//+------------------------------------------------------------------+
//| Split a row budget between the sides, nearest levels first       |
//+------------------------------------------------------------------+
bool CDomLadder::VisibleRows(const int max_rows,int &ask_rows,int &bid_rows) const
  {
   ask_rows=0;
   bid_rows=0;
   if(max_rows<1)
      return(false);
//--- each side gets half the rows; a side with fewer levels leaves its unused rows to the other
   const int half=max_rows/2;
   ask_rows=::MathMin(m_ask_count,::MathMax(half,max_rows-m_bid_count));
   bid_rows=::MathMin(m_bid_count,max_rows-ask_rows);
   return(true);
  }

HiddenClusters() counts cluster levels that fall outside the visible rows. The visible levels form one contiguous block around the spread, so two index comparisons are enough.

//+------------------------------------------------------------------+
//| Count cluster levels that fall outside the visible rows          |
//+------------------------------------------------------------------+
int CDomLadder::HiddenClusters(const int ask_rows,const int bid_rows) const
  {
//--- visible asks are the last ask_rows asks and visible bids are the first bid_rows bids
   const int first_visible=m_ask_count-ask_rows;
   const int last_visible=m_ask_count+bid_rows-1;
   int hidden=0;
   for(int i=0; i<m_count; i++)
     {
      if(m_levels[i].cluster_rank<=0)
         continue;
      if(i<first_visible || i>last_visible)
         hidden++;
     }
   return(hidden);
  }


Validating, Bucketing, and Sorting a Snapshot: CDomLadderBuilder

The builder turns an MqlBookInfo array into a ladder. It keeps a private scratch array of accepted entries and calls no market, symbol, chart, or object functions. The declaration comes first.

//+------------------------------------------------------------------+
//|                                             DomLadderBuilder.mqh |
//+------------------------------------------------------------------+
#ifndef DOM_LADDER_BUILDER_MQH
#define DOM_LADDER_BUILDER_MQH

#include "DomTypes.mqh"
#include "DomLadder.mqh"

//+------------------------------------------------------------------+
//| Turns a raw MqlBookInfo snapshot into a sorted, aggregated ladder|
//| This class never calls the terminal.                             |
//+------------------------------------------------------------------+
class CDomLadderBuilder
  {
private:
   double            m_tick_size;
   int               m_digits;
   int               m_ticks_per_level;
   int               m_min_levels;
   bool              m_configured;
   SDomLevel         m_raw[];
public:
                     CDomLadderBuilder(void);
                    ~CDomLadderBuilder(void);
   bool              Configure(const double tick_size,const int digits,const int ticks_per_level,const int min_levels);
   ENUM_DOM_STATUS   Build(const MqlBookInfo &book[],CDomLadder &ladder);
private:
   bool              ToTickIndex(const double price,long &tick_index) const;
   double            ReadVolume(const MqlBookInfo &entry) const;
   long              BucketTick(const long tick_index,const bool is_bid) const;
   bool              Precedes(const SDomLevel &a,const SDomLevel &b) const;
   bool              SortRaw(const int count);
  };
//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CDomLadderBuilder::CDomLadderBuilder(void)
  {
   m_tick_size       = 0.0;
   m_digits          = 0;
   m_ticks_per_level = 1;
   m_min_levels      = 2;
   m_configured      = false;
  }
//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CDomLadderBuilder::~CDomLadderBuilder(void)
  {
  }

Configure() receives the tick size, the price digits, the ticks per level, and the minimum number of levels. It rejects values that cannot work, and it uses MathIsValidNumber() to reject a tick size that is not a finite number. On rejection it returns false and keeps the previous settings. The minimum level count is a heuristic: below it, the book is reported as "No DOM data".

//+------------------------------------------------------------------+
//| Set tick size, price digits, bucket size and the minimum number  |
//| of levels needed to call the book usable                         |
//+------------------------------------------------------------------+
bool CDomLadderBuilder::Configure(const double tick_size,const int digits,const int ticks_per_level,const int min_levels)
  {
//--- reject values that would make the tick index meaningless
   if(!::MathIsValidNumber(tick_size) || tick_size<=0.0)
      return(false);
   if(digits<0 || digits>16)
      return(false);
   if(ticks_per_level<1 || min_levels<1)
      return(false);
//--- store the settings only after every check has passed
   m_tick_size       = tick_size;
   m_digits          = digits;
   m_ticks_per_level = ticks_per_level;
   m_min_levels      = min_levels;
   m_configured      = true;
   return(true);
  }

ToTickIndex() converts a price to a whole tick count with MathRound(). It returns false for prices that are not finite, are not positive, are absurdly large relative to the tick size, or round to tick index zero.

//+------------------------------------------------------------------+
//| Convert a price to a whole tick count, rounding to the nearest   |
//| tick. Returns false for prices that cannot be used.              |
//+------------------------------------------------------------------+
bool CDomLadderBuilder::ToTickIndex(const double price,long &tick_index) const
  {
   if(!::MathIsValidNumber(price) || price<=0.0)
      return(false);
//--- how many ticks the price is above zero; a huge ratio would not fit a long
   const double ratio=price/m_tick_size;
   if(ratio>1.0e15)
      return(false);
//--- round to the nearest tick, so a price slightly off the grid still gets an index
   const double rounded=::MathRound(ratio);
   const long index=(long)rounded;
   if(index<=0)
      return(false);
   tick_index=index;
   return(true);
  }

ReadVolume() applies the volume rule: volume_real when it is nonzero, otherwise volume. A negative or non-finite value is passed on unchanged and rejected by the caller.

//+------------------------------------------------------------------+
//| volume_real when it is nonzero, otherwise volume                 |
//+------------------------------------------------------------------+
double CDomLadderBuilder::ReadVolume(const MqlBookInfo &entry) const
  {
//--- volume_real is preferred when the broker fills it, otherwise the integer volume is used
   if(entry.volume_real!=0.0)
      return(entry.volume_real);
   return((double)entry.volume);
  }

BucketTick() implements the bucket rule. Positive integer division gives the floor for bids, and adding L minus one before dividing gives the ceiling for asks.

//+------------------------------------------------------------------+
//| Bucket rule with L = ticks per level (positive tick indexes):    |
//| bid: floor(index / L) * L   ask: ceil(index / L) * L             |
//| Both roundings move away from the market. For prices on the tick |
//| grid and a book that is not crossed, a bucket therefore does not |
//| move to the other side of the spread.                            |
//+------------------------------------------------------------------+
long CDomLadderBuilder::BucketTick(const long tick_index,const bool is_bid) const
  {
   const long step=(long)m_ticks_per_level;
   long bucket=0;
//--- bid: integer division gives the floor, so the bucket is at or below the price
   if(is_bid)
      bucket=tick_index/step;
//--- ask: adding step-1 before the division gives the ceiling, so the bucket is at or above the price
   else
      bucket=(tick_index+step-1)/step;
   return(bucket*step);
  }

Precedes() defines the sort order. Asks come before bids, and within a side the higher tick index comes first.

//+------------------------------------------------------------------+
//| Sort order: asks before bids, then tick index descending         |
//+------------------------------------------------------------------+
bool CDomLadderBuilder::Precedes(const SDomLevel &a,const SDomLevel &b) const
  {
   if(a.is_bid!=b.is_bid)
      return(!a.is_bid);
   return(a.tick_index>b.tick_index);
  }

SortRaw() is an explicit insertion sort. The code does not assume that the snapshot arrives sorted. Insertion sort is stable and simple to verify by reading, and its quadratic cost is discussed in the limitations.

//+------------------------------------------------------------------+
//| Explicit insertion sort of the first count raw levels            |
//+------------------------------------------------------------------+
bool CDomLadderBuilder::SortRaw(const int count)
  {
//--- insertion sort: take each entry and move it left until it is in order
   for(int i=1; i<count; i++)
     {
      SDomLevel key=m_raw[i];
      int j=i-1;
      //--- shift larger entries one place to the right; equal entries keep their order
      while(j>=0 && Precedes(key,m_raw[j]))
        {
         m_raw[j+1]=m_raw[j];
         j--;
        }
      m_raw[j+1]=key;
     }
   return(true);
  }

Build() is the main method and runs in three passes. In pass one, each entry is validated in this order: type, price, volume, then bucket. It also tracks the unbucketed best bid and best ask.

Pass two sorts. Pass three merges neighbors that share a side and a bucket, and appends the merged levels to the ladder.

The method calls NormalizeDouble() to round each bucket price to the symbol digits. A snapshot with no entries returns DOM_STATUS_NO_DATA immediately, and so does a result with fewer levels than the configured minimum. In that second case the levels are cleared and the counters are kept. A builder that has not been configured returns DOM_STATUS_READ_FAILED.

//+------------------------------------------------------------------+
//| Build the ladder from a snapshot                                 |
//+------------------------------------------------------------------+
ENUM_DOM_STATUS CDomLadderBuilder::Build(const MqlBookInfo &book[],CDomLadder &ladder)
  {
   SDomStats stats;
   stats.total_entries  = 0;
   stats.used_entries   = 0;
   stats.skipped_price  = 0;
   stats.skipped_volume = 0;
   stats.skipped_zero   = 0;
   stats.market_orders  = 0;
   stats.unknown_type   = 0;
   ladder.Clear();
   if(!m_configured)
      return(DOM_STATUS_READ_FAILED);
   const int total=::ArraySize(book);
   stats.total_entries=total;
   if(total<=0)
     {
      ladder.SetStats(stats);
      return(DOM_STATUS_NO_DATA);
     }
   if(::ArrayResize(m_raw,total)!=total)
      return(DOM_STATUS_READ_FAILED);
//--- pass 1: check every entry in a fixed order (type, price, volume, bucket)
//--- and count the reason when an entry is skipped
   int raw_count = 0;
   bool has_bid  = false;
   bool has_ask  = false;
   long best_bid = 0;
   long best_ask = 0;
   for(int i=0; i<total; i++)
     {
      const ENUM_BOOK_TYPE entry_type=book[i].type;
      //--- market-order entries do not rest at a price level, so they are only counted
      if(entry_type==BOOK_TYPE_SELL_MARKET || entry_type==BOOK_TYPE_BUY_MARKET)
        {
         stats.market_orders++;
         continue;
        }
      if(entry_type!=BOOK_TYPE_SELL && entry_type!=BOOK_TYPE_BUY)
        {
         stats.unknown_type++;
         continue;
        }
      //--- only BOOK_TYPE_BUY and BOOK_TYPE_SELL reach this point
      const bool is_bid=(entry_type==BOOK_TYPE_BUY);
      long tick_index=0;
      if(!ToTickIndex(book[i].price,tick_index))
        {
         stats.skipped_price++;
         continue;
        }
      //--- a negative or non-finite volume is skipped even when the other volume field is valid
      const double volume=ReadVolume(book[i]);
      if(!::MathIsValidNumber(volume) || volume<0.0)
        {
         stats.skipped_volume++;
         continue;
        }
      if(volume<=0.0)
        {
         stats.skipped_zero++;
         continue;
        }
      //--- the bucket price replaces the raw price from here on, the raw tick index is kept only for the spread
      const long bucket_tick=BucketTick(tick_index,is_bid);
      if(bucket_tick<=0)
        {
         stats.skipped_price++;
         continue;
        }
      m_raw[raw_count].tick_index=bucket_tick;
      m_raw[raw_count].price=::NormalizeDouble((double)bucket_tick*m_tick_size,m_digits);
      m_raw[raw_count].volume=volume;
      m_raw[raw_count].cum_volume=0.0;
      m_raw[raw_count].is_bid=is_bid;
      m_raw[raw_count].cluster_rank=0;
      raw_count++;
      //--- the best bid is the highest raw bid, the best ask is the lowest raw ask
      if(is_bid && (!has_bid || tick_index>best_bid))
        {
         has_bid=true;
         best_bid=tick_index;
        }
      if(!is_bid && (!has_ask || tick_index<best_ask))
        {
         has_ask=true;
         best_ask=tick_index;
        }
     }
   stats.used_entries=raw_count;
//--- pass 2: sort explicitly because the snapshot order is not trusted
//--- asks come first, then bids, each side from the highest price to the lowest
   SortRaw(raw_count);
//--- pass 3: merge neighbors that share a side and a bucket
//--- after the sort, entries of one level are next to each other, so one scan is enough
   if(raw_count>0)
     {
      SDomLevel current=m_raw[0];
      for(int i=1; i<raw_count; i++)
        {
         if(m_raw[i].is_bid==current.is_bid && m_raw[i].tick_index==current.tick_index)
           {
            current.volume+=m_raw[i].volume;
            continue;
           }
         if(!ladder.AppendLevel(current))
           {
            ladder.Clear();
            return(DOM_STATUS_READ_FAILED);
           }
         current=m_raw[i];
        }
      if(!ladder.AppendLevel(current))
        {
         ladder.Clear();
         return(DOM_STATUS_READ_FAILED);
        }
     }
   ladder.SetRawBest(has_bid,best_bid,has_ask,best_ask);
   ladder.SetStats(stats);
//--- the minimum counts levels on both sides together, so one bid and one ask pass with the default of two
   if(ladder.Count()<m_min_levels)
     {
      ladder.ClearLevels();
      return(DOM_STATUS_NO_DATA);
     }
   ladder.ComputeCumulative();
   return(DOM_STATUS_OK);
  }

Entry checks

Figure 5: The order in which Build() checks one entry. A failed check (✗) increases the counter on the right. A passed check (✓) moves to the next one.


Ranking the Largest Levels: CDomClusterFinder

The cluster finder ranks the largest levels on each side. It works only through the ladder interface.

//+------------------------------------------------------------------+
//|                                            DomClusterFinder.mqh  |
//+------------------------------------------------------------------+
#ifndef DOM_CLUSTER_FINDER_MQH
#define DOM_CLUSTER_FINDER_MQH

#include "DomTypes.mqh"
#include "DomLadder.mqh"

//+------------------------------------------------------------------+
//| Ranks the largest levels of each side of a ladder                |
//| A cluster is a ranking by volume, not a statistical test.        |
//| This class never calls the terminal.                             |
//+------------------------------------------------------------------+
class CDomClusterFinder
  {
private:
   int               m_top_n;
public:
                     CDomClusterFinder(void);
                    ~CDomClusterFinder(void);
   bool              SetTopN(const int top_n);
   int               Mark(CDomLadder &ladder);
private:
   int               MarkSide(CDomLadder &ladder,const bool bids);
   bool              IsBetter(const SDomLevel &a,const SDomLevel &b,const bool bids) const;
  };
//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CDomClusterFinder::CDomClusterFinder(void)
  {
   m_top_n=DOM_CLUSTER_COUNT;
  }
//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CDomClusterFinder::~CDomClusterFinder(void)
  {
  }

SetTopN() sets how many clusters are marked per side. The indicator uses the value 3.

//+------------------------------------------------------------------+
//| Number of clusters marked per side                               |
//+------------------------------------------------------------------+
bool CDomClusterFinder::SetTopN(const int top_n)
  {
//--- at least one cluster per side
   if(top_n<1)
      return(false);
   m_top_n=top_n;
   return(true);
  }

IsBetter() holds the tie-breaking rule. Volumes that differ by more than the tolerance are compared by value, using MathAbs(). Otherwise the level closer to the market wins.

//+------------------------------------------------------------------+
//| Tie-breaking: higher volume wins; on equal volume the level      |
//| closer to the market wins (higher bid, lower ask)                |
//+------------------------------------------------------------------+
bool CDomClusterFinder::IsBetter(const SDomLevel &a,const SDomLevel &b,const bool bids) const
  {
//--- volumes that differ by less than the tolerance count as equal
   if(::MathAbs(a.volume-b.volume)>DOM_VOLUME_EPS)
      return(a.volume>b.volume);
//--- equal volume: the level nearer the market wins
   if(bids)
      return(a.tick_index>b.tick_index);
   return(a.tick_index<b.tick_index);
  }

MarkSide() first clears the ranks on its side, so calling the finder twice gives the same result. It then selects the best unranked level once per rank, and stops as soon as no unranked level remains. That early exit is what prevents invented clusters on short sides.

//+------------------------------------------------------------------+
//| Rank the top levels of one side; returns how many were marked    |
//+------------------------------------------------------------------+
int CDomClusterFinder::MarkSide(CDomLadder &ladder,const bool bids)
  {
//--- the ladder stores asks first, so each side is one contiguous index range
   int first=0;
   int last=ladder.AskCount();
   if(bids)
     {
      first=ladder.AskCount();
      last=ladder.Count();
     }
//--- clear old ranks first so that calling Mark() twice gives the same result
   for(int i=first; i<last; i++)
      ladder.SetClusterRank(i,0);
   int marked=0;
   for(int rank=1; rank<=m_top_n; rank++)
     {
      //--- one pass per rank: pick the best level that has no rank yet
      int best=-1;
      for(int i=first; i<last; i++)
        {
         //--- read the level at index i and skip it when it already has a rank
         SDomLevel candidate;
         if(!ladder.GetLevel(i,candidate))
            continue;
         if(candidate.cluster_rank>0)
            continue;
         if(best<0)
           {
            best=i;
            continue;
           }
         SDomLevel current_best;
         if(ladder.GetLevel(best,current_best) && IsBetter(candidate,current_best,bids))
            best=i;
        }
      //--- no unranked level left: stop, so a short side gets fewer clusters and none are invented
      if(best<0)
         break;
      ladder.SetClusterRank(best,rank);
      marked++;
     }
   return(marked);
  }

Mark() runs both sides and returns the number of marked levels.

//+------------------------------------------------------------------+
//| Mark clusters on both sides; returns the number of marked levels |
//+------------------------------------------------------------------+
int CDomClusterFinder::Mark(CDomLadder &ladder)
  {
//--- asks and bids are ranked independently
   int marked=MarkSide(ladder,false);
   marked+=MarkSide(ladder,true);
   return(marked);
  }


Skipping Redraws When Nothing Changed: CDomChangeDetector

The change detector decides whether a redraw is needed. It stores a copy of the previous raw snapshot and compares the new one entry by entry, in order. The same entries delivered in a different order count as a change, which can cause an unnecessary redraw but not a missed one.

//+------------------------------------------------------------------+
//|                                            DomChangeDetector.mqh |
//+------------------------------------------------------------------+
#ifndef DOM_CHANGE_DETECTOR_MQH
#define DOM_CHANGE_DETECTOR_MQH

//+------------------------------------------------------------------+
//| Tells whether a snapshot differs from the previous one           |
//| Entries are compared in order, so the same entries delivered in  |
//| a different order count as a change. This class never calls the  |
//| terminal.                                                        |
//+------------------------------------------------------------------+
class CDomChangeDetector
  {
private:
   MqlBookInfo       m_prev[];
   int               m_prev_count;
   bool              m_has_prev;
public:
                     CDomChangeDetector(void);
                    ~CDomChangeDetector(void);
   bool              Update(const MqlBookInfo &book[]);
   bool              Reset(void);
  };
//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CDomChangeDetector::CDomChangeDetector(void)
  {
   m_prev_count=0;
   m_has_prev=false;
  }
//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CDomChangeDetector::~CDomChangeDetector(void)
  {
  }

Reset() forgets the stored snapshot, so the next Update() call reports a change. The indicator calls it after a failed read.

//+------------------------------------------------------------------+
//| Forget the stored snapshot; the next Update() reports a change   |
//+------------------------------------------------------------------+
bool CDomChangeDetector::Reset(void)
  {
//--- with no stored snapshot, the next Update() reports a change
   m_prev_count=0;
   m_has_prev=false;
   return(true);
  }

Update() returns true on the first snapshot, when the entry count changes, or when any entry differs in type, price, volume, or volume_real. It stores the new snapshot whenever it reports a change.

//+------------------------------------------------------------------+
//| Compare with the stored snapshot, then store the new one         |
//| The first call after construction or Reset() returns true        |
//+------------------------------------------------------------------+
bool CDomChangeDetector::Update(const MqlBookInfo &book[])
  {
   const int count=::ArraySize(book);
//--- the first snapshot, or a different number of entries, is always a change
   bool changed=true;
   if(m_has_prev && count==m_prev_count)
     {
      changed=false;
      for(int i=0; i<count; i++)
        {
         //--- exact comparison of every field, stop at the first difference
         if(book[i].type!=m_prev[i].type ||
            book[i].price!=m_prev[i].price ||
            book[i].volume!=m_prev[i].volume ||
            book[i].volume_real!=m_prev[i].volume_real)
           {
            changed=true;
            break;
           }
        }
     }
//--- keep a copy of the new snapshot for the next comparison
   if(changed)
     {
      //--- if the copy cannot be stored, forget the old one and still report the change
      if(::ArrayResize(m_prev,count)!=count)
        {
         m_prev_count=0;
         m_has_prev=false;
         return(true);
        }
      for(int i=0; i<count; i++)
         m_prev[i]=book[i];
      m_prev_count=count;
      m_has_prev=true;
     }
   return(changed);
  }


Reading the Book from the Terminal: CDomBookReader

The reader is the only class that calls the book functions. It also reads the tick size and digits of the symbol. It keeps the last error code so the panel can show it.

//+------------------------------------------------------------------+
//|                                                DomBookReader.mqh |
//+------------------------------------------------------------------+
#ifndef DOM_BOOK_READER_MQH
#define DOM_BOOK_READER_MQH

//+------------------------------------------------------------------+
//| The only class that talks to the terminal for book data          |
//+------------------------------------------------------------------+
class CDomBookReader
  {
private:
   string            m_symbol;
   bool              m_subscribed;
   int               m_last_error;
public:
                     CDomBookReader(void);
                    ~CDomBookReader(void);
   bool              Subscribe(const string symbol);
   bool              Unsubscribe(void);
   bool              Read(MqlBookInfo &book[]);
   bool              LoadSymbolInfo(const string symbol,double &tick_size,int &digits);
   bool              IsSubscribed(void) const;
   int               LastError(void) const;
  };
//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CDomBookReader::CDomBookReader(void)
  {
   m_symbol     = "";
   m_subscribed = false;
   m_last_error = 0;
  }
//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CDomBookReader::~CDomBookReader(void)
  {
  }

Subscribe() calls MarketBookAdd() and checks the return value. It resets the error state with ResetLastError() first, and on failure it saves the code from GetLastError().

//+------------------------------------------------------------------+
//| Subscribe to the book of a symbol with MarketBookAdd()           |
//+------------------------------------------------------------------+
bool CDomBookReader::Subscribe(const string symbol)
  {
//--- clear the last error first, so GetLastError() reports this call and not an older one
   ::ResetLastError();
   if(!::MarketBookAdd(symbol))
     {
      m_last_error=::GetLastError();
      return(false);
     }
//--- remember the symbol, because the release must use the same name
   m_symbol     = symbol;
   m_subscribed = true;
   m_last_error = 0;
   return(true);
  }

Unsubscribe() calls MarketBookRelease() and checks the return value. The subscription flag is cleared even when the release fails, and the method does not retry.

//+------------------------------------------------------------------+
//| Release the subscription with MarketBookRelease()                |
//+------------------------------------------------------------------+
bool CDomBookReader::Unsubscribe(void)
  {
//--- nothing to release when there is no subscription
   if(!m_subscribed)
      return(true);
   ::ResetLastError();
   const bool released=::MarketBookRelease(m_symbol);
   if(!released)
      m_last_error=::GetLastError();
//--- the flag is cleared even when the release failed, so the call is not repeated
   m_subscribed=false;
   return(released);
  }

Read() calls MarketBookGet() and checks the return value. On failure it empties the output array and saves the error code. Without a subscription it returns false and does not call the terminal. A successful read can still return an empty array, and the documentation page does not say what an empty snapshot looks like, so the builder handles that case.

//+------------------------------------------------------------------+
//| Read the current snapshot with MarketBookGet()                   |
//+------------------------------------------------------------------+
bool CDomBookReader::Read(MqlBookInfo &book[])
  {
//--- reading without a subscription is not a terminal error, so no error code is stored
   if(!m_subscribed)
     {
      ::ArrayResize(book,0);
      m_last_error=0;
      return(false);
     }
   ::ResetLastError();
//--- a failed read returns an empty array, so old data is never passed on as current
   if(!::MarketBookGet(m_symbol,book))
     {
      m_last_error=::GetLastError();
      ::ArrayResize(book,0);
      return(false);
     }
   m_last_error=0;
   return(true);
  }

LoadSymbolInfo() reads the tick size with SymbolInfoDouble() and falls back to the point size when the tick size is not positive. It reads the digits with SymbolInfoInteger(). Each call is checked, and on a failed read the method saves the error code and returns false, so a failed read is not mistaken for a valid value.

//+------------------------------------------------------------------+
//| Tick size and digits of a symbol; false when a read fails        |
//+------------------------------------------------------------------+
bool CDomBookReader::LoadSymbolInfo(const string symbol,double &tick_size,int &digits)
  {
   ::ResetLastError();
   double size=0.0;
   long symbol_digits=0;
//--- tick size, with the point size as a fallback when the tick size is not positive
   if(!::SymbolInfoDouble(symbol,SYMBOL_TRADE_TICK_SIZE,size) || size<=0.0)
     {
      if(!::SymbolInfoDouble(symbol,SYMBOL_POINT,size) || size<=0.0)
        {
         m_last_error=::GetLastError();
         return(false);
        }
     }
//--- the number of digits is checked as well, because a failed read must not look like zero digits
   if(!::SymbolInfoInteger(symbol,SYMBOL_DIGITS,symbol_digits) || symbol_digits<0)
     {
      m_last_error=::GetLastError();
      return(false);
     }
   tick_size=size;
   digits=(int)symbol_digits;
   return(true);
  }

The last two methods report the subscription flag and the saved error code.

//+------------------------------------------------------------------+
//| True after a successful Subscribe() and before Unsubscribe()     |
//+------------------------------------------------------------------+
bool CDomBookReader::IsSubscribed(void) const
  {
   return(m_subscribed);
  }
//+------------------------------------------------------------------+
//| Error code saved by the last failed terminal call                |
//+------------------------------------------------------------------+
int CDomBookReader::LastError(void) const
  {
   return(m_last_error);
  }


Drawing the Ladder on a Canvas: CDomPanel

The panel draws on a bitmap label. It is built on CCanvas and uses these methods: CreateBitmapLabel(), Erase(), FillRectangle(), Rectangle(), FontSet(), TextOut(), TextWidth(), TextHeight(), Update(), Resize(), and Destroy().

The layout has five columns. Reading from the left they are cumulative bid volume, bid volume, price, ask volume, and cumulative ask volume. Bid volume is on the left, the price is in the center, and ask volume is on the right. The macros below set the sizes and colors.

The panel paints its own opaque light gray background with dark text, so it stays readable on a light or a dark chart. Color is not the only carrier of meaning. Bids and asks differ by column position and column heading, and a cluster level carries a "C1", "C2", or "C3" label and a border in addition to its fill color.

//+------------------------------------------------------------------+
//|                                                     DomPanel.mqh |
//+------------------------------------------------------------------+
#ifndef DOM_PANEL_MQH
#define DOM_PANEL_MQH

#include <Canvas/Canvas.mqh>
#include "DomTypes.mqh"
#include "DomLadder.mqh"

//--- layout in pixels
#define DOM_ROW_H        18
#define DOM_PAD          6
#define DOM_COL_CUM      96
#define DOM_COL_VOL      118
#define DOM_COL_PRICE    104
#define DOM_WIDTH        (2*DOM_PAD+2*DOM_COL_CUM+2*DOM_COL_VOL+DOM_COL_PRICE)
#define DOM_HEAD_ROWS    2
#define DOM_FOOT_ROWS    3
#define DOM_MIN_ROWS     2
//--- horizontal text anchors, applied by CDomPanel::Text() from the measured text width
#define DOM_ALIGN_LEFT   0
#define DOM_ALIGN_RIGHT  1
#define DOM_ALIGN_CENTER 2
//--- font size, checked on one display only; the row height is fixed
#define DOM_FONT_NAME    "Consolas"
#define DOM_FONT_SIZE    14
//--- the panel paints its own opaque light gray background and uses dark text on it
#define DOM_CLR_BG       C'238,241,245'
#define DOM_CLR_HEAD     C'206,214,226'
#define DOM_CLR_STRIP    C'222,228,236'
#define DOM_CLR_BORDER   C'120,130,145'
#define DOM_CLR_TEXT     C'28,32,38'
#define DOM_CLR_MUTED    C'84,92,104'
#define DOM_CLR_BID      C'24,86,160'
#define DOM_CLR_ASK      C'166,84,8'
#define DOM_CLR_CLUSTER  C'255,205,70'
#define DOM_CLR_CLUSTER_TEXT C'20,20,20'

//+------------------------------------------------------------------+
//| Live ladder panel drawn on a CCanvas bitmap label                |
//+------------------------------------------------------------------+
class CDomPanel
  {
private:
   CCanvas           m_canvas;
   string            m_name;
   int               m_x;
   int               m_y;
   int               m_max_rows;
   int               m_rows;
   int               m_height;
   bool              m_created;
public:
                     CDomPanel(void);
                    ~CDomPanel(void);
   bool              Create(const string name,const int x,const int y,const int max_rows);
   bool              Destroy(void);
   bool              OnChartChange(void);
   bool              Render(const CDomLadder &ladder,const ENUM_DOM_STATUS status,const string symbol,const int digits,const int error_code);
private:
   int               FitRows(void) const;
   int               HeightForRows(const int rows) const;
   uint              Argb(const color clr) const;
   bool              Text(const int x,const int y,const string text,const color clr,const uint align);
   string            FormatVolume(const double volume) const;
   string            StatusText(const ENUM_DOM_STATUS status) const;
   bool              DrawFrame(const string title);
   bool              DrawMessage(const string line1,const string line2);
   bool              DrawHeadings(void);
   bool              DrawLadder(const CDomLadder &ladder,const int digits);
   bool              DrawLevelRow(const int row,const SDomLevel &level,const int digits);
   bool              DrawSpreadRow(const int row,const CDomLadder &ladder);
   bool              DrawFooter(const CDomLadder &ladder,const int ask_rows,const int bid_rows);
  };
//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CDomPanel::CDomPanel(void)
  {
   m_name     = "";
   m_x        = 0;
   m_y        = 0;
   m_max_rows = DOM_MIN_ROWS;
   m_rows     = DOM_MIN_ROWS;
   m_height   = 0;
   m_created  = false;
  }
//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CDomPanel::~CDomPanel(void)
  {
   Destroy();
  }

FitRows() reduces the number of level rows to fit the chart height. It starts from the configured maximum and lowers it when the chart height, read with ChartGetInteger(), cannot hold that many rows. A minimum of two rows is kept, so a very small chart can still clip the panel. The calculation handles height only, so a chart narrower than the panel clips it as well.

//+------------------------------------------------------------------+
//| FitRows                                                          |
//+------------------------------------------------------------------+
int CDomPanel::FitRows(void) const
  {
   int rows=m_max_rows;
   const long chart_height=::ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS);
   if(chart_height>0)
     {
      const int available=(int)chart_height-m_y-4;
      const int overhead=(DOM_HEAD_ROWS+1+DOM_FOOT_ROWS)*DOM_ROW_H;
      rows=::MathMin(rows,(available-overhead)/DOM_ROW_H);
     }
   rows=::MathMax(rows,DOM_MIN_ROWS);
   return(rows);
  }

HeightForRows() returns the canvas height for a row count: the header, the level rows, one spread row, and the footer. The maximum number of rows counts level rows only, so the spread strip is one extra row. The canvas height depends on the row budget and not on the number of levels, so a small book leaves blank rows at the bottom of the level area.

//+------------------------------------------------------------------+
//| Canvas height: header, level rows, one spread row, footer        |
//+------------------------------------------------------------------+
int CDomPanel::HeightForRows(const int rows) const
  {
   return((DOM_HEAD_ROWS+rows+1+DOM_FOOT_ROWS)*DOM_ROW_H+4);
  }

Create() makes the bitmap label and returns false when the canvas cannot be created.

//+------------------------------------------------------------------+
//| Create the bitmap label                                          |
//+------------------------------------------------------------------+
bool CDomPanel::Create(const string name,const int x,const int y,const int max_rows)
  {
//--- remember the settings, because the layout is recomputed when the chart changes
   m_name = name;
   m_x    = x;
   m_y    = y;
   m_max_rows=::MathMax(max_rows,DOM_MIN_ROWS);
//--- the canvas height follows from the row count that fits the chart
   m_rows=FitRows();
   m_height=HeightForRows(m_rows);
//--- an ARGB bitmap label, so the panel can be drawn with transparency support
   if(!m_canvas.CreateBitmapLabel(0,0,m_name,m_x,m_y,DOM_WIDTH,m_height,COLOR_FORMAT_ARGB_NORMALIZE))
      return(false);
   m_created=true;
   return(true);
  }
//+------------------------------------------------------------------+
//| Remove the bitmap label and its resource                         |
//+------------------------------------------------------------------+
bool CDomPanel::Destroy(void)
  {
   if(!m_created)
      return(true);
   m_canvas.Destroy();
   m_created=false;
   return(true);
  }

OnChartChange() handles chart resizing. It recomputes the row count, and only when the count changed does it resize the canvas. It returns true when the canvas was resized, which tells the caller to redraw.

//+------------------------------------------------------------------+
//| Re-fit the row count after a chart change                        |
//| Returns true only when the canvas was resized and needs a redraw |
//+------------------------------------------------------------------+
bool CDomPanel::OnChartChange(void)
  {
   if(!m_created)
      return(false);
//--- do nothing when the number of rows did not change
   const int rows=FitRows();
   if(rows==m_rows)
      return(false);
   const int height=HeightForRows(rows);
   if(!m_canvas.Resize(DOM_WIDTH,height))
      return(false);
   m_rows=rows;
   m_height=height;
   return(true);
  }

Argb() converts a color to an opaque ARGB value with ColorToARGB().

//+------------------------------------------------------------------+
//| Opaque ARGB color                                                |
//+------------------------------------------------------------------+
uint CDomPanel::Argb(const color clr) const
  {
   return(::ColorToARGB(clr,255));
  }

Text() draws one string. It measures the string with TextWidth() and TextHeight(), moves y up by half the height so that the string is centered on y, and moves x left by the full width for right alignment or by half the width for center alignment. The string is drawn with the default top-left anchor, so the code does not depend on the alignment flag values of TextOut().

The font size passed to FontSet() is a fixed positive number that was checked on one display only. Other display scaling settings were not tested, and the row height is fixed, so text that does not fit a row would need a smaller size.

//+------------------------------------------------------------------+
//| Text                                                             |
//+------------------------------------------------------------------+
bool CDomPanel::Text(const int x,const int y,const string text,const color clr,const uint align)
  {
//--- the canvas has no alignment option, so the text is measured and anchored by hand
   const int text_width=m_canvas.TextWidth(text);
   const int text_height=m_canvas.TextHeight(text);
//--- x is the left edge, the right edge or the center, depending on the alignment
   int left=x;
   if(align==DOM_ALIGN_RIGHT)
      left=x-text_width;
   if(align==DOM_ALIGN_CENTER)
      left=x-text_width/2;
//--- y is the middle of the text, so the text sits in the middle of its row
   m_canvas.TextOut(left,y-text_height/2,text,Argb(clr),0);
   return(true);
  }

FormatVolume() prints whole numbers without decimals, volumes of at least one with two decimals, and smaller fractions with four decimals so that a small nonzero volume is not displayed as zero. It uses MathAbs(), MathRound(), and DoubleToString().

//+------------------------------------------------------------------+
//| Whole numbers without decimals, fractions with 2 or 4 decimals   |
//+------------------------------------------------------------------+
string CDomPanel::FormatVolume(const double volume) const
  {
//--- whole numbers have no decimals; larger fractions get 2 decimals, small ones 4
   if(::MathAbs(volume-::MathRound(volume))<1.0e-9)
      return(::DoubleToString(volume,0));
   if(volume>=1.0)
      return(::DoubleToString(volume,2));
   return(::DoubleToString(volume,4));
  }

StatusText() maps each status to header text.

//+------------------------------------------------------------------+
//| Header text for each status                                      |
//+------------------------------------------------------------------+
string CDomPanel::StatusText(const ENUM_DOM_STATUS status) const
  {
   if(status==DOM_STATUS_OK)
      return("data OK");
   if(status==DOM_STATUS_NO_DATA)
      return("No DOM data");
   if(status==DOM_STATUS_READ_FAILED)
      return("DOM read failed");
   if(status==DOM_STATUS_SUBSCRIBE_FAILED)
      return("DOM subscribe failed");
   return("waiting");
  }

DrawFrame() clears the canvas, draws the header bar with the title, and draws the border.

//+------------------------------------------------------------------+
//| Background, border and the title bar                             |
//+------------------------------------------------------------------+
bool CDomPanel::DrawFrame(const string title)
  {
   m_canvas.FontSet(DOM_FONT_NAME,DOM_FONT_SIZE);
   m_canvas.Erase(Argb(DOM_CLR_BG));
   m_canvas.FillRectangle(0,0,DOM_WIDTH-1,DOM_ROW_H-1,Argb(DOM_CLR_HEAD));
   Text(DOM_PAD,DOM_ROW_H/2,title,DOM_CLR_TEXT,DOM_ALIGN_LEFT);
   m_canvas.Rectangle(0,0,DOM_WIDTH-1,m_height-1,Argb(DOM_CLR_BORDER));
   return(true);
  }

DrawMessage() writes two centered lines. It is used for all statuses other than data OK, so an unavailable book is not drawn as an empty ladder.

//+------------------------------------------------------------------+
//| Centered message used when there is no ladder to draw            |
//+------------------------------------------------------------------+
bool CDomPanel::DrawMessage(const string line1,const string line2)
  {
   const int middle=(DOM_HEAD_ROWS+(m_rows+1)/2)*DOM_ROW_H;
   Text(DOM_WIDTH/2,middle,line1,DOM_CLR_TEXT,DOM_ALIGN_CENTER);
   Text(DOM_WIDTH/2,middle+DOM_ROW_H,line2,DOM_CLR_MUTED,DOM_ALIGN_CENTER);
   return(true);
  }

DrawHeadings() writes the column headings.

//+------------------------------------------------------------------+
//| Column headings                                                  |
//+------------------------------------------------------------------+
bool CDomPanel::DrawHeadings(void)
  {
   const int y=DOM_ROW_H+DOM_ROW_H/2;
   const int cum_bid_right=DOM_PAD+DOM_COL_CUM;
   const int bid_right=cum_bid_right+DOM_COL_VOL;
   const int ask_left=bid_right+DOM_COL_PRICE;
   const int ask_right=ask_left+DOM_COL_VOL;
   Text(cum_bid_right-4,y,"Cum bid",DOM_CLR_MUTED,DOM_ALIGN_RIGHT);
   Text(bid_right-4,y,"Bid vol",DOM_CLR_MUTED,DOM_ALIGN_RIGHT);
   Text(bid_right+DOM_COL_PRICE/2,y,"Price",DOM_CLR_MUTED,DOM_ALIGN_CENTER);
   Text(ask_left+4,y,"Ask vol",DOM_CLR_MUTED,DOM_ALIGN_LEFT);
   Text(ask_right+DOM_COL_CUM-4,y,"Cum ask",DOM_CLR_MUTED,DOM_ALIGN_RIGHT);
   return(true);
  }

DrawLevelRow() draws one level. A bid fills the left half and an ask fills the right half. The other half of the row stays empty, not zero. A cluster level gets a filled, bordered cell and a rank label.

//+------------------------------------------------------------------+
//| One ladder level: bid on the left, ask on the right              |
//| Cluster levels get a filled, bordered cell and a "Cn" label      |
//+------------------------------------------------------------------+
bool CDomPanel::DrawLevelRow(const int row,const SDomLevel &level,const int digits)
  {
//--- every row has a fixed height, so the top edge follows from the row number
   const int top=row*DOM_ROW_H;
   const int middle=top+DOM_ROW_H/2;
//--- column edges, from left to right: bid cumulative, bid volume, price, ask volume, ask cumulative
   const int cum_bid_right  = DOM_PAD+DOM_COL_CUM;
   const int bid_right      = cum_bid_right+DOM_COL_VOL;
   const int ask_left       = bid_right+DOM_COL_PRICE;
   const int ask_right      = ask_left+DOM_COL_VOL;
   const int cum_ask_right  = ask_right+DOM_COL_CUM;
   const string volume_text = FormatVolume(level.volume);
   const string cum_text    = FormatVolume(level.cum_volume);
//--- the price is centered between the two volume columns
   Text(bid_right+DOM_COL_PRICE/2,middle,::DoubleToString(level.price,digits),DOM_CLR_TEXT,DOM_ALIGN_CENTER);
   if(level.is_bid)
     {
      color text_color=DOM_CLR_BID;
      string label=volume_text;
//--- a cluster gets a filled cell and a rank label such as C1, so it is not shown by color alone
      if(level.cluster_rank>0)
        {
         m_canvas.FillRectangle(cum_bid_right,top,bid_right-1,top+DOM_ROW_H-1,Argb(DOM_CLR_CLUSTER));
         m_canvas.Rectangle(cum_bid_right,top,bid_right-1,top+DOM_ROW_H-1,Argb(DOM_CLR_TEXT));
         text_color=DOM_CLR_CLUSTER_TEXT;
         label="C"+(string)level.cluster_rank+" "+volume_text;
        }
      Text(bid_right-4,middle,label,text_color,DOM_ALIGN_RIGHT);
      Text(cum_bid_right-4,middle,cum_text,DOM_CLR_BID,DOM_ALIGN_RIGHT);
     }
   else
     {
//--- ask side: same layout mirrored, the volume text is left aligned
      color text_color=DOM_CLR_ASK;
      string label=volume_text;
      if(level.cluster_rank>0)
        {
         m_canvas.FillRectangle(ask_left,top,ask_right-1,top+DOM_ROW_H-1,Argb(DOM_CLR_CLUSTER));
         m_canvas.Rectangle(ask_left,top,ask_right-1,top+DOM_ROW_H-1,Argb(DOM_CLR_TEXT));
         text_color=DOM_CLR_CLUSTER_TEXT;
         label=volume_text+" C"+(string)level.cluster_rank;
        }
      Text(ask_left+4,middle,label,text_color,DOM_ALIGN_LEFT);
      Text(cum_ask_right-4,middle,cum_text,DOM_CLR_ASK,DOM_ALIGN_RIGHT);
     }
   return(true);
  }

DrawSpreadRow() draws the strip between the sides. It reports the spread in ticks, labels a crossed or locked book, and states which side is missing when the spread is unavailable. It uses IntegerToString().

//+------------------------------------------------------------------+
//| Strip between asks and bids that states the spread               |
//+------------------------------------------------------------------+
bool CDomPanel::DrawSpreadRow(const int row,const CDomLadder &ladder)
  {
//--- the strip uses the unbucketed best prices, so the spread is not changed by the bucket size
   const int top=row*DOM_ROW_H;
   m_canvas.FillRectangle(1,top,DOM_WIDTH-2,top+DOM_ROW_H-1,Argb(DOM_CLR_STRIP));
   string text="";
   long ticks=0;
   if(ladder.GetSpreadTicks(ticks))
     {
      text="spread "+::IntegerToString(ticks)+" ticks";
//--- a crossed or locked book is flagged instead of showing a negative number alone
      if(ladder.IsCrossed())
         text="CROSSED OR LOCKED: spread "+::IntegerToString(ticks)+" ticks";
     }
   else
     {
//--- the spread is unavailable, so say which side is missing and do not show zero
      if(ladder.AskCount()==0)
         text="no ask levels in this snapshot";
      else
         text="no bid levels in this snapshot";
     }
   Text(DOM_WIDTH/2,top+DOM_ROW_H/2,text,DOM_CLR_TEXT,DOM_ALIGN_CENTER);
   return(true);
  }

DrawFooter() writes three lines: how many levels are shown out of how many exist together with the number of hidden clusters, the skipped-entry counters, and the volume rule. It uses StringFormat().

//+------------------------------------------------------------------+
//| Footer: rows shown, hidden clusters, skipped entries, units      |
//+------------------------------------------------------------------+
bool CDomPanel::DrawFooter(const CDomLadder &ladder,const int ask_rows,const int bid_rows)
  {
   SDomStats stats;
   ladder.GetStats(stats);
//--- the footer starts below the header rows, the level rows and the spread row
   const int base=DOM_HEAD_ROWS+m_rows+1;
   const int hidden=ladder.HiddenClusters(ask_rows,bid_rows);
   const string line1=::StringFormat("Showing %d of %d levels, clusters hidden: %d",ask_rows+bid_rows,ladder.Count(),hidden);
   const string line2=::StringFormat("Skipped: price %d, volume %d, zero %d, market %d, type %d",
                                     stats.skipped_price,stats.skipped_volume,stats.skipped_zero,stats.market_orders,stats.unknown_type);
   const string line3="Volume = volume_real, else volume (broker units)";
   Text(DOM_PAD,base*DOM_ROW_H+DOM_ROW_H/2,line1,DOM_CLR_MUTED,DOM_ALIGN_LEFT);
   Text(DOM_PAD,(base+1)*DOM_ROW_H+DOM_ROW_H/2,line2,DOM_CLR_MUTED,DOM_ALIGN_LEFT);
   Text(DOM_PAD,(base+2)*DOM_ROW_H+DOM_ROW_H/2,line3,DOM_CLR_MUTED,DOM_ALIGN_LEFT);
   return(true);
  }

DrawLadder() decides which levels fit. When the book has more levels than rows, the panel keeps the levels nearest the spread on each side and hides the farthest ones. The footer states how many levels are shown and how many cluster levels are hidden.

//+------------------------------------------------------------------+
//| Asks above the spread strip, bids below, nearest levels first    |
//+------------------------------------------------------------------+
bool CDomPanel::DrawLadder(const CDomLadder &ladder,const int digits)
  {
//--- decide how many ask rows and bid rows fit in the row budget
   int ask_rows=0;
   int bid_rows=0;
   ladder.VisibleRows(m_rows,ask_rows,bid_rows);
   const int ask_count=ladder.AskCount();
   int row=DOM_HEAD_ROWS;
   SDomLevel level;
//--- asks: only the nearest ones are drawn, from the farthest of them down to the best ask
   for(int i=ask_count-ask_rows; i<ask_count; i++)
     {
      if(ladder.GetLevel(i,level))
         DrawLevelRow(row,level,digits);
      row++;
     }
//--- the spread strip separates the asks from the bids
   DrawSpreadRow(row,ladder);
   row++;
//--- bids: from the best bid downward, again only the nearest ones
   for(int i=ask_count; i<ask_count+bid_rows; i++)
     {
      if(ladder.GetLevel(i,level))
         DrawLevelRow(row,level,digits);
      row++;
     }
   DrawFooter(ladder,ask_rows,bid_rows);
   return(true);
  }

Render() redraws the whole panel. For a usable ladder the title states the symbol, the number of levels, and the data status. For all other statuses the title says "levels n/a", and a message explains the condition.

//+------------------------------------------------------------------+
//| Redraw the whole panel for the given state                       |
//+------------------------------------------------------------------+
bool CDomPanel::Render(const CDomLadder &ladder,const ENUM_DOM_STATUS status,const string symbol,const int digits,const int error_code)
  {
   if(!m_created)
      return(false);
//--- the title carries the symbol, the level counts and the status
   string title="";
   if(status==DOM_STATUS_OK)
      title=::StringFormat("%s  levels %d (ask %d, bid %d)  %s",symbol,ladder.Count(),ladder.AskCount(),ladder.BidCount(),StatusText(status));
   else
      title=symbol+"  levels n/a  "+StatusText(status);
//--- background, title bar and border are drawn first, then the content
   DrawFrame(title);
   if(status==DOM_STATUS_OK)
     {
      DrawHeadings();
      DrawLadder(ladder,digits);
     }
   else
     {
//--- every other status shows a message instead of a ladder; a missing book is never drawn as zeros
      if(status==DOM_STATUS_NO_DATA)
        {
         SDomStats stats;
         ladder.GetStats(stats);
         if(stats.total_entries==0)
            DrawMessage("No DOM data","The book is empty");
         else
            DrawMessage("No DOM data",::StringFormat("Too few valid levels (%d entries, %d skipped)",
                        stats.total_entries,stats.total_entries-stats.used_entries));
        }
      else
         if(status==DOM_STATUS_READ_FAILED)
            DrawMessage("DOM unavailable",::StringFormat("Book read or processing failed (error %d)",error_code));
         else
            if(status==DOM_STATUS_SUBSCRIBE_FAILED)
               DrawMessage("DOM unavailable",::StringFormat("MarketBookAdd failed (error %d)",error_code));
            else
               DrawMessage("Waiting for book data","No snapshot has been processed yet");
     }
//--- nothing appears on the chart until the canvas is updated
   m_canvas.Update();
   return(true);
  }

Panel state

Figure 6: The panel state for each outcome. A failed check (✗) shows the title on the right, and a passed check (✓) continues down to the ladder.


Wiring the Classes Together: DomLadderPanel

The indicator holds one instance of each class. The inputs are the ticks per level, the maximum number of rows, the minimum number of valid levels, and the panel position. The comments on the input lines become the parameter labels in the terminal dialog.

//+------------------------------------------------------------------+
//|                                               DomLadderPanel.mq5 |
//+------------------------------------------------------------------+
#property description "Live price ladder built from the Depth of Market snapshot."
#property description "Live terminal only. Shows book levels, not trades."
#property indicator_chart_window
#property indicator_buffers 0
#property indicator_plots   0

#include <DomLadder/DomTypes.mqh>
#include <DomLadder/DomLadder.mqh>
#include <DomLadder/DomLadderBuilder.mqh>
#include <DomLadder/DomClusterFinder.mqh>
#include <DomLadder/DomChangeDetector.mqh>
#include <DomLadder/DomBookReader.mqh>
#include <DomLadder/DomPanel.mqh>

//--- Inputs
input int InpLevelTicks = 1;    // Ticks per ladder level (1 = every tick is a level)
input int InpMaxRows    = 20;   // Maximum number of level rows in the panel
input int InpMinLevels  = 2;    // Minimum valid levels needed to draw a ladder
input int InpPanelX     = 10;   // Panel X offset from the chart corner, pixels
input int InpPanelY     = 20;   // Panel Y offset from the chart corner, pixels

string             g_symbol="";
int                g_digits=0;
int                g_error_code=0;
ENUM_DOM_STATUS    g_status=DOM_STATUS_WAITING;
CDomBookReader     g_reader;
CDomLadderBuilder  g_builder;
CDomClusterFinder  g_finder;
CDomChangeDetector g_detector;
CDomLadder         g_ladder;
CDomPanel          g_panel;
//+------------------------------------------------------------------+
//| Draw the stored state without reading the book again             |
//+------------------------------------------------------------------+
bool RenderCurrent(void)
  {
   return(g_panel.Render(g_ladder,g_status,g_symbol,g_digits,g_error_code));
  }

ProcessBook() reads a snapshot and redraws only when something changed. A failed read resets the change detector, clears the ladder, and sets the read-failed status, and it does not redraw again while that status stays the same. A successful read goes to the change detector, and a snapshot that is identical to the previous one ends the call without a redraw. Otherwise the builder and the cluster finder run and the panel is redrawn.

//+------------------------------------------------------------------+
//| Read, compare, build, mark and draw. Called from OnInit() for    |
//| the first read and from OnBookEvent() for every later update.    |
//+------------------------------------------------------------------+
bool ProcessBook(void)
  {
   MqlBookInfo book[];
//--- step 1: read the raw snapshot
   if(!g_reader.Read(book))
     {
      //--- a failed read clears the old ladder, so stale data is never shown as current
      g_error_code=g_reader.LastError();
      g_detector.Reset();
      if(g_status==DOM_STATUS_READ_FAILED)
         return(false);
      g_ladder.Clear();
      g_status=DOM_STATUS_READ_FAILED;
      return(RenderCurrent());
     }
//--- step 2: skip the work when the snapshot is identical to the previous one
   if(!g_detector.Update(book))
      return(false);
//--- step 3: aggregate into a ladder; the returned status says why a ladder may be empty
   g_status=g_builder.Build(book,g_ladder);
//--- step 4: rank clusters only when the ladder is usable
   if(g_status==DOM_STATUS_OK)
      g_finder.Mark(g_ladder);
   return(RenderCurrent());
  }

OnInit() validates the inputs, reads the symbol properties, configures the builder, and creates the panel. It then subscribes. If the subscription fails, the indicator keeps running and the panel shows the failure with the error code, using Print() to log it. There is no retry logic. The first read at the end of initialization can come back empty if the broker has not delivered a snapshot yet, and the next book event then replaces that view.

//+------------------------------------------------------------------+
//| Indicator initialization                                         |
//+------------------------------------------------------------------+
int OnInit(void)
  {
//--- the panel follows the chart symbol
   g_symbol=_Symbol;
//--- reject inputs that would make the bucket or the row count meaningless
   if(InpLevelTicks<1 || InpMaxRows<DOM_MIN_ROWS || InpMinLevels<1)
     {
      ::Print("DomLadderPanel: invalid input parameters");
      return(INIT_PARAMETERS_INCORRECT);
     }
//--- the bucket size depends on the tick size, so read it before configuring
   double tick_size=0.0;
   if(!g_reader.LoadSymbolInfo(g_symbol,tick_size,g_digits))
     {
      ::Print("DomLadderPanel: cannot read tick size of ",g_symbol," error ",g_reader.LastError());
      return(INIT_FAILED);
     }
   if(!g_builder.Configure(tick_size,g_digits,InpLevelTicks,InpMinLevels))
     {
      ::Print("DomLadderPanel: builder configuration rejected");
      return(INIT_PARAMETERS_INCORRECT);
     }
//--- the canvas is created before subscribing so that a failure can be drawn on it
   g_finder.SetTopN(DOM_CLUSTER_COUNT);
   if(!g_panel.Create("DomLadderPanel",InpPanelX,InpPanelY,InpMaxRows))
     {
      ::Print("DomLadderPanel: cannot create the canvas panel");
      return(INIT_FAILED);
     }
//--- a refused subscription is shown on the panel; the indicator stays loaded
   if(!g_reader.Subscribe(g_symbol))
     {
      g_error_code=g_reader.LastError();
      g_status=DOM_STATUS_SUBSCRIBE_FAILED;
      ::Print("DomLadderPanel: MarketBookAdd failed for ",g_symbol," error ",g_error_code);
      RenderCurrent();
      return(INIT_SUCCEEDED);
     }
//--- the first read may be empty if the broker has not delivered a snapshot yet
   ProcessBook();
   return(INIT_SUCCEEDED);
  }

OnDeinit() releases the subscription when one exists, logs a release failure, and destroys the canvas. The handler is declared void, so it ends with a plain return statement.

//+------------------------------------------------------------------+
//| Indicator deinitialization                                       |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   if(g_reader.IsSubscribed())
     {
      if(!g_reader.Unsubscribe())
         ::Print("DomLadderPanel: MarketBookRelease failed for ",g_symbol," error ",g_reader.LastError());
     }
   g_panel.Destroy();
   return;
  }

OnBookEvent() ignores events for other symbols and processes the rest.

//+------------------------------------------------------------------+
//| Book update handler                                              |
//+------------------------------------------------------------------+
void OnBookEvent(const string &symbol)
  {
   if(symbol!=g_symbol)
      return;
   ProcessBook();
   return;
  }

OnChartEvent() reacts to CHARTEVENT_CHART_CHANGE by re-fitting the panel and redrawing when the canvas was resized.

//+------------------------------------------------------------------+
//| Chart event handler: re-fit the panel when the chart changes     |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
  {
   if(id==CHARTEVENT_CHART_CHANGE)
     {
      if(g_panel.OnChartChange())
         RenderCurrent();
     }
   return;
  }

OnCalculate() returns the bar count.

//+------------------------------------------------------------------+
//| Required by the indicator type; the panel does not use price data|
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   return(rates_total);
  }


Checking the Logic Classes: DomLadderTests

The test script covers the pure-logic classes only: the ladder, the builder, the cluster finder, and the change detector. It uses no terminal data. Each assertion has a name, and the script prints a final pass and fail count.

OnStart() runs the thirteen test functions, and the summary uses PrintFormat(). The script also uses Print() for each assertion line and MathSqrt() to produce a value that is not a number.

These are the assertion helpers, the helpers that build test snapshots, and four small accessors that read one level of a ladder.

//+------------------------------------------------------------------+
//|                                               DomLadderTests.mq5 |
//+------------------------------------------------------------------+
#property description "Tests of the pure-logic DOM ladder classes. No terminal data is used."
#property script_show_inputs

#include <DomLadder/DomTypes.mqh>
#include <DomLadder/DomLadder.mqh>
#include <DomLadder/DomLadderBuilder.mqh>
#include <DomLadder/DomClusterFinder.mqh>
#include <DomLadder/DomChangeDetector.mqh>

int g_pass=0;
int g_fail=0;
//+------------------------------------------------------------------+
//| Assertion helpers                                                |
//+------------------------------------------------------------------+
bool AssertTrue(const bool condition,const string name)
  {
   if(condition)
     {
      g_pass++;
      ::Print("ASSERT PASS [",name,"]");
     }
   else
     {
      g_fail++;
      ::Print("ASSERT FAIL [",name,"]");
     }
   return(condition);
  }
//+------------------------------------------------------------------+
//| AssertLong                                                       |
//+------------------------------------------------------------------+
bool AssertLong(const long actual,const long expected,const string name)
  {
   const bool ok=(actual==expected);
   if(!ok)
      ::Print("  expected ",expected," but got ",actual);
   return(AssertTrue(ok,name));
  }
//+------------------------------------------------------------------+
//| AssertNear                                                       |
//+------------------------------------------------------------------+
bool AssertNear(const double actual,const double expected,const string name)
  {
   const bool ok=(::MathAbs(actual-expected)<1.0e-9);
   if(!ok)
      ::Print("  expected ",::DoubleToString(expected,8)," but got ",::DoubleToString(actual,8));
   return(AssertTrue(ok,name));
  }
//+------------------------------------------------------------------+
//| AssertStatus                                                     |
//+------------------------------------------------------------------+
bool AssertStatus(const ENUM_DOM_STATUS actual,const ENUM_DOM_STATUS expected,const string name)
  {
   const bool ok=(actual==expected);
   if(!ok)
      ::Print("  expected status ",(int)expected," but got ",(int)actual);
   return(AssertTrue(ok,name));
  }
//+------------------------------------------------------------------+
//| Test data helpers                                                |
//+------------------------------------------------------------------+
bool AddEntry(MqlBookInfo &book[],const ENUM_BOOK_TYPE entry_type,const double price,const long volume,const double volume_real)
  {
   const int n=::ArraySize(book);
   if(::ArrayResize(book,n+1)!=n+1)
      return(false);
   book[n].type=entry_type;
   book[n].price=price;
   book[n].volume=volume;
   book[n].volume_real=volume_real;
   return(true);
  }
//+------------------------------------------------------------------+
//| MakeBuilder                                                      |
//+------------------------------------------------------------------+
bool MakeBuilder(CDomLadderBuilder &builder,const int ticks_per_level,const int min_levels)
  {
   return(builder.Configure(0.01,2,ticks_per_level,min_levels));
  }
//+------------------------------------------------------------------+
//| LevelPrice                                                       |
//+------------------------------------------------------------------+
double LevelPrice(const CDomLadder &ladder,const int index)
  {
   SDomLevel level;
   if(!ladder.GetLevel(index,level))
      return(-1.0);
   return(level.price);
  }
//+------------------------------------------------------------------+
//| LevelVolume                                                      |
//+------------------------------------------------------------------+
double LevelVolume(const CDomLadder &ladder,const int index)
  {
   SDomLevel level;
   if(!ladder.GetLevel(index,level))
      return(-1.0);
   return(level.volume);
  }
//+------------------------------------------------------------------+
//| LevelCum                                                         |
//+------------------------------------------------------------------+
double LevelCum(const CDomLadder &ladder,const int index)
  {
   SDomLevel level;
   if(!ladder.GetLevel(index,level))
      return(-1.0);
   return(level.cum_volume);
  }
//+------------------------------------------------------------------+
//| LevelRank                                                        |
//+------------------------------------------------------------------+
int LevelRank(const CDomLadder &ladder,const int index)
  {
   SDomLevel level;
   if(!ladder.GetLevel(index,level))
      return(-1);
   return(level.cluster_rank);
  }

The first test shows the pattern. Five entries go in, and the assertions check the status, the level counts, the summed volumes, and the entry counter.

//+------------------------------------------------------------------+
//| Entries at one price are summed                                  |
//+------------------------------------------------------------------+
bool TestSamePrice(void)
  {
   CDomLadderBuilder builder;
   CDomLadder ladder;
   MqlBookInfo book[];
   MakeBuilder(builder,1,2);
   AddEntry(book,BOOK_TYPE_BUY,100.00,5,0.0);
   AddEntry(book,BOOK_TYPE_BUY,100.00,7,0.0);
   AddEntry(book,BOOK_TYPE_BUY,99.99,1,0.0);
   AddEntry(book,BOOK_TYPE_SELL,100.02,3,0.0);
   AddEntry(book,BOOK_TYPE_SELL,100.02,4,0.0);
   AssertStatus(builder.Build(book,ladder),DOM_STATUS_OK,"same_price.status_ok");
   AssertLong(ladder.AskCount(),1,"same_price.ask_levels");
   AssertLong(ladder.BidCount(),2,"same_price.bid_levels");
   AssertNear(LevelVolume(ladder,0),7.0,"same_price.ask_sum");
   AssertNear(LevelVolume(ladder,1),12.0,"same_price.bid_sum");
   AssertNear(LevelVolume(ladder,2),1.0,"same_price.single_bid");
   SDomStats stats;
   ladder.GetStats(stats);
   AssertLong(stats.used_entries,5,"same_price.used_entries");
   return(true);
  }

The remaining tests follow the same pattern. They cover the cases below.

  • Unsorted input, including a check that reversed input gives the same ladder.
  • Bucketing at exact boundaries with five ticks per level, off-grid price rounding, merging inside buckets, the unbucketed spread, a bid bucket that falls to tick zero, and rejected configuration values.
  • Cumulative sums on both sides.
  • Top three selection with ties that cross the cutoff, distinct volumes, and repeated marking.
  • Fewer than three levels, with no invented cluster.
  • An empty book, a single level, entries that are all invalid, and rebuilding after an empty snapshot.
  • Invalid prices, including zero, negative, not a number, too large, and rounding to tick zero, with a check that the counters add up to the number of entries.
  • Negative, zero, and non-finite volumes, and the volume_real fallback.
  • Market-order entry types and an unknown type value.
  • Normal, crossed, locked, and one-sided books.
  • The row split for several row budgets, and the hidden cluster count.
  • The change detector for first snapshot, identical snapshot, changed volume, changed length, empty snapshots, reset, changed price, and changed volume_real.

The script contains 150 assertion calls. A successful run prints this in the Experts tab:

DomLadderTests RESULT: 150 passed, 0 failed

The tests have a narrow scope. A pass shows that the pure-logic classes behave as the listed assertions expect. It does not show correct behavior on a real feed, and it does not cover inputs that the assertions do not list. It does not cover OnBookEvent(), the reader class, the subscription and release logic, the rendering, the resize handling, or how any broker fills the fields of a book entry. The full script is in the attached archive, so you can check each assertion.


Which Servers Returned a Book

The panel can only draw what the server supplies, so it helps to check a server before attaching the indicator. The script lists symbols whose SYMBOL_TICKS_BOOKDEPTH is greater than zero and calls MarketBookAdd() for each one. The script reads no book entries.

The MQL5 documentation describes the property as the maximal number of requests shown in the Depth of Market, which in practice means the number of book levels, and as zero for symbols that have no queue of requests. The script uses AccountInfoString(), SymbolsTotal(), and SymbolName() to walk the symbol list.

//+------------------------------------------------------------------+
//|                                                DomServerScan.mq5 |
//+------------------------------------------------------------------+
#property description "Lists the symbols of the connected server that report a book depth above zero"
#property description "and calls MarketBookAdd() on each of them. No book entries are read."

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   ::PrintFormat("Server: %s",::AccountInfoString(ACCOUNT_SERVER));
   const int total=::SymbolsTotal(false);
   int reporting=0;
   for(int i=0;i<total;i++)
     {
      const string name=::SymbolName(i,false);
      long depth=0;
      if(!::SymbolInfoInteger(name,SYMBOL_TICKS_BOOKDEPTH,depth) || depth<=0)
         continue;
      ::ResetLastError();
      const bool added=::MarketBookAdd(name);
      const int error=::GetLastError();
      if(added)
         ::MarketBookRelease(name);
      ::PrintFormat("%s depth=%I64d bookadd=%s(%d)",name,depth,added?"true":"false",error);
      reporting++;
     }
   ::PrintFormat("Scanned %d symbols, %d report depth above 0",total,reporting);
   return;
  }
//+------------------------------------------------------------------+

The script and the indicator were run on four servers on 12 and 13 October 2026. The servers are called A to D in this article. Three were demo accounts and one was a live account. The table lists what was seen.

Server Symbols scanned Symbols reporting depth above 0 What was seen
Server A (demo) 12310 157 Forex pairs and metals reported 32, and indices reported 10. The panel drew books for EURUSD, XAUUSD, and AUDJPY. MSFT and NVDA exist on this server, reported 0, and MarketBookAdd() failed with error 4901.
Server B (demo) 7401 364 Forex, indices, metals, crypto, futures-style CFDs, and stock CFDs with.HK,.AD, and.DU suffixes. MarketBookAdd() succeeded on all of them. The panel drew books for UK100, XAUUSD, CocoaZ6_CFD, F40, and others. ETHUSD reported 0 and failed with error 4901. EURUSD and AUDJPY reported a depth above 0, subscribed, and returned an empty snapshot.
Server C (demo) 592 0 MarketBookAdd() failed with error 4901 on XAUUSD, EURUSD, NVIDIA, and MICROSOFT, which all reported 0.
Server D (live) 1646 0 MarketBookAdd() failed with error 4901 on EURUSD, AUDJPY, and GOLD. EURUSD and AUDJPY reported 0.

In these results a nonzero value of the property went with a successful MarketBookAdd(), and a value of zero went with error 4901. Only a few symbols were tried on the servers where the call failed, so this is an observation and not a rule. The sample is small: four servers and a few symbols on each. It is an example and not a statement about brokers or about SYMBOL_TICKS_BOOKDEPTH. The scan only checks whether the subscription is accepted, so a successful subscription does not show that the book has entries.

The property also does not say whether entries exist. EURUSD on Server B reported a depth of 10, subscribed successfully, and returned an empty array on each of 15 reads, one per second, in a short probe that is not part of the attached files.

The documentation points in the same direction. The MQL5 Programming for Traders book says an order book is available, as a rule, for exchange instruments, and that a broker may provide one for an OTC instrument. The MetaTrader 5 help says the book for an OTC instrument can be formed from the broker quotes.

Neither source says which servers provide a book, and this article makes no claim about any broker beyond the table.

On the servers where the subscription fails, the indicator keeps running and the Experts tab shows lines like the following. The panel shows "DOM unavailable" with the same error code.

DomLadderPanel: MarketBookAdd failed for XAUUSD error 4901


Interpreting the Panel

The mock-up below shows the layout with synthetic numbers. Bid volumes are on the left, the price is in the center, and ask volumes are on the right. Asks sit above the spread strip, bids sit below it, and the cumulative columns grow outward from the spread.

Layout mock-up

Figure 7: Layout mock-up with synthetic values. It is not live DOM data.

The next four screenshots come from the live terminal and are cropped to the panel. Each shows book levels at one moment and says nothing about trades. Figures 8 to 11 were taken on Server B.

The panel on USDTRY

Figure 8: The panel on USDTRY with status data OK, seven ask levels and seven bid levels, and a spread of 814 ticks.

The best ask is 49.42139 and the best bid is 49.41325, which gives the spread of 814 ticks shown in the strip. On the ask side the cumulative values grow from 100000 to 39600000, and the largest three levels are marked C1 to C3 by volume.

The panel on XAUUSD

Figure 9: The panel on XAUUSD with status data OK, a spread of 20 ticks, and the same shape of book as Figure 8.

In Figures 8 and 9 the volumes are round numbers and are identical on both sides, and the largest levels sit farthest from the market. The panel cannot show how the server forms such a book, and this article does not guess. In Figure 9 the best bid in the book is 4154.65, while the price line on the chart reads 4154.70, so the book and the quote are separate values and should not be treated as the same.

The panel on AUDJPY

Figure 10: The panel on AUDJPY with status No DOM data and the message "The book is empty".

The subscription succeeded, but the read returned no entries. The panel reports this as missing data and draws no zero volumes, and the chart still shows prices, with the price line at 108.885.

The panel on ETHUSD

Figure 11: The panel on ETHUSD with status DOM subscribe failed and the message "MarketBookAdd failed (error 4901)".

The server did not accept the subscription for this symbol. The panel shows the error code and does not guess the cause.


Extensions

The following ideas can be implemented to extend this project:

  • Combine the book with time and sales ticks, for example from CopyTicks(), to compare a level that disappears with trades at that price. Treat that as a separate measurement and label it as such.
  • Replace the top three rule with a threshold, such as a share of the total volume on a side.
  • Keep a short history of snapshots and show how long a level has been present.
  • Draw proportional volume bars behind the numbers.
  • Write the ladder to a file for later study.


Limitations and tradeoffs

Servers without DOM: A server may provide no book for a symbol. The subscription can fail with error 4901, as it did for every existing symbol tried on two of the four servers, or it can succeed and return an empty snapshot, as in Figure 10. The panel shows "DOM unavailable" in the first case and "No DOM data" in the second.

The threshold of two valid levels is a heuristic, and the input InpMinLevels changes it. The count covers both sides together, so a book with one bid and one ask is accepted, and so is a book with two levels on one side only. In the second case no spread can be shown.

Snapshot versus trades: The ladder lists price levels at the moment of the read, mostly resting limit orders. It does not record trades, so it cannot say what was bought or sold.

Spoofing and icebergs: A large level can be cancelled, can be spoofed, or can be an iceberg. A cluster is a ranking of the snapshot and is not liquidity that you can count on, and it is not a support or resistance level.

Fill versus cancel ambiguity: When a level disappears between two snapshots, the book does not say whether it was filled or cancelled. This code does not try to decide.

Unit differences: The panel shows the units the broker reports, and values cannot be compared across symbols. Because volume_real is used when it is nonzero and volume otherwise, a feed that mixes the two would mix their scales in the sums.

Invalid volume_real: A negative or non-finite volume_real rejects the entry even when volume holds a valid value, because the rule reads only one field.

Redraw cost on busy books: A changed snapshot triggers a full pass: validation, an insertion sort with quadratic cost in the number of entries, aggregation, cluster ranking, and a complete canvas redraw. The change detector compares raw arrays entry by entry on each book event and stops at the first difference. Deep books on busy symbols increase the cost. The row limit reduces drawing work but not aggregation. The change detector compares the double fields for exact equality, so a harmless difference in a value causes a redraw even when the aggregated ladder is the same.

Book versus quote: The spread strip reports the spread between the best bid and the best ask of the book. During testing the book spread differed from the quoted spread on some symbols, so the two numbers must not be treated as the same thing.

Column width: The columns and the font size are fixed. A volume with its label that is longer than about thirteen characters is clipped, and the panel has no abbreviation for large numbers. The layout was checked on one display only, so a different display scaling can change how the text fits.

Bucketing: A bucket size above one tick widens the displayed gap between bid and ask prices, which is why the spread strip uses the unbucketed best prices.

Subscription handling: The indicator checks the return values of MarketBookAdd() and MarketBookRelease() but does not retry a failed subscription. A failed release is reported once and is not retried, because the subscription flag is cleared. It uses one fixed object name, so a second copy on the same chart would try to create an object with the same name.

Terminal behavior that the documentation does not describe: The page for MarketBookGet() does not say what an empty snapshot looks like. On one server the call returned true with an empty array, which the panel reports with the message "The book is empty". The MqlBookInfo page does not describe the fields of market-order entries, and no market-order entries appeared in the books seen during testing, so that path was exercised by the tests only.

Test scope: The tests cover only the pure-logic classes, and only the cases listed in the assertions. They do not cover the reader, OnBookEvent(), the subscription and release logic, or the rendering.


Conclusion

We have followed a DOM snapshot through validation, price bucketing, sorting, aggregation, cumulative-volume calculation, cluster ranking, and canvas rendering. DomLadderPanel brings these steps together in a live indicator that groups volume by price level, marks up to three of the largest levels on each side, and reports the spread using the unbucketed best prices. When data is unavailable or the snapshot is empty, the panel shows a status message instead of drawing a ladder of zeros.

The included test script checks the calculation logic with synthetic inputs; it reports 150 passed assertions and 0 failures. Separate terminal checks demonstrate how the indicator handles available books, empty snapshots, and refused subscriptions. These checks have different scopes: the logic tests do not validate subscription handling or rendering, and the server observations do not establish which symbols or brokers will provide DOM data.

The finished indicator is a reading aid for the book supplied by the terminal. It makes a snapshot easier to inspect, but it does not show trades, explain why levels changed, or identify trading signals.


Programs used in the article:

# Name Type Description
1 DomTypes.mqh Include File Status enumeration, level structure, and statistics structure
2 DomLadder.mqh Include File
CDomLadder: stores levels, cumulative volume, spread, and the row split
3 DomLadderBuilder.mqh Include File
CDomLadderBuilder: validates, buckets, sorts, and aggregates a snapshot
4 DomClusterFinder.mqh Include File
CDomClusterFinder: ranks the three largest levels on each side
5 DomChangeDetector.mqh Include File
CDomChangeDetector: reports whether a snapshot differs from the previous one
6 DomBookReader.mqh Include File
CDomBookReader: the only class that calls the book functions and reads symbol properties
7 DomPanel.mqh Include File
CDomPanel: draws the ladder on a CCanvas bitmap label
8 DomLadderPanel.mq5 Custom Indicator Wires the classes together and handles terminal events
9 DomLadderTests.mq5 Script Tests of the pure-logic classes
10 DomServerScan.mq5 Script Lists the symbols of the connected server that report a book depth and tries the subscription on each
11 DomLadder_sources.zip Zip Archive Zip archive containing all the attached files and their paths relative to the terminal's root folder.
Attached files |
DomTypes.mqh (2.73 KB)
DomLadder.mqh (10.72 KB)
DomBookReader.mqh (5.33 KB)
DomPanel.mqh (19.34 KB)
DomLadderPanel.mq5 (6.76 KB)
DomLadderTests.mq5 (30.23 KB)
DomServerScan.mq5 (2.01 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.
Volatility Sizing Under Controlled Stress in MQL5 (Part 2): Heavy Tails, Outliers, and Risk Recovery Volatility Sizing Under Controlled Stress in MQL5 (Part 2): Heavy Tails, Outliers, and Risk Recovery
We study how additive, transient outliers affect volatility estimates and next‑bar sizing when the Part 1 rules remain fixed. Using standardized Student‑t returns and paired stress paths, we evaluate capped exposure under both base and complete‑return conditional risk. The article provides an MQL5 script and a CSV audit to reproduce decisions and verify results.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Gating Trades with the Wald-Wolfowitz Runs Test: An O(1) Randomness Filter for Bar Direction Gating Trades with the Wald-Wolfowitz Runs Test: An O(1) Randomness Filter for Bar Direction
A rolling Wald–Wolfowitz runs-test engine classifies recent bar direction as persistent, alternating, or indistinguishable from noise before any entry logic is applied. The package includes full MQL5 source, a chart indicator, a three-mode Expert Advisor (Gated, No gate, Placebo), validation scripts, and an audit log. An 18‑run Strategy Tester matrix with fixed window and critical value, plus a null‑rate calibration on real history, shows how a regime gate changes trade frequency and drawdown.