Building a Divergence System (Part VI): A Scoring Divergence Engine
Contents
- Introduction
- Designing the class
- The Oscillator, Reused
- Choosing the Pivot Pair
- Measuring a Divergence
- Filters and Rejection Reasons
- Reading the Results
- Driving the Engine From Your Own Loop
- Upgrading the Trailing Utility
- Limitations
- Conclusion
Introduction
The previous part ended on what its trailing header could not do. It could react to an opposing divergence and limit how old that divergence was allowed to be, but it could not tell a large divergence from a small one. Every divergence the engine found counted the same. This was true whether price barely made a new low or broke well below the old one, and whether the oscillator disagreed by a fraction of a point or by a wide margin. This part builds the engine that measures those things. It measures size and nothing else. Whether a larger divergence is more often followed by a reversal is a separate question, and this part does not test it.
The Quality Problem
The first part described the problem in its limitations. In a sideways market, price and the oscillator can form many small pivots that meet the divergence conditions without any reversal, so the indicator prints an arrow on each one. The same article advised that a bullish arrow near the oversold level is stronger than one near zero. The engine has no way to act on that advice. Its output is a divergence type and a bar count, so a large divergence and a small one produce the same result. The engine also compares each new pivot with a single remembered pivot. The Adaptive SuperTrend indicator shows this in its state buffers, where LastPivLowPriceBuffer[] stores the most recent pivot low price. When a shallow pivot forms between two meaningful lows, it replaces the older low in memory, and the comparison that mattered is never made.
The engine is also more complicated to integrate than it needs to be. Using it currently takes eight stages: initialization and lookback, sizing, seeding, the RSI refresh, the per-bar loop, queries, and teardown. Every consumer has to implement that sequence itself.
Solution
DivergenceEnginePro.mqh holds a class, CDivergenceEnginePro, built around the same oscillator. It keeps every oscillator pivot it confirms inside its window, instead of the latest one of each kind, and compares each new pivot with up to PairingDepth earlier ones. It measures each candidate pair three ways: by how far price moved past the older pivot, how far the oscillator disagreed, and how far apart the two pivots are, and combines the three into a score from 0 to 100. The score is a size measured against the chosen settings, not a probability. Filters reject pairs that are too close, too small, or outside a zone. When no pair passes for a new pivot, the nearest rejected pair is kept with the reason it was rejected.
The trailing header from the previous part is upgraded to run on the new engine, and its adaptation now scales with the score.
Scope of This Article
In the sections that follow, we will:
- Configure the class through one struct and drive it in four steps.
- Store every pivot found in the window and choose which earlier pivot a new one is paired with.
- Measure a pair in ATR, oscillator points, and bars, and combine the three into a score.
- Filter pairs in a fixed order, and name the first filter a pair fails.
- Drive the engine one bar at a time from a loop that has to reset it mid-pass.
- Move the trailing header onto the new engine and scale its adaptation by the score.
What the Previous Part Already Settles
The oscillator is unchanged. MPO4 and RSI, the smoothing, and the reason the calculation loop runs from the oldest bar towards the newest were all covered when the engine was extracted into its own header, and the new class calls the same functions to produce the same values. Pivots are still found on the smoothed oscillator with the same strict test, and a pivot is still confirmed PivotLength bars after it forms. State is still carried forward in per-bar buffers. Within a pass, a bar's result depends only on that bar and earlier bars; later bars do not revise it. It can still be reset when a consumer's own trend flips.
The window is recomputed on every pass, which puts two limits on that: results near the old end of the window can change as the window moves, and bar 0 is still forming. Limitations covers both. The trailing header still decides what a divergence means for the stop. A divergence that opposes the direction the SAR is trailing changes the acceleration step, either reducing it or increasing it as the trader configures, and this part changes only how far the step moves, not that decision.
Designing the Class
The Configuration Struct
Every setting is a field of one struct, with a default for each:
//+------------------------------------------------------------------+ //| Every setting in one struct | //+------------------------------------------------------------------+ struct DivergenceProConfig { //--- Market context string Symbol; // Empty = chart symbol ENUM_TIMEFRAMES Timeframe; int Lookback; // Bars copied per pass //--- Oscillator, handed to DivergenceEngine.mqh ENUM_DIV_SOURCE Source; int MPOLength; int MPOSmooth; int RSIPeriod; int PivotLength; // Bars either side of an oscillator pivot //--- Pairing int PairingDepth; // Earlier pivots a new pivot is compared with (1 = the previous one only) int MinSeparation; // Bars int MaxSeparation; // Bars //--- Filters int ATRPeriod; double MinPriceExtATR; // Price must pass the older pivot by at least this many ATR double MinOscDelta; // Oscillator must disagree by at least this many points bool UseZone; double BullZoneLevel; // Bullish: older pivot's oscillator at or below this double BearZoneLevel; // Bearish: older pivot's oscillator at or above this double MinScore; // 0..100 //--- Score double PriceExtFullATR; // Extension that earns the full price score double OscDeltaFull; // Disagreement that earns the full oscillator score int SepFullBars; // Separation that earns the full spacing score double WeightPrice; double WeightOsc; double WeightSep; //--- Diagnostics bool LogRecords; // Print every pair when its confirmation bar closes void SetDefaults(void) { Symbol = ""; Timeframe = PERIOD_CURRENT; Lookback = 300; Source = DIV_SRC_MPO; MPOLength = 6; MPOSmooth = 7; RSIPeriod = 14; PivotLength = 2; PairingDepth = 3; MinSeparation = 5; MaxSeparation = 60; ATRPeriod = 14; MinPriceExtATR = 0.10; MinOscDelta = 1.0; UseZone = false; BullZoneLevel = -30.0; BearZoneLevel = 30.0; MinScore = 0.0; PriceExtFullATR = 1.0; OscDeltaFull = 10.0; SepFullBars = 20; WeightPrice = 1.0; WeightOsc = 1.0; WeightSep = 1.0; LogRecords = false; } DivergenceProConfig(void) { SetDefaults(); } };
The struct has twenty-five fields in six groups. The market context and oscillator groups hold the settings the previous engine already used. The pairing, filter, and score groups are new, and each field is explained alongside the code that reads it. The constructor calls SetDefaults(), so a struct declared in an EA starts from the defaults, and the EA changes only what it needs.
The defaults are a template to start from, not recommended settings. Each is a round value in its own unit, and none was tuned or measured in any market:
- PairingDepth 3: a new pivot is compared with at most three earlier pivots of its kind.
- MinSeparation 5 and MaxSeparation 60: a pair is accepted only when its pivots are 5 to 60 bars apart, which on M15 is 75 minutes to 15 hours of trading.
- MinPriceExtATR 0.10 and MinOscDelta 1.0: low floors that reject a new extreme smaller than a tenth of an ATR and a disagreement smaller than one oscillator point.
- PriceExtFullATR 1.0, OscDeltaFull 10, and SepFullBars 20: the full price sub-score at one ATR past the older pivot, the full oscillator sub-score at a tenth of MPO4's 100-point span, and the full spacing sub-score at 20 bars.
- Equal weights: no measurement counts for more than another, and none was tested against what followed a divergence.
The Score shows how far a score moves when the references and weights change. Init() checks the settings before allocating anything and prints the reason for each refusal with a [DivPro] prefix.
The periods and PivotLength must be above zero; PairingDepth must be at least 1; MinSeparation cannot be negative, and MaxSeparation must be greater than it; the thresholds must be non-negative; MinScore must be between 0 and 100; the three score references must be above zero; and no weight can be negative, with at least one above zero. The zone levels are checked only when UseZone is on. A Lookback too short to hold a pair at MaxSeparation is not refused: Init() raises it and prints the new value.
The Lifecycle
The eight integration stages become four steps:
| Host event | The previous engine's stages | This engine |
|---|---|---|
| OnInit() | InitializeDivergenceEngine(), GetRequiredLookback(), ResizeDivergenceBuffers() | Init(cfg) |
| Each new bar | ResizeDivergenceBuffers() if the bar count changes, InitDivergenceBoundaries(), UpdateDivergenceRSI(), then a loop calling CalculateOscillator and DetectDivergence() | Refresh() |
| Wherever a value is needed | GetLastDivergenceType(), GetBarsSinceDivergence(), GetOscillatorValue() | Type(), Age(), Score(), Latest(), Oscillator() |
| OnDeinit() | ReleaseDivergenceEngine() | Deinit() |
Three of the four steps are single calls, and the third is a small set of read-only queries. The class maintains its own copy of the price window. Refresh() copies the most recent Lookback bars for the configured symbol and timeframe, resizes buffers if the bar count changed, computes the oscillator and divergence state from Limit() down to 0, and then marks the engine ready. If the terminal does not yet hold enough history, it returns false and the next call tries again. The destructor calls Deinit(), so an engine declared as a global releases its RSI handle and its buffers when the program ends.
Refresh() is enough for a consumer that only reads the results. A consumer that has to act inside the per-bar loop, such as the trailing header resetting divergence state when the SAR flips, drives the engine with three calls instead, covered in Driving the Engine From Your Own Loop.
Using the Engine in an EA of Your Own
- Put DivergenceEngine.mqh and DivergenceEnginePro.mqh in MQL5/Include/ and include the second one.
- Declare a CDivergenceEnginePro object at file scope.
- In OnInit(), declare a DivergenceProConfig, change the fields you need, and pass it to Init(). When Init() returns false, return INIT_FAILED from OnInit(); the reason is already in the Experts tab.
- When a new bar opens, call Refresh(). A false return means the window could not be built yet, and the EA should skip any decision that depends on it for that bar.
- Read Type(1), Age(1), and Score(1) wherever the EA decides what a divergence should change.
Deinit() runs from the destructor, so the EA does not need to call it. Calling it from OnDeinit() is also harmless. The trailing header later in this article is a complete example of a consumer, and the one case where those steps are not enough is covered in Driving the Engine From Your Own Loop.
The Oscillator, Reused
The class includes the original engine:
#include <DivergenceEngine.mqh> It holds a DivergenceEngine struct as a private member and uses it for the oscillator only. Each pass calls UpdateDivergenceRSI(), InitDivergenceBoundaries(), and then CalculateOscillator() bar by bar, and pivots are read with GetOscillatorValue(), so the oscillator values are the ones the previous engine produced. None of its divergence functions are called. The class finds pivots, pairs them, and keeps state itself.
DivergenceEngine.mqh, therefore, has to stay in MQL5/Include/ beside the new header. The new class calls ResizeDivergenceBuffers() for its result and stops the pass when it returns false, so it needs the version of that file that returns bool.
The oscillator's scale matters from here on, because several settings are measured in it. MPO4 is bounded at ±50, and the bound follows from CalculateOscillator() as it stands. Each of the last MPOLength candles contributes its direction, which is +1, −1, or 0 for a candle that closes where it opened, times a weight, which is its body divided by the average body of those same candles. The weights therefore add up to MPOLength, and the sum of the contributions lies between −MPOLength and +MPOLength.
The raw value is that sum divided by twice MPOLength and multiplied by 100, so it cannot pass 50 in either direction. When every body in the lookback is zero, every weight is zero and the raw value is 0. The smoothed value is an exponential average of the raw values that starts from 0, so it stays inside the same bounds. This is narrower than the range Part 1 described, which was roughly −100 to +100 where it walked through the code and about ±30 where it explained how to read the oscillator. RSI runs from 0 to 100. Every oscillator setting in this part uses the source's own points.
Pivot Storage
//+------------------------------------------------------------------+ //| One oscillator pivot | //+------------------------------------------------------------------+ struct DivergencePivot { bool isHigh; // true = pivot high, false = pivot low int bar; // Shift in the current pass datetime time; double price; // Bar high for a pivot high, bar low for a pivot low double osc; // Smoothed oscillator at the pivot int confirmBar; // Shift where the pivot became known };
Each pass stores every oscillator pivot it finds in an array, highs and lows together, oldest first. A pivot records the bar it formed on, the price at that bar (the high for a pivot high, the low for a pivot low), the smoothed oscillator value, and the bar on which it was confirmed. The bar numbers are shifts within the current pass, and time identifies the pivot across passes.
bar and confirmBar are always PivotLength bars apart. A divergence is dated from the bar that confirmed its newer pivot, never from the bar the pivot formed on, so nothing is reported on a bar where it could not yet have been known. On closed bars, this is the same property that keeps the arrows in the earlier indicators from repainting. A pivot confirmed on bar 0 is confirmed on a bar that is still forming, and it can change until that bar closes. Keeping all of them lets a new pivot be compared with more than the latest earlier one. With a single remembered low, a shallow low between two deep ones takes the older low's place, and the two deep lows are never compared. With every pivot stored, the engine can look past the shallow one. A pivot at bar p is tested only once PivotLength bars on each side of it have been processed in the current pass. Near the oldest end of the window, where the bars before a candidate were not processed, no pivot is recorded, so the engine never compares against oscillator values it has not calculated.Choosing the Pivot Pair
When a new pivot is confirmed, the engine looks back through the earlier pivots of the same kind, newest first, for one to pair it with:
//+------------------------------------------------------------------+ //| Compare a new pivot with earlier pivots of the same kind, newest | //| first, and keep the first pair that passes every filter | //+------------------------------------------------------------------+ void CDivergenceEnginePro::PairNewPivot(const int newIdx, const int i) { if(newIdx < 0) return; DivergencePivot newer = m_pivots[newIdx]; bool isHigh = newer.isHigh; double oscGuard = isHigh ? -DBL_MAX : DBL_MAX; int examined = 0; bool haveReject = false; DivergenceInfo rejected; ZeroMemory(rejected); for(int k = newIdx - 1; k >= m_barrier && examined < m_cfg.PairingDepth; k--) { if(m_pivots[k].isHigh != isHigh) continue; DivergencePivot older = m_pivots[k]; if(older.bar - newer.bar > m_cfg.MaxSeparation) break; examined++; //--- Price has to make a new extreme against the older pivot bool newExtreme = isHigh ? (newer.price > older.price) : (newer.price < older.price); if(!newExtreme) break; //--- The older pivot has to be the most extreme oscillator reading so far bool cleanStart = isHigh ? (older.osc > oscGuard) : (older.osc < oscGuard); oscGuard = isHigh ? MathMax(oscGuard, older.osc) : MathMin(oscGuard, older.osc); if(!cleanStart) continue; //--- The oscillator has to disagree with price bool disagrees = isHigh ? (newer.osc < older.osc) : (newer.osc > older.osc); if(!disagrees) continue; DivergenceInfo d; Measure(older, newer, i, d); if(d.status == DIV_ACCEPTED) { int idx = AddInfo(d); if(idx >= 0) m_lastSig[i] = idx; return; } if(!haveReject) { rejected = d; haveReject = true; } } //--- Nothing accepted: keep the nearest rejected pair so its reason can be read if(haveReject) AddInfo(rejected); }
The search takes the pivots of the same kind in order, newest first, and applies these rules to each. The description uses pivot lows and a bullish divergence; pivot highs are the mirror image.
- Distance. A candidate farther back than MaxSeparation bars ends the search, since every pivot before it is even farther away.
- Depth. At most PairingDepth candidates within that distance are examined. A candidate counts as soon as it is within range, whether or not it goes on to be measured, so a new pivot can be measured against fewer pairs than PairingDepth, or against none.
- A lower low in price. The new pivot's price must be below the candidate's. When it is not, the search ends: the candidate is at or below the new pivot, so any pair with an older pivot would have that lower low between its two ends. Stopping there is a rule this engine imposes to keep its pairs clean. It is not a property of regular divergence, and an engine without the rule would go on to test the older pivots.
- The deepest oscillator reading so far. The candidate's oscillator value must be lower than every candidate examined before it. If a newer candidate went deeper, a line from this candidate to the new pivot would cut through that deeper reading, so this candidate is skipped, and the search continues.
- Disagreement. The oscillator at the new pivot must be higher than at the candidate. If it is not, there is no divergence with this candidate, and the search continues.
- Measurement and filters. A candidate that reaches this point is measured and filtered, as described in the next two sections. The first accepted pair is stored as the bar's divergence, and the search stops. A rejected pair is remembered if it is the first one rejected, and the search continues.
If no candidate is accepted, the nearest rejected pair is stored with its reason, so a trader can see why a pivot produced nothing. A pivot for which no candidate reached step 6 stores nothing.

In the figure, C is the new pivot. B is the nearest earlier low and forms a divergence with C, but the two are closer together than MinSeparation, so the pair is rejected as too close and the search moves on to A. Price at C is below A, the oscillator at A is deeper than at B, and the oscillator at C is above A, so the A to C pair is measured, passes the filters, and is stored. With a single remembered pivot, C would only ever have been compared with B.
The search keeps the nearest pair that passes, not the pair with the highest score. That is a design choice, not a finding. The nearest passing pair is the one whose older pivot is closest to the current bar, and the engine prefers it for that reason alone. Nothing here shows that it is the better pair to trade on, and a pair further back that would have scored higher is never measured once a nearer one passes. With PairingDepth at 1, every threshold at zero, and the zone off, the only candidate is the previous pivot of the same kind, and a pair is accepted whenever price makes a new extreme and the oscillator disagrees. The results still differ in three places. The previous engine had no MaxSeparation, so it could pair pivots further apart. It tested for pivots at the old end of the window, which this class leaves out. And after a reset it could still pair a pivot that had formed before the reset bar with the one remembered before it, which this class never does.Measuring a Divergence
Each candidate pair is measured three ways, and each measurement uses a unit that does not depend on the symbol's price scale.
Price Extension in ATR
The first measurement is how far price went past the older pivot. A 20-point new low is a decisive break on one symbol and noise on another, so the distance is divided by the ATR at the newer pivot's bar. A price extension of 0.4 means the new low is four tenths of an ATR below the old one. ATR is the unit here because it expresses a move in the symbol's own recent range. Nothing in this part shows that it is the best unit for the job.
The class computes ATR itself from the prices in its window. Computing it inside the class is a practical choice: it avoids a second indicator handle and the readiness checks that come with one.
//+------------------------------------------------------------------+ //| True range of one bar, using the previous close | //+------------------------------------------------------------------+ double CDivergenceEnginePro::TrueRange(const int k) { return MathMax(m_high[k], m_close[k + 1]) - MathMin(m_low[k], m_close[k + 1]); } //+------------------------------------------------------------------+ //| Simple average of true range, as MetaTrader's own ATR computes it| //+------------------------------------------------------------------+ void CDivergenceEnginePro::ComputeATR(void) { int period = m_cfg.ATRPeriod; ArrayInitialize(m_atr, 0.0); //--- The oldest bar with a full period of true ranges behind it int oldest = m_bars - 1 - period; if(oldest < 0) return; double sum = 0.0; for(int k = oldest; k < oldest + period; k++) sum += TrueRange(k); m_atr[oldest] = sum / period; for(int b = oldest - 1; b >= 0; b--) { sum += TrueRange(b) - TrueRange(b + period); m_atr[b] = sum / period; } }
TrueRange() is the larger of the bar's high and the previous bar's close, minus the smaller of its low and that close. ComputeATR() starts at the oldest bar of the window with ATRPeriod true ranges behind it and gives it their simple average. Moving towards bar 0, it adds each newer true range to the sum and drops the one that has left the period. Bars older than that first value keep an ATR of 0. The pass starts at Limit(), which is newer than all of them, so every pivot the engine measures has an ATR taken over a full period.
The ATR example indicator that ships with MetaTrader 5, MQL5\Indicators\Examples\ATR.mq5, computes the same quantity. In the copy installed with the terminal used here (build 6231), its true range has the same formula (lines 73 and 91), its first value is the simple average of the first period's true ranges (lines 75 to 83), and each later value moves that average on by one bar, adding the newest true range and dropping the oldest (line 92). Both are therefore simple averages and not Wilder's smoothed one. A simple average depends only on the bars it covers, so at any bar the engine measures, the class's ATR and the example's ATR with the same period agree apart from floating-point rounding: the example carries the average forward, and the class carries the sum. This follows from reading the two sources. The two were not compared on a chart.
Oscillator Disagreements in Points
The second is how far the oscillator disagreed with price: the absolute difference between the two pivots' oscillator values, in the source's own points. MPO4, bounded at ±50, and RSI, from 0 to 100, both have a span of 100 points, but they do not use that span in the same way. They are built differently and centered differently, so a MinOscDelta or an OscDeltaFull chosen on one source should be chosen again on the other.
Spacing in Bars
The third is the number of bars between the two pivots. The score treats pivots very close together as the small swings of a ranging market, and it treats distance beyond SepFullBars as adding nothing more. Both are assumptions built into the score, not measurements. The spacing score, therefore, rises in a straight line from zero at MinSeparation to full at SepFullBars and stays full after that.The Score
Each measurement is divided by the value that earns its full score and capped at 1, which gives three sub-scores between 0 and 1. Those are combined as a weighted average and multiplied by 100. Init() refuses a negative weight, and refuses weights that are all zero, so the result always lies between 0 and 100:
| Measurement | Unit | Earns the full sub-score at | Default |
|---|---|---|---|
| Price extension | ATR at the newer pivot | PriceExtFullATR | 1.0 ATR |
| Oscillator disagreement | Oscillator point | OscDeltaFull | 10 points |
| Spacing | bars | SepFullBars, rising from zero at MinSeparation | 20 bars, from 5 |
| Weight | - | WeightPrice, WeightOsc, WeightSep | 1.0 each |
The whole calculation is one function:
//+------------------------------------------------------------------+ //| Measure a pair, score it, and classify it | //+------------------------------------------------------------------+ void CDivergenceEnginePro::Measure(const DivergencePivot &older, const DivergencePivot &newer, const int i, DivergenceInfo &d) { ZeroMemory(d); d.type = newer.isHigh ? -1 : 1; d.time1 = older.time; d.time2 = newer.time; d.bar1 = older.bar; d.bar2 = newer.bar; d.price1 = older.price; d.price2 = newer.price; d.osc1 = older.osc; d.osc2 = newer.osc; d.confirmTime = m_time[i]; d.confirmBar = i; d.separation = older.bar - newer.bar; //--- The three measurements double atr = m_atr[newer.bar]; d.priceExtATR = (atr > 0.0) ? MathAbs(newer.price - older.price) / atr : 0.0; d.oscDelta = MathAbs(newer.osc - older.osc); //--- Each measured against the value that earns its full score d.priceScore = MathMin(d.priceExtATR / m_cfg.PriceExtFullATR, 1.0); d.oscScore = MathMin(d.oscDelta / m_cfg.OscDeltaFull, 1.0); if(m_cfg.SepFullBars > m_cfg.MinSeparation) d.sepScore = MathMax(0.0, MathMin((double)(d.separation - m_cfg.MinSeparation) / (m_cfg.SepFullBars - m_cfg.MinSeparation), 1.0)); else d.sepScore = (d.separation >= m_cfg.MinSeparation) ? 1.0 : 0.0; double weights = m_cfg.WeightPrice + m_cfg.WeightOsc + m_cfg.WeightSep; d.score = 100.0 * (m_cfg.WeightPrice * d.priceScore + m_cfg.WeightOsc * d.oscScore + m_cfg.WeightSep * d.sepScore) / weights; d.status = Classify(older, d); }
The function fills the record for the pair, takes the three measurements, turns each into a sub-score, and combines them. If SepFullBars is set at or below MinSeparation, the spacing score has no range to rise through, so it is either full or zero. The last line sends the record to the filters. A worked example shows the arithmetic. It is an illustration of the calculation, not market data. Take a pair whose new low is 0.4 ATR below the old one, whose oscillator readings differ by 6.0 points, and whose pivots are 15 bars apart, with every setting at its default:
- Price sub-score: 0.4 / 1.0 = 0.40.
- Oscillator sub-score: 6.0 / 10 = 0.60.
- Spacing sub-score: (15 - 5) / (20 - 5) = 0.67.
- Score: 100 * (0.40 + 0.60 + 0.67) / 3 = 56.
A score of 56 means the pair reached a little over half of the level that these references and weights define as a full divergence. It is a measure relative to the settings, not a probability, and it says nothing about how often such a divergence is followed by a reversal. Changing a reference or a weight changes every score. Where this article calls a divergence strong or weak, it means a high or a low score in this sense and nothing more.
How much the score depends on these settings can be seen on two pairs side by side. Pair A is the worked example above. Pair B is another illustration: a new low 1.2 ATR below the old one, an oscillator disagreement of 2.0 points, and pivots 10 bars apart. Both pass the default filters. Each row of the table changes one setting from its default and keeps the others. The step columns give the step the trailing header, shown later, takes from each score when the divergence opposes the SAR's direction and is within DivBarsLimit, with the demo's defaults: SARStep 0.02, AdaptFactor 0.30, the reduce mode, and ScaleByScore on.
| Setting changed | Score A | Step A | Score B | Step B |
|---|---|---|---|---|
| None (the defaults) | 56 | 0.0167 | 51 | 0.0169 |
| PriceExtFullATR 0.5 | 69 | 0.0159 | 51 | 0.0169 |
| PriceExtFullATR 2.0 | 49 | 0.0171 | 38 | 0.0177 |
| OscDeltaFull 5 | 69 | 0.0159 | 58 | 0.0165 |
| OscDeltaFull 20 | 46 | 0.0173 | 48 | 0.0171 |
| SepFullBars 10 | 67 | 0.0160 | 73 | 0.0156 |
| SepFullBars 40 | 43 | 0.0174 | 45 | 0.0173 |
| WeightPrice 2 | 52 | 0.0169 | 63 | 0.0162 |
| WeightSep 0 | 50 | 0.0170 | 60 | 0.0164 |
Halving or doubling one reference, or changing one weight, moves A between 43 and 69, B between 38 and 73, and the step between 0.0156 and 0.0177, against 0.02 when no divergence adapts it. The order of the two pairs changes as well. A scores higher at the defaults and in three of the changed rows, and B scores higher in the other five. With MinScore above zero, the settings also decide which pair passes: at a MinScore of 55, the defaults accept A and reject B, and WeightPrice 2 does the reverse. This is arithmetic on two made-up pairs, not a test on market data, and how many real pairs each setting accepts or rejects on a chart was not measured.
The references and weights determine what the score emphasizes. Lowering PriceExtFullATR lets a smaller break of the old extreme earn the full price sub-score, and raising it demands a larger one. A weight of zero removes that measurement from the score entirely, so WeightSep = 0 scores a pair on price and oscillator alone. The score does not filter anything by itself because MinScore defaults to zero. Setting MinScore above zero turns it into a filter, and the trailing header can use the score without any filter at all, as shown later.
Filters and Rejection Reasons
Every measured pair ends with one of six statuses:
//+------------------------------------------------------------------+ //| Outcome of one evaluated pair | //+------------------------------------------------------------------+ enum ENUM_DIV_STATUS { DIV_ACCEPTED = 0, // Passed every filter DIV_TOO_CLOSE, // Pivots closer than MinSeparation DIV_SMALL_PRICE_MOVE, // New extreme smaller than MinPriceExtATR DIV_SMALL_OSC_MOVE, // Oscillator disagreement smaller than MinOscDelta DIV_OUTSIDE_ZONE, // Older pivot's oscillator outside its zone DIV_LOW_SCORE // Score below MinScore };
The filters run in a fixed order, and the first one that fails names the pair:
//+------------------------------------------------------------------+ //| The filters, in order. The first one that fails names the pair. | //+------------------------------------------------------------------+ ENUM_DIV_STATUS CDivergenceEnginePro::Classify(const DivergencePivot &older, const DivergenceInfo &d) { if(d.separation < m_cfg.MinSeparation) return DIV_TOO_CLOSE; if(d.priceExtATR < m_cfg.MinPriceExtATR) return DIV_SMALL_PRICE_MOVE; if(d.oscDelta < m_cfg.MinOscDelta) return DIV_SMALL_OSC_MOVE; if(m_cfg.UseZone && !InZone(older)) return DIV_OUTSIDE_ZONE; if(d.score < m_cfg.MinScore) return DIV_LOW_SCORE; return DIV_ACCEPTED; } //+------------------------------------------------------------------+ //| The divergence has to start from an extreme oscillator reading | //+------------------------------------------------------------------+ bool CDivergenceEnginePro::InZone(const DivergencePivot &older) { if(older.isHigh) return (older.osc >= m_cfg.BearZoneLevel); return (older.osc <= m_cfg.BullZoneLevel); }
MinSeparation removes pairs whose pivots are too close together. MinPriceExtATR removes pairs where price barely made a new extreme, which is the amplitude filter. MinOscDelta removes pairs where the oscillator barely disagreed. MinScore removes pairs whose combined score is too low, and at its default of zero, it removes nothing. With SepFullBars above MinSeparation, as in the defaults, a pair whose separation equals MinSeparation passes that filter and scores zero on spacing, since the spacing score starts rising at that value.
The zone filter is the engine's version of the advice about arrows near the oversold and overbought levels. When UseZone is enabled, a bullish pair is accepted only when the older pivot's oscillator value is at or below BullZoneLevel and a bearish pair only when it is at or above BearZoneLevel. The test is made at the older pivot, where the divergence starts. The newer pivot's level is not tested, so the zone says where a divergence began and nothing about where it ended. The default values of −30 and +30 are MPO4 levels. With UseZone off, as it is by default, the levels are not read, and selecting RSI needs no other change. With UseZone on and RSI as the source, the trader has to set them, for example, to 30 and 70, because Init() then rejects zone levels outside the source's range, and −30 is outside RSI's. A stored rejected pair keeps its status, so a trader tuning the filters can see which filter removed it. The trailing header's result codes work the same way for a stop that did not move.
Each reason points at a different setting. Many TOO_CLOSE records mean pivots are forming close together, as they do on a ranging chart. MinSeparation decides how close is too close, and a larger PivotLength produces fewer, wider pivots in the first place. SMALL_PRICE_MOVE means the price made a new extreme by less than MinPriceExtATR of an ATR, and SMALL_OSC_MOVE means the oscillator disagreed by less than MinOscDelta points. OUTSIDE_ZONE only appears with the zone on, and a chart full of them means the zone levels are stricter than that market's swings reach. LOW_SCORE only appears when MinScore is above zero. Because the filters run in order, a pair shows only the first reason it failed, and a pair rejected as too close may also have been too small. Counting reasons therefore shows which filter acts first, not how many pairs each filter would remove by itself.Reading the Results
Each evaluated pair is stored as a record:
//+------------------------------------------------------------------+ //| One evaluated pair: accepted, or the reason it was not | //+------------------------------------------------------------------+ struct DivergenceInfo { int type; // 1 = bullish, -1 = bearish ENUM_DIV_STATUS status; datetime time1; // Older pivot datetime time2; // Newer pivot int bar1; int bar2; double price1; double price2; double osc1; double osc2; datetime confirmTime; int confirmBar; int separation; // Bars between the two pivots double priceExtATR; // How far price went past the older pivot, in ATR double oscDelta; // How far the oscillator disagreed, in oscillator points double priceScore; // 0..1 double oscScore; // 0..1 double sepScore; // 0..1 double score; // 0..100 };
The record holds both pivots' times, bars, prices, and oscillator values; the bar on which the pair was confirmed; the three measurements; the three sub-scores; the score and the status. A consumer that draws a divergence or explains why one was rejected has everything it needs in the record and does not have to repeat any of the engine's logic.
Most consumers need less. The per-bar queries report the latest accepted divergence as of a bar, and they read the last closed bar by default:
| Query | Returns |
|---|---|
| Type(shift) | 1 for bullish, −1 for bearish, 0 for none |
| Age(shift) | Bars since that divergence was confirmed, or −1 for none |
| Score(shift) | Its score from 0 to 100, or 0 for none |
| Latest(shift, out) | Its full record, and true when there is one |
| Oscillator(shift), ATR(shift) | The smoothed oscillator and the class's ATR at that bar |
Age() returns −1 when there is no divergence, so a consumer never has to translate a sentinel. InfoCount() and InfoAt() return every record the pass stored, accepted and rejected, oldest first, and PivotCount() and PivotAt() do the same for the pivots. BarTime() to BarClose() return the prices of the window the pass ran on, GetConfig() returns the configuration in effect after any adjustment Init() made, and IsReady() reports whether the last pass completed.
When LogRecords is enabled, each stored pair is printed to the Experts tab when its confirmation bar closes, one line per pair. The line comes from DivergenceInfoToString(), which is also used for chart tooltips.
CS 0 18:39:31.056 DEMO_PSAR_Trailing (EURUSD,M15) 2026.06.01 00:00:00 [PSARTrail] Initialized on EURUSD with 300 bars, adaptive=on. CS 0 18:39:32.192 Ticks EURUSD : real ticks begin from 2021.01.04 00:00:00 CS 0 18:39:32.382 DEMO_PSAR_Trailing (EURUSD,M15) 2026.06.01 00:30:00 [DivPro] EURUSD BULLISH ACCEPTED | score 51 | 2026.05.29 21:15 -> 2026.05.29 23:45 | price 1.06 ATR -> 1.00 | osc 2.0 pts -> 0.20 | spacing 10 bars -> 0.33 CS 0 18:39:37.025 DEMO_PSAR_Trailing (EURUSD,M15) 2026.06.01 07:30:00 [DivPro] EURUSD BULLISH ACCEPTED | score 63 | 2026.06.01 05:15 -> 2026.06.01 06:45 | price 0.81 ATR -> 0.81 | osc 27.0 pts -> 1.00 | spacing 6 bars -> 0.07 CS 0 18:39:37.511 Trade 2026.06.01 08:15:00 market buy 0.1 EURUSD (1.16516 / 1.16518)
Reading from left to right, the line shows the direction and status, the score, the older and newer pivot times, and then each measurement followed by its sub-score. A rejected pair prints the same way with its reason in place of ACCEPTED, for example, TOO_CLOSE, which is the quickest way to see which filter acts first on a given chart. Only one pair is stored for each new pivot, so the log does not show every pair the filters turned away.
The lines come from one run of the demo EA in the Strategy Tester, with lines between them left out, and these settings:
| Setting | Value |
|---|---|
| Symbol and timeframe | EURUSD, M15 |
| Dates | 2026.06.01 to 2026.06.29 |
| Data | MetaQuotes-Demo server, hedging demo account, terminal build 6231 |
| Modelling | Every tick based on real ticks |
| Spread | The real ticks' own bid and ask, so it can change within a bar. No fixed spread was set |
| Commission | Not recorded with the run |
| Execution | No delay |
| Deposit and leverage | 100,000 USD, 1:100 |
| Inputs | Every divergence, pairing, filter and score input at its default. Changed from the defaults: InpEnableAdaptive true, InpStartPoints 400, InpMinStopBuffer 400, InpRequireBreakEven true, InpVerboseLog true |
Driving the Engine From Your Own Loop
Refresh() is the whole pass:
//+------------------------------------------------------------------+ //| Run a whole pass | //+------------------------------------------------------------------+ bool CDivergenceEnginePro::Refresh(void) { if(!BeginPass()) return false; for(int i = m_limit; i >= 0; i--) ProcessBar(i); return m_ready; }
BeginPass() copies the window, refreshes the RSI buffer if RSI is the source, seeds the oscillator, computes ATR, and clears the stored pivots and records. The loop then processes every bar from Limit(), the oldest usable bar, down to 0. A consumer that needs to do its own work on each bar, in the same pass and in the same order, calls those pieces itself: BeginPass() once, then ProcessBar(i) inside its own loop from Limit() down to 0.
//+------------------------------------------------------------------+ //| Process one bar. Bars must arrive from Limit() down to 0. | //+------------------------------------------------------------------+ void CDivergenceEnginePro::ProcessBar(const int i) { if(i != m_expect) { WarnUsage(StringFormat("ProcessBar(%d) called out of order, expected %d. Call BeginPass(), then loop from Limit() down to 0.", i, m_expect)); return; } CalculateOscillator(m_base, i, m_open, m_close, m_point); //--- Inherit the previous bar's state m_lastSig[i] = (i < m_limit) ? m_lastSig[i + 1] : -1; //--- A pivot at p is known once PivotLength bars on each side have been processed int p = i + m_cfg.PivotLength; if(p + m_cfg.PivotLength <= m_limit) { int kind = PivotKindAt(p); if(kind != 0) PairNewPivot(AddPivot(kind == 1, p, i), i); } m_processedDown = i; m_expect = i - 1; if(i == 1 && m_cfg.LogRecords) LogConfirmedAt(1); if(i == 0) m_ready = true; }Each call computes the oscillator for the bar, copies the previous bar's divergence state forward, and tests the bar PivotLength bars back for a pivot. That bar now has enough processed bars on both sides to be tested. A new pivot is stored and paired at once. PivotKindAt() is the same strict test the previous engine used, and it is not repeated here. The engine only accepts the bar it expects next. A call for any other bar prints a single warning and does nothing, so a mistake in the consumer's loop shows up in the log and cannot corrupt the state.
The reason to drive the loop yourself is ResetAt():
//+------------------------------------------------------------------+ //| Clear the state of the bar just processed, and stop every later | //| pivot from pairing with a pivot stored before it | //+------------------------------------------------------------------+ void CDivergenceEnginePro::ResetAt(const int i) { if(i != m_processedDown || i > m_limit) { WarnUsage(StringFormat("ResetAt(%d) ignored: only the bar just processed (%d) can be reset.", i, m_processedDown)); return; } m_lastSig[i] = -1; m_barrier = ArraySize(m_pivots); }
A reset clears the divergence state of the bar just processed and moves a barrier up to the current end of the pivot list. The search in PairNewPivot() never goes below that barrier, so no later pivot can pair with a pivot stored before the reset. The next bar inherits the cleared state, and pivots stored before the reset no longer count. The previous engine's reset on a trend flip had the same purpose, with one difference: it could still pair a pivot that formed before the flip and was confirmed after it, and this class does not.
Only the bar just processed can be reset; a reset for any other bar is refused with the same one-time warning. Both ways of running a pass remain supported for this reason. A consumer that only reads results calls Refresh(). A consumer whose own per-bar logic can decide, in the middle of the pass, that the divergence state should be cleared calls the three pieces and resets at the exact bar where its own condition occurred.
Upgrading the Trailing Utility
Open your trailing header and compare it with the upgraded one. The adaptation formula changes in two existing lines, with one new line added. Moving the header onto the new engine is a larger change because the new engine owns the price window and the per-bar loop.
What Changed in the Header
| Before | After |
|---|---|
| Five engine settings in PSARTrailConfig: DivSource, MPOLength, MPOSmooth, RSIPeriod, PivotLength | One nested DivergenceProConfig Div, plus ScaleByScore |
| The header's own price arrays and a price copy on each refresh | Prices read from the engine's window with BarOpen() to BarClose() |
| CalculateOscillator() and DetectDivergence() in the SAR loop | m_engine.ProcessBar(i) |
| ResetDivergenceState() on a flip | m_engine.ResetAt(i) |
| GetLastDivergenceType(), GetBarsSinceDivergence() | m_engine.Type(), m_engine.Age() |
| - | New queries: DivergenceScore(), LatestDivergence() |
PSARTrailConfig goes from twenty-four fields to twenty-one. The nested struct carries every divergence setting, and Init() overwrites its symbol, timeframe, and lookback with the header's own before starting the engine, so the SAR and the divergence engine always run on the same market and the same number of bars. The header got shorter because it no longer copies prices at all.
Scaling the Adaptation
//+------------------------------------------------------------------+ //| Step for one bar, adapted only by a divergence that argues | //| against the direction the SAR is currently trailing | //+------------------------------------------------------------------+ double CAdaptivePSARTrail::AdaptiveStepAt(const int shift, const int trendDir) { double stepNow = m_cfg.SARStep; if(!m_cfg.EnableAdaptive) return stepNow; int divType = m_engine.Type(shift); int barsSince = m_engine.Age(shift); if(divType == 0 || barsSince > m_cfg.DivBarsLimit) return stepNow; //--- A bullish divergence during a downtrend, or a bearish one during an uptrend bool opposes = (trendDir == 1 && divType == -1) || (trendDir == -1 && divType == 1); if(!opposes) return stepNow; //--- A divergence scoring 50 moves the step half as far as one scoring 100 double strength = m_cfg.ScaleByScore ? m_engine.Score(shift) / 100.0 : 1.0; if(m_cfg.AdaptMode == PSAR_ADAPT_REDUCE) stepNow = m_cfg.SARStep * (1.0 - m_cfg.AdaptFactor * strength); else stepNow = m_cfg.SARStep * (1.0 + m_cfg.AdaptFactor * strength); //--- Confine to a usable range if(stepNow < 0.0001) stepNow = 0.0001; if(stepNow > m_cfg.SARMaximum) stepNow = m_cfg.SARMaximum; return stepNow; }The two queries at the top now go to the class, and the new strength line turns the score into a fraction. The two formula lines multiply AdaptFactor by that fraction. With ScaleByScore on, a divergence scoring 50 moves the step half as far as AdaptFactor alone would, and one scoring 100 moves it the full amount. Scaling does not block anything. With MinScore at zero, a pair scoring 10 still adapts the step, by a tenth of AdaptFactor, and with ScaleByScore off it adapts it in full. To keep low-scoring pairs out of the adaptation altogether, set MinScore. With ScaleByScore off, the strength is 1, and the adaptation behaves as it did before. DivBarsLimit still applies, so the score scales the adaptation within the age limit and does not replace it.
One Window for the SAR and the Divergence
//+------------------------------------------------------------------+ //| Recompute the oscillator, divergence state and SAR series | //+------------------------------------------------------------------+ bool CAdaptivePSARTrail::Refresh(void) { m_ready = false; //--- The engine copies the window; the SAR is computed on exactly the same bars if(!m_engine.BeginPass()) return false; m_bars = m_engine.BarCount(); m_limit = m_engine.Limit(); if(m_bars != m_sizedFor && !AllocateBuffers(m_bars)) return false; ComputeSeries(); m_lastRefreshBar = m_engine.BarTime(0); m_ready = true; return true; }
The header starts the engine's pass and takes its bar count and oldest usable bar from the engine. It then sizes its own SAR, step, and trend buffers to match. The SAR loop inside ComputeSeries() walks the same bars from Limit() down to 0. It calls m_engine.ProcessBar(i) at the top of each iteration and reads that bar's prices from the engine. When the SAR flips on a bar and ResetOnTrendChange is on, it calls m_engine.ResetAt(i) for that bar, which is the bar the engine has just processed. The step for the bar is then taken from AdaptiveStepAt(), which reads the divergence state the engine produced for that same bar. Since the engine's window is the only price copy, the SAR and the divergence state cannot end up on different bars, and the reset lands on the flip bar exactly as it did before.
New Inputs in the Demo EA
DEMO_PSAR_Trailing.mq5 exposes the new settings as inputs and copies them into cfg.Div in OnInit(). Its other inputs are unchanged.
| Group | Inputs | Defaults |
|---|---|---|
| Adaptive Settings | InpScaleByScore | true |
| Divergence Pairing and Filters | InpPairingDepth, InpMinSeparation, InpMaxSeparation, InpATRPeriod, InpMinPriceExtATR, InpMinOscDelta, InpUseZone, InpBullZoneLevel, InpBearZoneLevel, InpMinScore | 3, 5, 60, 14, 0.10, 1.0, false, −30, 30, 0 |
| Divergence Score | InpPriceExtFullATR, InpOscDeltaFull, InpSepFullBars, InpWeightPrice, InpWeightOsc, InpWeightSep, InpLogDivergence | 1.0, 10.0, 20, 1.0, 1.0, 1.0, true |
Limitations
The window is recomputed on every refresh. Its oldest bars only feed the calculations, and changing Lookback changes the results near the old end of the window, as in the previous engine. The per-bar queries are bound by the window as well. Once the older pivot of the latest accepted divergence has moved out of it, that divergence is no longer found, and Type() and Age() stop reporting it. Pivots are still found on the oscillator only. The price recorded for a pivot is the bar's high or low at the oscillator pivot, which is not necessarily a price pivot. Only regular divergence is detected.
Hidden divergence, where the price makes a higher low and the oscillator a lower low, is not. Each new pivot produces at most one record: the nearest pair that passes or, when none passes, the nearest pair that was measured and rejected. It is never chosen for having the highest score. A pivot whose candidates never reach the measurement step produces no record. The score is relative to its references and weights. Every default is a template value, neither tuned nor measured, and a score is not a probability or a win rate. The Score shows how a score moves with its settings by arithmetic on two made-up pairs, and how many pairs each setting accepts on a real chart was not measured. The zone levels are in the source's own units. The ±30 levels used with MPO4 do not apply to RSI, which requires its own levels.
A pair confirmed on bar 0 was confirmed on the bar that is still forming. The per-bar queries read bar 1 by default for that reason, and a consumer that reads bar 0 has to accept that the result can change before the bar closes. LogRecords assumes one pass per bar. A consumer that refreshes on every tick will print the same pairs repeatedly. Nothing persists across a restart. The state is rebuilt from the window on the first pass, and one instance handles one symbol and one timeframe. The log in Reading the Results comes from one run on one server's EURUSD history, and the run was not repeated.
Mistakes in driving the engine are refused, not repaired. A ProcessBar() call out of order, or a ResetAt() on a bar other than the one just processed, does nothing after a single printed warning, and that pass's results should not be trusted.
Conclusion
CDivergenceEnginePro keeps every oscillator pivot it confirms inside its window, compares each new pivot with several earlier ones, and chooses the nearest pair that shows a clean divergence and passes the filters. Each pair is measured by how far price moved past the older pivot in ATR, how far the oscillator disagreed in its own points, and how many bars separate the two pivots. Those three measurements combine into a score from 0 to 100, which measures size against the chosen settings and is not a probability. Pairs that are too close, too small, or outside a zone are rejected with a named reason. When nothing passes for a new pivot, the nearest rejected pair is kept, so a trader can see which filter stopped it.
Integration takes four steps instead of eight stages, and a consumer that needs to reset divergence state in the middle of its own loop can still drive the engine one bar at a time. The trailing header runs on the new engine, reads its prices from the engine's window, and scales its adaptation by the score, so a low-scoring divergence moves the acceleration step less than a high-scoring one.
Every record carries both pivots' times, prices, and oscillator values. Drawing those records on the chart, including rejected pairs, is the subject of the next part.
The source files are attached below.
| Filename | Description |
|---|---|
| DivergenceEnginePro.mqh | The scoring divergence engine: multi-pivot storage, pair selection, three measurements and a 0 to 100 score, filters with named rejection reasons, and per-bar queries. Requires DivergenceEngine.mqh. |
| AdaptivePSARTrail.mqh | The adaptive Parabolic SAR trailing header, upgraded to run on the scoring engine and to scale its adaptation by the score. |
| DEMO_PSAR_Trailing.mq5 | The demonstration EA, with inputs for the new pairing, filter, and score settings and the score shown on each divergence arrow. |
| DivergenceEngine.mqh | The oscillator engine the new class builds on, unchanged. |
| MQL5.zip | Archive containing the four source files, arranged in the required MQL5 terminal directory structure. |
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.