Streaming Percentiles in MQL5: Testing the P-Square Algorithm on Real Tick Data
Contents
- Introduction
- What is already published
- Exact percentiles and how I measure an error
- The P-Square algorithm
- The CPSquare class
- Checking CPSquare against the paper
- Accuracy on generated data
- Real ticks in time order
- Exact counters for whole numbers
- Log buckets for continuous values
- Tests
- Cost
- Using the classes in an EA
- Python consistency check
- Which class to use
- Limitations
- What the checks do not cover
- Conclusion
- Attached files
Introduction
An EA often needs a percentile of a value observed on every tick. A spread filter can block entries when the spread is above its own 95th percentile. A feed monitor can raise an alarm when no tick arrives for longer than the 99.9th percentile of normal gaps between ticks. Computing the exact percentile requires storing all values. For one month of EURUSD ticks on MetaQuotes-Demo, that is 5,443,254 values per series, about 43 MB of doubles, and a sort each time the threshold must be updated.
The P-Square algorithm of Raj Jain and Imrich Chlamtac (Communications of the ACM, 1985) estimates a percentile without storing the values. The result is an approximation and can differ from the exact percentile of a full sort. The algorithm keeps five markers on the distribution and moves them with a parabolic formula as values arrive. Nothing else is stored. My plan for this article was a spread gate built on P-Square.
I implemented the algorithm as the CPSquare class and validated it in two ways. The class reproduced every marker position of the worked example in the paper. On generated data in random order, the median rank error after one million values was below 0.01 percentage points for four continuous distributions. Then I gave it real ticks in the order they arrived. For the 90th percentile of the time between EURUSD ticks, the exact answer was 801 ms and P-Square returned 4,346.63 ms. For the 95th percentile of the XAUUSD spread, the exact answer was 52 points and P-Square returned 5,645.75 points. Shuffled into a random order, the same ticks gave 821.82 ms and 52.90 points.
A spread gate based on P-Square performed poorly on these data. This article presents the implementation, the validation against the paper, and the measurements on generated and real ticks. The article also explains why the spread estimate on time-ordered ticks remained wrong for the whole month. It names the part of the error that this mechanism does not explain. Then the article adds two classes whose answer does not depend on the order of the values:
- CCountQuantile keeps one counter per whole number and returns the exact percentile of whole numbers, such as a spread rounded to whole points.
- CLogQuantile keeps counters on a logarithmic grid, the bucket rule of DDSketch. Between a minimum and a maximum that you set, every percentile it returns lies within a relative error that you choose (0.5% in this article) of the exact one.
The checks consist of 66 unit checks, six mutation runs, and a Python consistency check that recomputes the main numbers from the raw values with a second implementation.
What is already published
The closest MQL5 article is Adaptive Spread Monitoring and Order Gating in MQL5. That article compares the live spread with percentiles from a rolling histogram of fixed bins over the last N ticks. My CCountQuantile class belongs to the same family. The difference is in what I measured: the article here compares three ways to get a percentile on the same real ticks and shows where one of the three fails.
The standard library computes exact sample percentiles. MathQuantile() in Math\Stat\Math.mqh sorts a copy of the array and uses type 7 of Hyndman and Fan, the default of R. The Statistical Distributions in MQL5 article describes that library. ALGLIB has CAlglib::SamplePercentile(). Both need all values in memory. I found no MQL5 articles implementing P-Square or a sketch with a relative error guarantee, and the MQL5 search for "Jain Chlamtac" returned no article.
Outside MQL5, the log-bucket rule comes from DDSketch by Charles Masson, Jee E. Rim, and Homin K. Lee (PVLDB, 2019). I use the bucket index and the representative value. I did not implement the bucket collapsing of DDSketch, because a fixed range of values is enough here.
| Method | What it stores | Does the order of values matter | Error |
|---|---|---|---|
| MathQuantile() | Every value | No | Exact |
| CPSquare | Five heights and five positions | Yes, on real ticks in time order | No bound |
| CCountQuantile | One counter per whole number from 0 to a maximum | No | Exact for whole numbers |
| CLogQuantile | One counter per bucket of a logarithmic grid | No | Within alpha of the exact value, relatively |
Exact percentiles and how I measure an error
All exact values in this article use the type 7 rule of MathQuantile(). For n sorted values and a probability p, the rule takes the value at the 0-based rank (n-1)p. When that rank falls between two values, the rule interpolates between those two values. The helper PsqTypeSevenSorted() repeats the expression of MathQuantile() on an array that is already sorted:
//+------------------------------------------------------------------+ //| PsqTypeSevenSorted | //| Quantile of the first n values of a sorted array, by the rule | //| MathQuantile() uses (Hyndman and Fan type 7): the value at the | //| 0-based rank (n-1)*p, interpolated between the two neighbors. | //| Returns NaN when n is below 1 or above the array size, or when p | //| is outside [0,1]. | //+------------------------------------------------------------------+ double PsqTypeSevenSorted(const double &sorted[],const int n,const double p) { if(n<1 || n>ArraySize(sorted) || !(p>=0.0 && p<=1.0)) return((double)"nan"); double ind=(n-1)*p; int lo=(int)MathFloor(ind); int hi=(int)MathCeil(ind); double q=sorted[lo]; if(ind>lo) { double gamma=(ind-lo); q=(1.0-gamma)*q+gamma*sorted[hi]; } return(q); }
A unit check confirms that both functions return bit-identical results in 42 cases.
An error in the units of the data says little across distributions. I therefore also measure a rank error. For an estimate v, I count the values below v and the values at or below v. If p lies between these two shares, the rank error is zero. Otherwise it is the distance from p to the nearer share, positive when v is too high. The two shares matter for data with ties. For a spread that is 0 or 1 point on 97.7% of ticks, any threshold between 0 and 1 has the same rank, while 1 itself covers a whole range of ranks. A rank error of +5 percentage points for p=0.95 means that the estimate sits above all values.
The rank error uses only the two counts, so it does not depend on the type 7 rule. The value comparisons use type 7. Other quantile types interpolate between neighbor values in a different way. On the real ticks, the values near each tested percentile are whole numbers of points or ms. The P-Square errors on real ticks in time order are far larger than the step between two neighbor values, so the choice of type 7 does not explain them. In the real tick tests below, every method is compared with the same exact value of the same ticks.
The P-Square algorithm
P-Square keeps five markers. Marker 1 is the minimum and marker 5 is the maximum. Marker 3 estimates the p-quantile, and markers 2 and 4 estimate the quantiles p/2 and (1+p)/2. Each marker has a height, the current estimate of its quantile, and a position, the number of values at or below that height.
For a new value x, the algorithm does three things:
- The algorithm finds the cell of x between two markers. A new minimum or maximum becomes the height of marker 1 or marker 5.
- Every marker above x moves one position to the right, because one more value lies below it.
- Each middle marker that is at least one position away from its desired position moves one step toward it. The new height comes from a parabola through the marker and its two neighbors. If the parabola would put the height outside its neighbors, a straight line toward the neighbor gives the height instead.
The desired position of marker i after n values is 1+(n-1)f. The fraction f is 0, p/2, p, (1+p)/2, and 1 for the five markers. Fig. 1 shows the state after the 20 values of the example in the paper.
The five P-Square markers after the worked example of the paper
The median of 20 values, Table I of Jain and Chlamtac

Fig. 1. Steps show the sorted 20 values. The five markers sit on the steps at positions 1, 6, 10, 16, and 20. Marker 3 at 4.44 is the median estimate, while the exact type 7 median of the 20 values is 2.43
The estimate depends only on the five markers. When a marker height is wrong, the only way to correct it is through these steps. The real tick results below show how slow that can be.
The CPSquare class
The class stores the probability, the fraction of each desired position, five heights, and five positions. The class also counts the values, the refused values, and the moves made with each formula. The counters of moves are for reports and tests.
//+------------------------------------------------------------------+ //| CPSquare | //| Streaming estimate of one quantile with the P-Square algorithm | //| (Jain and Chlamtac, 1985). It keeps five markers and no values. | //+------------------------------------------------------------------+ class CPSquare { private: double m_p; // probability of the quantile, 0 < p < 1 double m_f[5]; // desired position of each marker as a fraction of n-1 double m_q[5]; // marker heights, the first values while fewer than five long m_n[5]; // marker positions, 1-based long m_count; // accepted values long m_rejected; // NaN and infinite values that were refused long m_parabolic; // marker moves that used the parabolic formula long m_linear; // marker moves where the linear formula replaced it bool m_ready; // Init() succeeded //--- double Parabolic(const int i,const int d) const; double Linear(const int i,const int d) const; public: CPSquare(void); bool Init(const double p); void Reset(void); bool Add(const double x); bool Value(double &value) const; double Desired(const int i) const; bool Save(const int handle) const; bool Load(const int handle); //--- state for reports and tests double P(void) const { return(m_p); } long Count(void) const { return(m_count); } long Rejected(void) const { return(m_rejected); } long ParabolicMoves(void) const { return(m_parabolic); } long LinearMoves(void) const { return(m_linear); } double Height(const int i) const { return(m_q[i]); } long Position(const int i) const { return(m_n[i]); } };
Add() follows the algorithm of the paper. The first five values are kept sorted and become the markers. After that, each value updates the markers:
//+------------------------------------------------------------------+ //| CPSquare::Add | //| Adds one value. NaN and infinity are refused and counted. | //+------------------------------------------------------------------+ bool CPSquare::Add(const double x) { if(!m_ready) return(false); if(!MathIsValidNumber(x)) { m_rejected++; return(false); } //--- the first five values are kept sorted, they become the markers if(m_count<5) { int j=(int)m_count; while(j>0 && m_q[j-1]>x) { m_q[j]=m_q[j-1]; j--; } m_q[j]=x; m_count++; if(m_count==5) for(int i=0; i<5; i++) m_n[i]=i+1; return(true); } //--- a new minimum or maximum becomes the height of the extreme marker if(x<m_q[0]) m_q[0]=x; if(x>m_q[4]) m_q[4]=x; //--- cell k of x: m_q[k] <= x < m_q[k+1], the last cell includes m_q[4] int k=0; while(k<3 && x>=m_q[k+1]) k++; //--- every marker above the cell moves one position to the right for(int i=k+1; i<5; i++) m_n[i]++; m_count++; //--- move the three middle markers toward their desired positions for(int i=1; i<=3; i++) { double d=Desired(i)-(double)m_n[i]; if((d>=1.0 && m_n[i+1]-m_n[i]>1) || (d<=-1.0 && m_n[i-1]-m_n[i]<-1)) { int s=(d>0.0 ? 1 : -1); double q=Parabolic(i,s); if(m_q[i-1]<q && q<m_q[i+1]) { m_q[i]=q; m_parabolic++; } else { m_q[i]=Linear(i,s); m_linear++; } m_n[i]+=s; } } return(true); }
I made one change to the paper. The paper adds a fixed increment to each desired position after every value. Desired() computes the position from the count instead. Both give the same number in exact arithmetic. The increment adds a rounding error with every value, and after millions of values that error could move a marker one value earlier or later. The count gives the same result in the MQL5 code and in the Python check, without an error that grows.
The two height formulas are short:
//+------------------------------------------------------------------+ //| CPSquare::Parabolic | //| Piecewise-parabolic (P-Square) prediction of the height of | //| marker i after a move of one position, d = +1 or d = -1. | //+------------------------------------------------------------------+ double CPSquare::Parabolic(const int i,const int d) const { double n0=(double)m_n[i-1]; double n1=(double)m_n[i]; double n2=(double)m_n[i+1]; double dd=(double)d; return(m_q[i]+dd/(n2-n0)*((n1-n0+dd)*(m_q[i+1]-m_q[i])/(n2-n1) +(n2-n1-dd)*(m_q[i]-m_q[i-1])/(n1-n0))); }
//+------------------------------------------------------------------+ //| CPSquare::Linear | //| Linear prediction toward the neighbor in the direction of d. | //+------------------------------------------------------------------+ double CPSquare::Linear(const int i,const int d) const { return(m_q[i]+d*(m_q[i+d]-m_q[i])/(double)(m_n[i+d]-m_n[i])); }
Value() returns false before the first value. Up to five values it returns the exact type 7 percentile of those values. From the sixth value on it returns the height of marker 3:
//+------------------------------------------------------------------+ //| CPSquare::Value | //| Current estimate. Up to five values it is the exact type 7 | //| quantile of those values, after that the height of marker 3. | //| Returns false while no value was added. | //+------------------------------------------------------------------+ bool CPSquare::Value(double &value) const { if(!m_ready || m_count==0) return(false); if(m_count<=5) value=PsqTypeSevenSorted(m_q,(int)m_count,m_p); else value=m_q[2]; return(true); }
Values that are NaN or infinite are refused and counted, and they leave the markers unchanged. Save() and Load() write and read the whole state as binary data. Load() checks a magic number, the version, the probability, the order of the heights, and the positions before it changes anything.
Checking CPSquare against the paper
Table I of the paper follows the median estimate through 20 values from an exponential distribution with a mean of 10. The table lists the positions and heights of the five markers after each value. The paper has an erratum: the second value is 0.15, not 0.5. With that correction, TestPSquare feeds the 20 values to CPSquare and compares every row.
My first version of this check compared heights rounded to two decimals, and 11 of the 15 rows failed. All marker positions matched. The heights differed from the table by at most 0.0161:
PASS paper Table I, value 18: positions equal, heights within 0.02 PASS paper Table I, value 19: positions equal, heights within 0.02 PASS paper Table I, value 20: positions equal, heights within 0.02 paper Table I: largest height difference 0.0161 PASS paper Table I, final median estimate 4.44
The largest difference is in marker 4 after the 17th value. My class has 17.2039 there, and the table has 17.22. I can only guess the reason. The table prints the values with two decimals, so the authors probably worked with more digits than they printed. I did not find their unrounded values. The check now requires equal positions and heights within 0.02. The final median estimate is 4.4406, and the table shows 4.44. The Python check gives the same heights to four decimals.
Accuracy on generated data
The script AccuracyPSquare generates streams of one million values and feeds them to five estimators at once. At four checkpoints it sorts the values seen so far and computes the exact percentiles. The generator is SplitMix64, so the same seed gives the same values on every machine.
| Setting | Values |
|---|---|
| Distributions | Uniform on (0,1), standard normal, exponential with mean 1, lognormal (exp of a standard normal), Pareto with shape 1.5, whole numbers from the floor of three times an exponential |
| Orders | Random, sorted ascending, regime (the second half multiplied by 3) |
| Seeds | 20 for random and regime orders, one for sorted order |
| Probabilities | 0.5, 0.9, 0.95, 0.99, and 0.999 |
| Checkpoints | 1,000, 10,000, 100,000, and 1,000,000 values |
The next table shows the median and the largest absolute rank error over 20 seeds after one million values in random order, in percentage points.
| Distribution | p=0.5 | p=0.9 | p=0.95 | p=0.99 | p=0.999 |
|---|---|---|---|---|---|
| Uniform | 0.002 (max 0.009) | 0.001 (max 0.004) | 0.001 (max 0.004) | 0.001 (max 0.002) | 0.000 (max 0.001) |
| Normal | 0.003 (max 0.012) | 0.004 (max 0.009) | 0.004 (max 0.010) | 0.002 (max 0.005) | 0.001 (max 0.002) |
| Exponential | 0.003 (max 0.013) | 0.005 (max 0.016) | 0.005 (max 0.008) | 0.003 (max 0.008) | 0.001 (max 0.002) |
| Lognormal | 0.006 (max 0.017) | 0.006 (max 0.017) | 0.005 (max 0.013) | 0.003 (max 0.009) | 0.001 (max 0.003) |
| Pareto | 0.047 (max 0.230) | 0.042 (max 0.193) | 0.031 (max 0.133) | 0.013 (max 0.039) | 0.002 (max 0.010) |
| Discrete | 1.336 (max 13.265) | 0.309 (max 3.478) | 0.020 (max 0.074) | 0.063 (max 0.081) | 0.010 (max 0.029) |
For the four continuous distributions with light or moderate tails, the largest error was 0.017 percentage points. The Pareto distribution with shape 1.5 has an infinite variance. Its errors were larger, up to 0.23 percentage points at the median. The discrete distribution is the case that the paper warns about. With whole numbers, the median estimate fell between two values in some seeds. The worst seed missed by 13.27 percentage points.
Order changed the picture. The table below shows the same statistics for the regime order. In those streams, the second half of the values is three times larger than the first half.
| Distribution | p=0.5 | p=0.9 | p=0.95 | p=0.99 | p=0.999 |
|---|---|---|---|---|---|
| Uniform | 8.573 (max 8.603) | 0.081 (max 0.113) | 0.046 (max 0.060) | 0.008 (max 0.015) | 0.001 (max 0.003) |
| Normal | 0.021 (max 0.047) | 3.112 (max 3.252) | 1.556 (max 1.641) | 0.313 (max 0.336) | 0.030 (max 0.035) |
| Exponential | 8.406 (max 8.673) | 3.471 (max 3.544) | 1.755 (max 1.816) | 0.346 (max 0.362) | 0.032 (max 0.036) |
| Lognormal | 10.230 (max 10.367) | 3.525 (max 3.561) | 1.848 (max 1.874) | 0.381 (max 0.393) | 0.038 (max 0.041) |
| Pareto | 14.326 (max 14.442) | 3.326 (max 3.382) | 1.690 (max 1.746) | 0.345 (max 0.363) | 0.034 (max 0.040) |
| Discrete | 11.147 (max 11.241) | 3.059 (max 3.110) | 1.506 (max 1.535) | 0.342 (max 0.361) | 0.038 (max 0.042) |
For five of the six distributions, the median error at p=0.95 was between 1.5 and 1.9 percentage points. The uniform distribution had a small error at p=0.95, but it missed the median by 8.6 points. The largest median error was 14.3 points, for the median of the Pareto streams. The change starts at value 500,001, so only the checkpoint at one million values lies after it. Fig. 2 shows the rank error at p=0.95 over the four checkpoints for both orders.
Rank error of P-Square at p=0.95 by number of values
Median over 20 seeds, random order and regime order

Fig. 2. For random order, the rank error falls as the number of values grows. For regime order, the curves equal those of random order up to 100,000 values, because the change starts later. At one million values, five distributions are at 1.5 to 1.9 percentage points, and the uniform distribution is at 0.05
Sorted order is a hard case for the markers. In sorted order, the error at p=0.95 was between 0.02 and 1.26 points. The full results are in the CSV file that the script writes.
Real ticks in time order
Results
TickQuantiles reads real ticks with CopyTicksRange() and COPY_TICKS_INFO, one day at a time. For each tick it computes the spread in points and the time since the previous tick in ms. The script feeds both series to CPSquare estimators in time order. At the end, the script sorts every value for the exact percentiles. Then it shuffles the same values with a Fisher-Yates shuffle (SplitMix64, seed 1) and feeds them to new estimators.
| Setting | Value |
|---|---|
| Server | MetaQuotes-Demo |
| Terminal build | 6252 |
| Symbols | EURUSD (point 0.00001), XAUUSD (point 0.01) |
| Period | 2026.09.01 00:00 to 2026.10.01 00:00, server time |
| Ticks | EURUSD 5,443,254, XAUUSD 10,667,469, none skipped |
| Warm-up of the gates | 1,000 ticks |
| Series | p | Exact | P-Square, time order | P-Square, shuffled | Counters or log buckets |
|---|---|---|---|---|---|
| EURUSD spread, points | 0.5 | 0.00 | 0.50 | 0.00 | 0.00 |
| EURUSD spread, points | 0.9 | 1.00 | 16.85 | 1.00 | 1.00 |
| EURUSD spread, points | 0.95 | 1.00 | 22.18 | 1.00 | 1.00 |
| EURUSD spread, points | 0.99 | 2.00 | 12.00 | 2.00 | 2.00 |
| EURUSD gap, ms | 0.5 | 83.00 | 98.11 | 84.45 | 82.68 |
| EURUSD gap, ms | 0.9 | 801.00 | 4,346.63 | 821.82 | 800.35 |
| EURUSD gap, ms | 0.99 | 4,276.48 | 13,757.45 | 4,438.79 | 4,294.36 |
| EURUSD gap, ms | 0.999 | 13,284.50 | 43,878.11 | 13,225.49 | 13,293.98 |
| XAUUSD spread, points | 0.5 | 33.00 | 35.57 | 33.00 | 33.00 |
| XAUUSD spread, points | 0.9 | 47.00 | 4,749.20 | 47.93 | 47.00 |
| XAUUSD spread, points | 0.95 | 52.00 | 5,645.75 | 52.90 | 52.00 |
| XAUUSD spread, points | 0.99 | 65.00 | 5,892.10 | 65.00 | 65.00 |
| XAUUSD gap, ms | 0.5 | 55.00 | 94.22 | 55.00 | 54.87 |
| XAUUSD gap, ms | 0.9 | 354.00 | 1,510.80 | 369.00 | 352.49 |
| XAUUSD gap, ms | 0.99 | 1,252.00 | 5,947.83 | 1,264.12 | 1,255.20 |
| XAUUSD gap, ms | 0.999 | 3,604.00 | 11,288.18 | 3,637.89 | 3,586.94 |
At p=0.9 and above, every P-Square value in time order is far from the exact one. At p=0.5 the error is smaller. For example, the XAUUSD spread gives 35.57 against an exact 33 points, and the EURUSD gap gives 98.11 against an exact 83 ms. For the EURUSD spread, the exact 95th percentile is 1 point and P-Square returns 22.18 points. The shuffled values give estimates close to the exact ones in value. On the EURUSD spread, close in value is not enough. The shuffled estimate for p=0.9 is 0.99999999908 points, and the one for p=0.95 is 1.0000000014 points. The first lies below every tick at 1 point, so its rank error is -35.6 percentage points. The second lies above every tick at 1 point, so its rank error is +2.7 points. These two rank errors are the tie problem from the generated data tests, this time on real data.
Why the estimate stays wrong
The month starts at 00:00 server time, in the rollover hour. The first EURUSD ticks of the period have spreads of 12 and 25 points, while 97.7% of all ticks in the month have a spread of 0 or 1 point. The first XAUUSD ticks have spreads between 1,165 and 6,792 points. These first values set the markers, and the markers did not recover within the month. The script prints the first 20 spreads of each run:
EURUSD first 20 spreads in points: 12 25 25 25 25 25 25 25 25 25 25 25 25 3 12 12 12 12 11 12
XAUUSD first 20 spreads in points: 4227 1175 1165 6344 5558 5518 5927 6152 6150 6149 6148 6146 6761 6762 6792 6151 6157 6153 6147 6639
Fig. 3 follows the P-Square estimate of the 95th percentile of the EURUSD spread at the end of each day, against the exact value.
P-Square estimate and exact value at the end of each day
EURUSD spread, 95th percentile, ticks from 00:00 and from 02:00 server time

Fig. 3. The exact value is 1 point on every day. The estimate of the run from 00:00 starts at 22.58 points and falls only to 22.18 points by the end of the month. The run that starts at 02:00 ends at 1.90 points
The reason is in the formula. A marker moves one position at a time, and the height of a move comes from its neighbors. For a move toward marker 2, the linear formula changes the height by (q3-q2)/(n3-n2). The final markers of the EURUSD spread estimator for p=0.95 show the size of that step:
EURUSD spread p=0.950 markers: heights 0.0000 0.0046 22.1816 22.1818 168.0000, positions 1 2585546 5171092 5307173 5443254
Marker 3 is 22.18 points above marker 2 and 2,585,546 positions away from it. One linear move toward marker 2 therefore lowers the height by about 0.0000086 points. The parabolic formula also uses the slope toward marker 4. Marker 4 is only 0.0002 points above marker 3, so that slope is even smaller. At the start of the month, the positions were close together, and each move changed the height by a large amount. The first ticks, with spreads of 12 and 25 points, set marker 3 high in that phase. Later, the steps became tiny as the count grew. In Fig. 3, the estimate fell from 22.58 points after the first day to 22.18 points after the last day.
To check that the start matters, I ran the script again with the first tick at 02:00, after the rollover hour. Everything else stayed the same:
| Series | p | Exact from 02:00 | P-Square from 00:00 | P-Square from 02:00 |
|---|---|---|---|---|
| EURUSD spread, points | 0.5 | 0.00 | 0.50 | 0.42 |
| EURUSD spread, points | 0.9 | 1.00 | 16.85 | 1.00 |
| EURUSD spread, points | 0.95 | 1.00 | 22.18 | 1.90 |
| EURUSD spread, points | 0.99 | 2.00 | 12.00 | 3.41 |
| EURUSD gap, ms | 0.5 | 83.00 | 98.11 | 98.11 |
| EURUSD gap, ms | 0.9 | 800.00 | 4,346.63 | 2,678.83 |
| EURUSD gap, ms | 0.99 | 4,256.00 | 13,757.45 | 10,846.64 |
| EURUSD gap, ms | 0.999 | 13,129.48 | 43,878.11 | 19,337.26 |
| XAUUSD spread, points | 0.5 | 33.00 | 35.57 | 35.52 |
| XAUUSD spread, points | 0.9 | 47.00 | 4,749.20 | 68.11 |
| XAUUSD spread, points | 0.95 | 52.00 | 5,645.75 | 83.58 |
| XAUUSD spread, points | 0.99 | 65.00 | 5,892.10 | 126.52 |
| XAUUSD gap, ms | 0.5 | 55.00 | 94.22 | 94.25 |
| XAUUSD gap, ms | 0.9 | 354.00 | 1,510.80 | 1,368.32 |
| XAUUSD gap, ms | 0.99 | 1,251.00 | 5,947.83 | 6,509.14 |
| XAUUSD gap, ms | 0.999 | 3,567.00 | 11,288.18 | 7,084.86 |
The later start lowered the spread estimates at p=0.9 and above a lot. For the EURUSD spread at p=0.95, the estimate fell from 22.18 to 1.90 points, and for XAUUSD from 5,645.75 to 83.58 points. Neither reached the exact value: 1.90 points still lies above every EURUSD tick at 1 point. The gap estimates stayed far from the exact values. For EURUSD at p=0.9 the estimate was 2,678.83 ms against an exact 800 ms. For XAUUSD at p=0.99 it even rose, from 5,947.83 to 6,509.14 ms. So the first ticks explain a large part of the spread error, but not all of it. For the gap series, the start at 02:00 left a large part of the error, and I have not established its cause. The start at 02:00 is not a fix either. The rollover returns every day, and an EA cannot choose its first ticks.
Shuffling does not isolate a single factor. It changes the initial values, the clustering of extreme values, and the local dependence between adjacent ticks at the same time. The comparison shows that the P-Square result depends on the order of these ticks. It does not show which property of the order causes the error.
What the error does to a spread gate
The script also simulates a gate that blocks a tick when its spread is above the 95th percentile of all ticks before it. After the warm-up, it compares three thresholds: the P-Square estimate, that estimate rounded to a whole point, and the exact value from CCountQuantile. I call the third variant the exact gate. Its threshold is the exact 95th percentile of the earlier ticks. The share of ticks that it blocks is not fixed at 5%, as the results below show.
| Symbol | Ticks decided | Blocked, P-Square | Blocked, P-Square rounded | Blocked, exact |
|---|---|---|---|---|
| EURUSD | 5,442,254 | 300 (0.0055%) | 300 (0.0055%) | 122,807 (2.257%) |
| XAUUSD | 10,666,469 | 38 (0.0004%) | 38 (0.0004%) | 448,314 (4.203%) |
The P-Square gate blocked almost nothing, because its threshold sat above nearly every spread. The exact gate blocked 2.257% of EURUSD ticks instead of 5%. The reason is ties. With a threshold of 1 point, every tick at 1 point passes. Over the whole month, 2.276% of the EURUSD ticks have a spread above 1 point. A percentile threshold on whole numbers does not block exactly 5% of ticks.
Exact counters for whole numbers
A spread in points is a whole number with a small range. For such data, the paper itself recommends keeping a count for each value instead of P-Square. CCountQuantile does that. Exact here means exact for the rounded spread. The scripts and the EA compute (ask-bid)/point and round it with MathRound(). A quote that is not a whole number of points is therefore counted at the nearest whole point. Add() refuses negative, fractional, NaN, and infinite values, as well as values above the maximum, and counts them. Value() finds the values at the two type 7 ranks by summing counters from 0 upward:
//+------------------------------------------------------------------+ //| CCountQuantile::ValueAtRank | //| Value at a 0-based rank of the sorted values held. | //+------------------------------------------------------------------+ int CCountQuantile::ValueAtRank(const long rank) const { long seen=0; for(int v=0; v<=m_max; v++) { seen+=m_counts[v]; if(seen>rank) return(v); } return(m_max); }
//+------------------------------------------------------------------+ //| CCountQuantile::Value | //| Exact type 7 quantile, the rule of MathQuantile(). | //+------------------------------------------------------------------+ bool CCountQuantile::Value(const double p,double &value) const { if(m_count==0 || !MathIsValidNumber(p) || p<0.0 || p>1.0) return(false); double ind=(m_count-1)*p; long lo=(long)MathFloor(ind); long hi=(long)MathCeil(ind); double q=(double)ValueAtRank(lo); if(ind>lo) { double gamma=(ind-lo); q=(1.0-gamma)*q+gamma*(double)ValueAtRank(hi); } value=q; return(true); }
The answer depends only on how many times each value occurred, not on the order. The memory is one long per value. A maximum of 20,000 points takes 160 KB. The time of Value() grows with the spread at the requested rank, because the loop stops there.
My first run of the XAUUSD ticks used a maximum of 5,000 points. CCountQuantile refused 91 spreads above that, and they were missing from the exact gate. The scripts and the EA now use 20,000 points, and the run in the tables refused 0 spreads. A symbol with larger spreads in points needs a larger maximum. The Rejected() counter shows when the maximum was too small.
Remove() takes a value back and allows a moving window: the EA keeps the last N spreads in a ring buffer and removes the oldest one when it adds a new one. The tests check Remove(). The tick runs in this article do not use a window.
Fig. 4 shows where the exact EURUSD gate blocked ticks, by server hour.
Ticks blocked by the exact spread gate, by server hour
EURUSD, p=0.95 over all ticks before each tick

Fig. 4. The gate blocks 88% of the ticks of hour 0. Hours 1, 8, 9, and 23 follow with 9% to 25%. During every other hour, the gate blocks under 2% of ticks
With one threshold for the whole day, 51% of the blocked ticks fall in hours 23, 0, and 1, around the rollover. Hours 8 and 9 add 33%. Whether this is useful depends on the EA. An EA that wants to avoid the rollover gets that result. An EA that wants to catch a spread that is unusual for its hour needs one counter per hour. The hourly CSV of the script has the percentiles per hour for that decision.
Log buckets for continuous values
The time between ticks is not a small whole number. On these data it runs from 0 ms to more than 172 million ms over a weekend. A counter per millisecond is possible but wasteful. CLogQuantile uses the bucket rule of DDSketch instead. With a relative accuracy alpha, the ratio of the bucket bounds is gamma=(1+alpha)/(1-alpha). A positive value x falls into bucket i=ceil(log(x)/log(gamma)), which holds the values from gamma^(i-1) to gamma^i. Zero gets its own counter.
//+------------------------------------------------------------------+ //| CLogQuantile::Bucket | //| Index of the bucket of a positive value, clamped to the grid. | //+------------------------------------------------------------------+ int CLogQuantile::Bucket(const double x) const { double v=MathMin(MathMax(x,m_min),m_max); int b=(int)MathCeil(MathLog(v)/m_log_gamma)-m_offset; return((int)MathMin(MathMax(b,0),ArraySize(m_buckets)-1)); }
Each bucket stands for one value, 2 gamma^i/(gamma+1). For any x in the bucket, this value differs from x by at most alpha times x.
//+------------------------------------------------------------------+ //| CLogQuantile::Representative | //| Value that stands for bucket b: 2*gamma^i/(gamma+1). It differs | //| from any value of the bucket by at most alpha, relatively. | //+------------------------------------------------------------------+ double CLogQuantile::Representative(const int b) const { return(2.0*MathPow(m_gamma,b+m_offset)/(m_gamma+1.0)); }
Value() uses the type 7 ranks, as MathQuantile() does, and interpolates between the representatives of the two ranks. If each representative is within alpha of its value, the interpolated result is also within alpha of the exact type 7 value. This argument holds for non-negative values. The class therefore refuses negative values.
//+------------------------------------------------------------------+ //| CLogQuantile::Value | //| Type 7 quantile, interpolated between the representatives of the | //| two ranks, like MathQuantile() does between two values. | //+------------------------------------------------------------------+ bool CLogQuantile::Value(const double p,double &value) const { if(m_count==0 || !MathIsValidNumber(p) || p<0.0 || p>1.0) return(false); double ind=(m_count-1)*p; long lo=(long)MathFloor(ind); long hi=(long)MathCeil(ind); double q=ValueAtRank(lo); if(ind>lo) { double gamma=(ind-lo); q=(1.0-gamma)*q+gamma*ValueAtRank(hi); } value=q; return(true); }
The guarantee holds between the minimum and the maximum that Init() receives. A value below the minimum is counted in the first bucket and a value above the maximum in the last one. BelowMin() and AboveMax() count these values. For the tick gaps, I used alpha=0.005, a minimum of 1 ms, and a maximum of 10^9 ms. The grid then has 2,074 buckets, which take about 16.6 KB. No gap was outside the range.
Fig. 5 follows the 99th percentile of the EURUSD gaps at the end of each day, in time order.
The 99th percentile of the time between EURUSD ticks at the end of each day
P-Square, log buckets with alpha 0.005, and the exact value

Fig. 5. The log-bucket line lies on the exact line. The exact value falls from 5,740.56 ms after the first day to 4,276.48 ms at the end. P-Square starts at 13,499.91 ms and ends at 13,757.45 ms
On the real ticks, every percentile of CLogQuantile in the table of real tick results was within 0.5% of the exact value. Fig. 6 shows the relative differences. The largest one was -0.47%, for the 99.9th percentile of the XAUUSD gaps.
Log buckets against the exact percentile of the tick gaps
Relative difference at the end of the period, alpha 0.005

Fig. 6. All eight differences lie between -0.47% and +0.42%, inside the dashed lines at plus and minus 0.5%
The online version of the long-gap flag compares each gap with the 99.9th percentile of the gaps before it:
| Symbol | Gaps decided | Flagged, log buckets | Flagged, P-Square |
|---|---|---|---|
| EURUSD | 5,442,253 | 3,781 (0.069%) | 197 (0.0036%) |
| XAUUSD | 10,666,468 | 9,107 (0.085%) | 335 (0.0031%) |
The log-bucket flag marked 0.069% of EURUSD gaps and 0.085% of XAUUSD gaps. Both are below the nominal 0.1%. Each threshold comes from the gaps before the tick, not from the whole month, so the share does not have to match 0.1%. The P-Square flag marked far fewer gaps.
Tests
TestPSquare prints one PASS or FAIL line per check. The checks cover:
- the 15 rows of Table I, the final estimate, and the cell rule of Box 1 for a value equal to a marker height,
- refused probabilities, refused values, and the exact answer for the first five values,
- the order of the markers after every value of seven streams of 100,000 values, with four probabilities per stream,
- Save() and Load(), including a loaded estimator that continues bit for bit like one that never stopped, and three kinds of broken files,
- PsqTypeSevenSorted(), CCountQuantile, and CLogQuantile against MathQuantile(),
- NaN from PsqTypeSevenSorted() for an invalid count or probability,
- the same answer of CLogQuantile for random, ascending, and descending order,
- refused, clamped, and removed values of both counter classes,
- four regression values of fixed seeds.
The seven streams are ascending, descending, constant, alternating extremes, four tied values, random normal, and a sawtooth.
The run on terminal build 6230 ended with these lines:
CLogQuantile: worst relative error 0.005000 with alpha 0.005 PASS CLogQuantile gives identical answers for random, ascending and descending order PASS CLogQuantile returns exactly 0 for zeros PASS CLogQuantile counts values below min and above max PASS CLogQuantile refuses negative, NaN and infinite values PASS CLogQuantile Remove() undoes Add() and refuses an empty bucket PASS CLogQuantile Save() and Load() round trip PASS CLogQuantile Load() refuses another alpha PASS seed 1 regression, uniform p=0.50, rank error under 0.2 percentage points PASS seed 1 regression, uniform p=0.95, rank error under 0.2 percentage points PASS seed 1 regression, normal p=0.50, rank error under 0.2 percentage points PASS seed 1 regression, normal p=0.95, rank error under 0.2 percentage points TestPSquare: 66 checks, 66 passed, 0 failed
In my first full run of these checks, the round-trip check of CLogQuantile reported FAIL. The class was not the cause. The test wrote the file name with a single backslash before "test_log.bin", and MQL5 reads a backslash followed by "t" in a string as a tab character. FileOpen() failed, so Save() had no file to write. The next check expected Load() to refuse a file saved with another alpha. That check passed for the wrong reason: Load() returned false because no file was open. I fixed the name. Every check that expects Load() to refuse a file now also requires that the file exists and was opened.
The unit checks show that my code does what I intended. They do not show that the intention is right. For that I planted six defects, one at a time, in a copy of the include files inside the terminal. The attached script mutate.py does this, compiles TestPSquare, runs it, and restores the files. Each mutant run expected at least one check to report FAIL:
| Mutant | File | Planted defect | Checks that reported FAIL | Caught |
|---|---|---|---|---|
| A | PSquare.mqh | Parabolic height accepted when it equals a neighbor | 0 | no |
| B | PSquare.mqh | Marker allowed to move onto the position of its neighbor | 25 | yes |
| C | PSquare.mqh | Linear formula moves away from the neighbor | 5 | yes |
| D | PSquare.mqh | A value equal to a marker height falls into the lower cell | 1 | yes |
| E | CountQuantile.mqh | Counter returns the value one rank too low | 1 | yes |
| F | LogQuantile.mqh | Bucket stands for its upper bound instead of its center | 1 | yes |
Mutant A survived. It accepts a parabolic height that equals a neighbor height exactly. Only in that case does its result differ from the original code, and none of the test streams produced such a height. My first round of mutation runs also let mutant D pass. Mutant D puts a value equal to a marker height into the cell below that marker, while Box 1 of the paper puts it into the cell above. No check pinned that rule. I added one: after the values 1, 2, 3, 4, 5, and 3, the positions must be 1, 2, 3, 5, and 6. The table shows the second round, with the new check.
Cost
BenchPSquare times each operation over 10 million values, five times, and prints the median. The program output in this article prints counts without thousands separators, as the code formats them.
BenchPSquare: 10000000 values, 5 passes, median of the passes CPSquare::Add 35.9 ns per value CCountQuantile::Add 12.7 ns per value CCountQuantile::Value 36.8 ns per call, p=0.95, discrete test values CLogQuantile::Add 45.3 ns per value CLogQuantile::Value 1255.6 ns per call, p=0.999, lognormal test values times 100 copy and ArraySort, 1,000,000 values 322.7 ms copy and ArraySort, 10000000 values 3644.5 ms MathQuantile, 1,000,000 values 218.8 ms stored values for an exact answer: 8000000 bytes per million values
An Add() of CPSquare takes about 35.9 ns, and an Add() of CCountQuantile takes 12.7 ns. A Value() of CCountQuantile for spread-like whole numbers takes 36.8 ns. An Add() of CLogQuantile takes 45.3 ns. A Value() of CLogQuantile at p=0.999 takes 1,256 ns, because the loop walks the buckets from the bottom. An exact answer for 10 million values needs 80 MB and a sort of about 3,644 ms. The times come from one laptop CPU (AMD Ryzen 5 PRO 5650U) and give the order of size only.
Using the classes in an EA
QuantileGateDemo shows the use in an EA. The EA opens no trades. On every tick it computes the spread in points and the time since the previous tick. The spread gate uses CCountQuantile by default. The long-gap flag uses CLogQuantile. A CPSquare estimator runs next to each of the two classes for the report. An entry rule would call SpreadAllowsEntry():
//+------------------------------------------------------------------+ //| SpreadThreshold | //| Threshold of one method. False while the gate is warming up. | //+------------------------------------------------------------------+ bool SpreadThreshold(const ENUM_GATE_METHOD method,double &threshold) { if(g_counts.Count()<InpWarmup) return(false); double v=0.0; switch(method) { case GATE_EXACT_COUNTS: if(!g_counts.Value(InpGateP,v)) return(false); break; case GATE_PSQUARE: if(!g_gate.Value(v)) return(false); break; case GATE_PSQUARE_ROUNDED: if(!g_gate.Value(v)) return(false); v=MathRound(v); break; } threshold=v; return(true); }
//+------------------------------------------------------------------+ //| SpreadAllowsEntry | //| The call an entry rule makes. False while warming up and when | //| the spread is above the threshold of the chosen method. | //+------------------------------------------------------------------+ bool SpreadAllowsEntry(const double spread_points) { double threshold=0.0; if(!SpreadThreshold(InpGateMethod,threshold)) return(false); return(spread_points<=threshold); }
SpreadAllowsEntry() returns false during the warm-up. An EA that wants to trade during the warm-up must decide that on purpose.
With a file name in InpStateFile, the EA saves all estimators in OnDeinit() and loads them in OnInit(). LoadState() loads into new objects first and copies them only when every part was read, so a broken file changes nothing. The file holds the symbol, and a file of another symbol is refused. Saving does not repair an estimate. A CPSquare state with an early error, such as the rollover error described above, keeps that error after a restart. For this reason the gate uses CCountQuantile, and the EA reports CPSquare only for comparison.
I ran the EA in the Strategy Tester on EURUSD with every tick based on real ticks. The tester period was set from 2026.09.01 to 2026.09.30. The tester stops at 00:00 of the end date, so the run covered the ticks from 2026.09.01 to 2026.09.29. The script runs on real ticks also include 2026.09.30, so the tester did not test the same ticks as the script. A second test split the tester period into two runs. The first run saved the state, and the second run loaded it.
| Run | Spreads held at the end | Ticks decided | Blocked, exact | Gaps flagged, log buckets | Spread p=0.95, P-Square | Gap p=0.999, log buckets, ms |
|---|---|---|---|---|---|---|
| Whole period, ticks of 2026.09.01 to 2026.09.29 | 5,124,132 | 5,123,132 | 115,333 | 3,615 | 22.188702403524502 | 13427.588455 |
| First half, ticks of 2026.09.01 to 2026.09.14, state saved | 2,295,013 | 2,294,013 | 50,926 | 1,665 | 22.283256758395808 | 14839.792627 |
| Second half, ticks of 2026.09.15 to 2026.09.29, state loaded | 5,124,131 | 2,829,118 | 64,407 | 1,950 | 22.188702479278028 | 13427.588455 |
The tester prints the end of a period as 00:00 of the last date, so that date itself is not tested. The second half therefore starts on the date where the first half ends. My first try started it one day later and left out one day of ticks.
The blocked ticks and the flagged gaps of both halves add up exactly to the whole run. The blocked ticks are 50,926 and 64,407, together 115,333. The flagged gaps are 1,665 and 1,950, together 3,615. The log-bucket percentile at the end is the same. The tick counts do not add up exactly. Both halves together received 5,124,131 ticks and decided on 5,123,131. Both numbers are one fewer than in the whole run. The P-Square estimate differs in the eighth significant digit, which fits one missing tick. I did not investigate which tick the second half did not receive.
The whole tester run received 5,124,132 ticks. For the same days, 2026.09.01 to 2026.09.29, CopyTicksRange() in the script returned 5,124,138, six more. The P-Square estimate of the script after the last tested day is 22.188702403524502, the same number that the tester run printed. I did not find which six ticks the tester did not pass to OnTick().
The first state file test also found a trap of the tester. The whole run had an empty InpStateFile in the ini file. The tester did not pass the empty value and kept the file name of the previous run, so the next run loaded a state it should not have seen. The batch script now gives the whole run a file name of its own and deletes the restart file before the first half.
Python consistency check
The script psquare_check.py implements P-Square, the type 7 rule, the counters, and the log buckets a second time in Python. The script reads the raw values that the MQL5 scripts write, recomputes the estimates and the gate counts, and compares them with the CSV files. The rules are the same in both programs. The check therefore finds a slip in one of the two programs, not an error in the rules.
accuracy.csv seed 1: 360 comparisons, 0 P-Square estimates differ (largest difference 0), 0 exact values differ
EURUSD: 5443254 spreads, 5443253 gaps gates python [5442254, 300, 300, 122807, 5442253, 197, 3781] gates mql5 [5442254, 300, 300, 122807, 5442253, 197, 3781] gate counts equal spread p=0.500 exact 0 P-Square 0.500906 shuffled 2.90428e-06 counters 0 ok spread p=0.900 exact 1 P-Square 16.8468 shuffled 1 counters 1 ok spread p=0.950 exact 1 P-Square 22.1816 shuffled 1 counters 1 ok spread p=0.990 exact 2 P-Square 11.9993 shuffled 2 counters 2 ok gap p=0.500 exact 83 P-Square 98.1148 shuffled 84.4534 log 82.6838 ok gap p=0.900 exact 801 P-Square 4346.63 shuffled 821.819 log 800.345 ok gap p=0.990 exact 4276.48 P-Square 13757.5 shuffled 4438.79 log 4294.36 ok gap p=0.999 exact 13284.5 P-Square 43878.1 shuffled 13225.5 log 13294 ok final quantiles: 0 mismatches
The P-Square estimates and the exact values agreed bit for bit. The log-bucket values agreed within 10^-12 relatively. The gate counts were equal. The same check on the XAUUSD values printed:
XAUUSD: 10667469 spreads, 10667468 gaps gates python [10666469, 38, 38, 448314, 10666468, 335, 9107] gates mql5 [10666469, 38, 38, 448314, 10666468, 335, 9107] gate counts equal spread p=0.500 exact 33 P-Square 35.5669 shuffled 33 counters 33 ok spread p=0.900 exact 47 P-Square 4749.2 shuffled 47.935 counters 47 ok spread p=0.950 exact 52 P-Square 5645.75 shuffled 52.899 counters 52 ok spread p=0.990 exact 65 P-Square 5892.1 shuffled 64.9958 counters 65 ok gap p=0.500 exact 55 P-Square 94.2165 shuffled 55.0014 log 54.873 ok gap p=0.900 exact 354 P-Square 1510.8 shuffled 369.003 log 352.495 ok gap p=0.990 exact 1252 P-Square 5947.83 shuffled 1264.12 log 1255.2 ok gap p=0.999 exact 3604 P-Square 11288.2 shuffled 3637.89 log 3586.94 ok final quantiles: 0 mismatches
Which class to use
| Data | Example | Class | Reason |
|---|---|---|---|
| Whole numbers in a known range | Spread rounded to whole points | CCountQuantile | Exact for the rounded values, order does not matter |
| Non-negative values over a wide range | Time between ticks (tested here), execution time (not tested) | CLogQuantile | Relative error within alpha between the minimum and the maximum, order does not matter |
| Values in a random order, memory very tight | Independent samples from a simulation | CPSquare | Five markers, accurate in random order in my tests |
| Values that arrive in time order with clusters or trends | EURUSD and XAUUSD ticks in these tests | CPSquare only after a check on your own ticks | On the tested ticks, high percentiles stayed far from the exact values for the whole month |
Limitations
All real-data results come from one server, one terminal build, two symbols, and one month of ticks. Other symbols, servers, and periods may give other numbers, and the P-Square error depends on the first values that it sees. The table in the previous section summarizes these tests. It is not a general rule for all tick data.
The generated data cover six distributions and three orders. The regime order is one kind of change, a larger scale in the second half. A slow drift, a daily seasonality, regimes that alternate, a return to the first regime, and a change of shape were not tested. The sorted order ran with one seed. In a sorted stream, the seed changes the values but not their order. Other seeds may still give other errors.
CPSquare has no window and cannot discard old values. A trend in the values or a wrong early height stays in the estimate. I have not tested restarting P-Square on a schedule or running two estimators in turn.
CCountQuantile needs whole numbers in a known range. A spread in points is a whole number only after rounding, and the script rounds (ask-bid)/point with MathRound(). A threshold on whole numbers cannot block exactly 5% of ticks when many ticks share one value.
CLogQuantile guarantees its error only between its minimum and maximum, and only for non-negative values. Its memory grows with the logarithm of the range. The class has no bucket collapsing, so a very wide range with a very small alpha needs many buckets.
The gates in the scripts decide from all ticks before each tick. They do not use a window, and they weight every tick equally. An hour with many ticks therefore has more weight than a quiet hour.
The scripts use COPY_TICKS_INFO (ticks with a change of the bid or the ask price). The gaps of Sections 4 and 6 come from that series. With COPY_TICKS_ALL, which also holds trade ticks, the gaps can be shorter, and their distribution can differ. I did not test that.
The tester run received six ticks fewer than CopyTicksRange() returned for the same days, and both halves together received one tick fewer than the whole run. The cause of both differences is open. The demo EA counts are therefore not an exact reproduction of the script data.
On data with many ties, the rank error jumps when an estimate crosses a whole value, as the real tick results show. For such data, read the value error and the rank error together.
The Python script repeats my rules, so it cannot find a wrong rule. The unit checks and the Python check confirm that the code follows the chosen rules. They do not show that these rules are the right ones for a trading decision.
What the checks do not cover
The checks do not cover live trading. In live trading, the ticks an EA receives in OnTick() can differ from the stored history. They do not cover other servers, custom symbols, or symbols where the spread in points exceeds the maximum of the counter. The tester runs use one symbol and one tick model. The mutation runs cover six defects that I chose, and the checks did not catch mutant A. The benchmark ran on one computer. No test shows that a percentile threshold makes an EA trade better. The gate counts only measure which ticks a threshold blocks.
Conclusion
CPSquare reproduces the worked example of the paper and is accurate on generated values in random order. On real EURUSD and XAUUSD ticks in time order, its estimates at p=0.9 and above stayed far from the exact percentiles for the whole month. For the spread, the large spreads of the first ticks set the markers high, and the estimates moved back by tiny steps. The height step of the algorithm shrinks as the number of values grows. That property explains why the early spread error stayed for the whole month. For the time between ticks, the cause of the remaining error is not established. Starting after the rollover reduced the error but did not remove it. Shuffling the same ticks removed most of the error. This result shows that the order matters, not which property of the order causes the error. An EA cannot shuffle its ticks.
For a spread rounded to whole points, CCountQuantile gives the exact percentile of the rounded values with one counter per point. For values over a wide range, such as the time between ticks, CLogQuantile kept all eight tested percentiles within 0.5% of the exact value on these data. Its error bound holds only between the minimum and the maximum that you set. Its answer does not depend on the order of the values, by construction and in the unit check with three orders. Both classes support a moving window through Remove(). If you need a percentile in an EA, test your estimator on your own ticks in time order, and compare it with the exact value before you trust it.
Attached files
| File | Location | Contents |
|---|---|---|
| PSquare.mqh | MQL5/Include/PSquare/ | CPSquare, the P-Square estimator, and PsqTypeSevenSorted() |
| CountQuantile.mqh | MQL5/Include/PSquare/ | CCountQuantile, exact percentiles of whole numbers |
| LogQuantile.mqh | MQL5/Include/PSquare/ | CLogQuantile, percentiles on a logarithmic grid with a relative error bound |
| PsqTestTools.mqh | MQL5/Include/PSquare/ | Generator, distributions, and rank helpers of the scripts |
| TestPSquare.mq5 | MQL5/Scripts/PSquare/ | 66 unit checks |
| AccuracyPSquare.mq5 | MQL5/Scripts/PSquare/ | Accuracy study on generated data |
| TickQuantiles.mq5 | MQL5/Scripts/PSquare/ | Spread and tick-gap percentiles of real ticks, and the gate simulation |
| BenchPSquare.mq5 | MQL5/Scripts/PSquare/ | Time per operation |
| QuantileGateDemo.mq5 | MQL5/Experts/PSquare/ | Demo EA with the spread gate, the long-gap flag, and a state file |
| psquare_check.py | MQL5/Files/PSquare/ | Python consistency check |
| mutate.py | MQL5/Files/PSquare/ | Python script for the mutation runs described in the Tests section |
| MQL5.zip | Attachment | All files above, with the folder structure of the terminal |
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.