//+------------------------------------------------------------------+
//|                                                VolumeProfile.mqh |
//+------------------------------------------------------------------+
#ifndef VOLUMEPROFILE_MQH
#define VOLUMEPROFILE_MQH

//+------------------------------------------------------------------+
//| ResolveTickPrice                                                 |
//| Returns the price a tick represents, preferring last, then bid,  |
//| then ask, and returning 0.0 when none of the three is usable.    |
//| AddTick() below and the price-range scan in VolumeProfileEA.mq5  |
//| both call this same function, so the range that sizes the profile|
//| and the price that bins each tick can no longer disagree about   |
//| which field to read.                                             |
//+------------------------------------------------------------------+
double ResolveTickPrice(const MqlTick &tick)
  {
   if(tick.last > 0.0)
      return(tick.last);
   if(tick.bid > 0.0)
      return(tick.bid);
   if(tick.ask > 0.0)
      return(tick.ask);
   return(0.0);
  }

//+------------------------------------------------------------------+
//| CVolumeProfile                                                   |
//| Owns a pre-allocated array of price bins on a tick-size grid and |
//| aggregates tick volume into those bins in O(1) per tick.         |
//+------------------------------------------------------------------+
class CVolumeProfile
  {
private:
   double            m_bins[];
   int               m_bin_count;
   double            m_price_min;
   double            m_price_max;
   double            m_bin_size;
   double            m_total_volume;
   long              m_skipped_zero_price;

public:
                     CVolumeProfile(void);
                    ~CVolumeProfile(void);
   bool              Initialize(const double price_min, const double price_max, const double bin_size);
   void              AddTick(const MqlTick &tick);
   int               Aggregate(const MqlTick &ticks[], const int count);
   int               BinCount(void);
   double            BinVolume(const int index);
   double            BinPrice(const int index);
   double            BinSize(void);
   double            TotalVolume(void);
   int               MaxBinIndex(void);
   long              SkippedZeroPriceCount(void);
  };

//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CVolumeProfile::CVolumeProfile(void)
  {
   m_bin_count          = 0;
   m_price_min          = 0.0;
   m_price_max          = 0.0;
   m_bin_size           = 0.0;
   m_total_volume       = 0.0;
   m_skipped_zero_price = 0;
  }

//+------------------------------------------------------------------+
//| Destructor                                                       |
//+------------------------------------------------------------------+
CVolumeProfile::~CVolumeProfile(void)
  {
  }

//+------------------------------------------------------------------+
//| Initialize                                                       |
//| Allocates the price bin array from the given price range and     |
//| tick-size grid, then zeroes every bin. The bin count is derived  |
//| from the range divided by the bin size, with one extra bin added |
//| to absorb rounding at the top edge. A zero-width range (every    |
//| valid tick at one price) is accepted and yields a single bin.    |
//| Returns true on success.                                         |
//+------------------------------------------------------------------+
bool CVolumeProfile::Initialize(const double price_min, const double price_max, const double bin_size)
  {
   if(bin_size <= 0.0 || price_max < price_min)
      return(false);

//--- store the tick-size grid parameters
   m_price_min = price_min;
   m_price_max = price_max;
   m_bin_size  = bin_size;

//--- size the array from the price range, with one extra bin for edge rounding
   m_bin_count = (int)::MathRound((price_max - price_min) / bin_size) + 1;
   if(::ArrayResize(m_bins, m_bin_count) != m_bin_count)
      return(false);

//--- zero every bin and reset the running total
   ::ArrayInitialize(m_bins, 0.0);
   m_total_volume       = 0.0;
   m_skipped_zero_price = 0;

   return(true);
  }

//+------------------------------------------------------------------+
//| AddTick                                                          |
//| AddTick computes the destination bin for a single tick in O(1)   |
//| using direct index arithmetic on the tick-size grid, then        |
//| increments that bin. Real volume is used when the tick carries   |
//| one, kept as a double so a fractional volume_real is not         |
//| truncated; otherwise the tick counts as one unit of volume, which|
//| is the correct fallback on symbols without trade volume. The     |
//| tick's price comes from ResolveTickPrice(), which returns 0.0    |
//| when last, bid, and ask are all zero or missing; such a tick is  |
//| skipped outright and counted in m_skipped_zero_price rather than |
//| being binned at an edge, since binning it there would silently   |
//| distort the profile. A tick with a valid price that simply falls |
//| outside the pre-allocated range is still clamped to the nearest  |
//| edge bin rather than dropped, which remains a known source of    |
//| distortion between refreshes (see the article's limitations).    |
//+------------------------------------------------------------------+
void CVolumeProfile::AddTick(const MqlTick &tick)
  {
   double price = ResolveTickPrice(tick);
   if(price <= 0.0)
     {
      m_skipped_zero_price++;
      return;
     }

//--- compute the bin index directly from the quantized price offset
   int bin = (int)::MathRound((price - m_price_min) / m_bin_size);

//--- clamp out of range prices to the nearest edge bin
   if(bin < 0)
      bin = 0;
   if(bin >= m_bin_count)
      bin = m_bin_count - 1;

//--- prefer real volume (fractional part preserved), fall back to a
//--- tick count of one
   double vol = (tick.volume_real > 0.0) ? tick.volume_real : 1.0;
   if(tick.volume > 0 && tick.volume_real <= 0.0)
      vol = (double)tick.volume;

   m_bins[bin]    += vol;
   m_total_volume += vol;
  }

//+------------------------------------------------------------------+
//| Aggregate                                                        |
//| Aggregate runs AddTick across the full tick array in a single    |
//| aggregation pass, which is the O(n) sweep that replaces the      |
//| naive O(n x m) nested-loop approach described in Section 1.      |
//+------------------------------------------------------------------+
int CVolumeProfile::Aggregate(const MqlTick &ticks[], const int count)
  {
   int processed = 0;
//--- single aggregation pass over the full tick array
   for(int i = 0; i < count; i++)
     {
      AddTick(ticks[i]);
      processed++;
     }
   return(processed);
  }

//+------------------------------------------------------------------+
//| BinCount                                                         |
//+------------------------------------------------------------------+
int CVolumeProfile::BinCount(void)
  {
   return(m_bin_count);
  }

//+------------------------------------------------------------------+
//| BinVolume                                                        |
//+------------------------------------------------------------------+
double CVolumeProfile::BinVolume(const int index)
  {
   if(index < 0 || index >= m_bin_count)
      return(0.0);
   return(m_bins[index]);
  }

//+------------------------------------------------------------------+
//| BinPrice                                                         |
//+------------------------------------------------------------------+
double CVolumeProfile::BinPrice(const int index)
  {
   if(index < 0 || index >= m_bin_count)
      return(0.0);
   return(m_price_min + index * m_bin_size);
  }

//+------------------------------------------------------------------+
//| BinSize                                                          |
//| Returns the price height of one bin. The renderer uses it so a   |
//| single-bin profile still has a visible bar height.               |
//+------------------------------------------------------------------+
double CVolumeProfile::BinSize(void)
  {
   return(m_bin_size);
  }

//+------------------------------------------------------------------+
//| TotalVolume                                                      |
//+------------------------------------------------------------------+
double CVolumeProfile::TotalVolume(void)
  {
   return(m_total_volume);
  }

//+------------------------------------------------------------------+
//| MaxBinIndex                                                      |
//+------------------------------------------------------------------+
int CVolumeProfile::MaxBinIndex(void)
  {
   int    best_index  = 0;
   double best_volume = 0.0;

//--- linear scan for the highest volume bin
   for(int i = 0; i < m_bin_count; i++)
     {
      if(m_bins[i] > best_volume)
        {
         best_volume = m_bins[i];
         best_index  = i;
        }
     }
   return(best_index);
  }

//+------------------------------------------------------------------+
//| SkippedZeroPriceCount                                            |
//| Returns how many ticks in the most recent Initialize()/AddTick() |
//| cycle had no valid price (last, bid, and ask all zero or         |
//| missing) and were skipped rather than binned.                    |
//+------------------------------------------------------------------+
long CVolumeProfile::SkippedZeroPriceCount(void)
  {
   return(m_skipped_zero_price);
  }

#endif // VOLUMEPROFILE_MQH
//+------------------------------------------------------------------+