Aggregating Order Flow Delta from Tick Data in MQL5
Introduction
Two bars can share the same open, high, low, and close and still tell opposite stories. In one, buyers lifted the offer again and again until the price drifted up. In the other, sellers hit the bid all the way down, and a few quote jumps carried the price up anyway. OHLC data cannot separate the two, because it records where price went and not how it got there.
Order flow delta is one of the simplest tools for reading that hidden story. It subtracts seller initiated volume from buyer initiated volume inside each bar. On trade data, a strongly positive value suggests aggressive buying, a strongly negative value suggests aggressive selling, and a value near zero suggests balance. On quote data, the same values describe quote pressure only. Computing it requires raw ticks because only ticks carry the direction of price changes inside a bar.
This article presents an indicator that computes delta from raw ticks. For each bar, it reads ticks via CopyTicksRange(), classifies them with the tick rule, and aggregates buy, sell, and unclassified volume (or tick counts in proxy mode). It plots per-bar or cumulative delta as a colored histogram and marks divergences with arrows.
One caveat belongs at the start. Most feeds do not report who initiated a trade, so the tick rule infers the answer from price changes. The result is a context signal for judging pressure. It is not a record of what happened, and it is not a forecast of what comes next.
The project consists of small, pure, testable classes plus a thin wrapper over the terminal tick history. The article explains how to carry state across bars, avoid plotting missing data as zero, and recalculate only changed parts. It introduces the theory first, then reviews each class, and ends with tests, annotated screenshots, and a list of limitations.
Order Flow Delta and the Tick Rule
This section defines the quantities the code computes and the assumptions behind them. Every design decision later in the article traces back to one of these definitions, so it is worth reading them closely.
What delta measures
Buyer initiated volume is volume where the buyer was the aggressor, meaning the trade printed at or above the ask. Seller initiated volume is the mirror case. Delta is buyer initiated volume minus seller initiated volume for a bar.
A positive delta suggests net buying pressure inside the bar, and a negative delta suggests net selling pressure. Delta can disagree with the candle. A bar can close higher while most of its classified volume was seller initiated. The close reflects where the last trades printed. Delta reflects how the volume was split along the way. These definitions apply to trade-based data. In the quote-based mode, buyer initiated means only that the bid moved up.
The tick rule
The tick rule compares each tick price with the previous tick price from the same source:
- A price above the previous price is a buy.
- A price below the previous price is a sell.
- An unchanged price repeats the most recent direction.
An unchanged price carries no new information about who initiated the trade, so the rule keeps the latest evidence. Without that step, long runs of equal prices would stay unclassified. A tick that still cannot be classified goes into its own unclassified bucket. That covers the first tick the indicator sees, and an unchanged tick when no direction has been established yet.
The rule is a standard approximation, not a measurement. It can misclassify trades that occur at an unchanged price. Classification from bid quotes is also weaker than classification from trade prices, because quotes can move without any trade.
The Bid source has one more weakness. A quote update that changes only the ask arrives as a tick with an unchanged bid, so the rule repeats the previous direction. A long run of ask-only updates therefore piles up on the side of the last bid move, with no trade and no bid change behind it.
MqlTick can carry the TICK_FLAG_BUY and TICK_FLAG_SELL flags on some feeds. This project uses the tick rule because those flags are not available on every feed. Flag-based classification is covered later as an extension.
Price sources and volume modes
The price source is either the Last price or the Bid price. The volume mode is either the tick volume field of each MqlTick or a tick count of one per tick. The tick volume field is meaningful on exchange symbols with Last-price ticks, where each trade carries a volume.
The terminal also reports a tick volume for each bar, which is the number of ticks in that bar. This article calls it the bar tick volume, to keep it distinct from the tick volume field of a single tick.
On symbols such as spot forex, trade ticks and volume fields are usually empty. The Bid source with tick count mode is then the working combination, and it is a proxy: it counts quote updates, not traded volume. The sub-window title says so on the chart. The Bid source combined with the tick volume field normally gives an all-zero delta, so OnInit() prints a warning for that pairing.
Two modes, two meanings
The two supported combinations measure different things, and this article keeps them apart.
The trade-based mode uses the Last price with the tick volume field. It approximates order flow delta in the usual sense, with the tick rule standing in for the unknown aggressor.
The quote-based mode uses the Bid price with tick count. It counts bid updates that moved up or down, so it describes quote pressure, not traded volume. The article calls its output the quote update proxy.
Architecture
Figure 1 shows the whole project on one page. Data flows down the spine from the indicator to the divergence detector, and then splits into the two plots. The two side boxes are the terminal tick history on the left and the shared types on the right.
Architectural Diagram

Figure 1: Architecture of the project: The indicator calls the reader, which wraps CopyTicksRange(). Ticks flow through the classifier into the aggregator, and the detector consumes the cumulative series. The histogram and the divergence arrows are the two outputs. The dashed arrow marks a shared dependency, not a data flow.
The Data Model: OrderFlowTypes.mqh
Every other file depends on this one, so it comes first. It defines the vocabulary of the project: five enums, three color index constants, and two data structures. The central rule of the data model is simple. Any value that is not computed must be explicitly marked as undefined. Every figure that can be undefined travels with a flag, and the plot buffers hold EMPTY_VALUE for undefined bars, so the chart never shows a missing value as zero. Internal fields such as delta, total_volume, and the cumulative buffer do hold 0.0 for an undefined bar, so code that reads them must check the matching flag.
Every enum and constant carries an OF_ or ENUM_OF_ prefix, so nothing collides with built-in names such as TICK_FLAG_BUY. The comment after each enum value becomes its label in the inputs dialog. Direction has an explicit OF_DIR_NONE value, so an unclassified tick is never confused with a buy or a sell.
//+------------------------------------------------------------------+ //| OrderFlowTypes.mqh | //| Shared enums and data containers | //+------------------------------------------------------------------+ #ifndef ORDERFLOWTYPES_MQH #define ORDERFLOWTYPES_MQH //--- color index mapping for the delta histogram #define OF_COLOR_POSITIVE 0 #define OF_COLOR_NEGATIVE 1 #define OF_COLOR_NEUTRAL 2 //--- tolerance used when comparing two prices of the same source #define OF_PRICE_EPSILON 1.0e-10 //+------------------------------------------------------------------+ //| Direction assigned to a tick by the tick rule | //+------------------------------------------------------------------+ enum ENUM_OF_DIRECTION { OF_DIR_SELL = -1, // Seller initiated OF_DIR_NONE = 0, // Unclassified OF_DIR_BUY = 1 // Buyer initiated }; //+------------------------------------------------------------------+ //| Price field used by the tick rule | //+------------------------------------------------------------------+ enum ENUM_OF_PRICE_SOURCE { OF_PRICE_LAST = 0, // Last price OF_PRICE_BID = 1 // Bid price }; //+------------------------------------------------------------------+ //| Volume measure accumulated per tick | //+------------------------------------------------------------------+ enum ENUM_OF_VOLUME_MODE { OF_VOL_TICK_VOLUME = 0, // Tick volume field OF_VOL_TICK_COUNT = 1 // Tick count (proxy) }; //+------------------------------------------------------------------+ //| Series shown by the histogram | //+------------------------------------------------------------------+ enum ENUM_OF_DISPLAY_MODE { OF_DISPLAY_BAR_DELTA = 0, // Per-bar delta OF_DISPLAY_CUMULATIVE = 1 // Cumulative delta }; //+------------------------------------------------------------------+ //| Result of the divergence test on one bar | //+------------------------------------------------------------------+ enum ENUM_OF_DIVERGENCE { OF_DIV_NONE = 0, OF_DIV_BEARISH = 1, OF_DIV_BULLISH = 2 };
CTickState and CBarDelta are plain data carriers, so they are declared as structures. CTickState holds the three values the tick rule needs between ticks. CBarDelta holds the results for one bar.
Any figure that can be undefined carries its own flag. The delta ratio has delta_ratio_defined, and the whole record has data_complete, which stays false until an aggregation fills it. The ratio divides by total volume, which includes unclassified volume. The indicator does not plot the ratio, but it is available for extensions.
//+------------------------------------------------------------------+ //| Tick rule state carried from tick to tick and bar to bar | //+------------------------------------------------------------------+ struct CTickState { bool has_price; double last_price; ENUM_OF_DIRECTION last_direction; CTickState(void); void Reset(void); }; //+------------------------------------------------------------------+ //| Aggregated order flow figures for one bar | //+------------------------------------------------------------------+ struct CBarDelta { datetime bar_time; int tick_count; int classified_count; int unclassified_count; double buy_volume; double sell_volume; double unclassified_volume; double total_volume; double delta; double delta_ratio; bool delta_ratio_defined; bool data_complete; CTickState end_state; CBarDelta(void); void Reset(void); };
The constructors and Reset() methods are defined outside the structures. Reset() puts every member into its not-computed state, so a caller that checks the flag never mistakes a fresh record for a computed zero.
//+------------------------------------------------------------------+ //| Constructor: start from an empty state | //+------------------------------------------------------------------+ CTickState::CTickState(void) { Reset(); } //+------------------------------------------------------------------+ //| Clears the state: no price seen and no direction known | //+------------------------------------------------------------------+ void CTickState::Reset(void) { has_price = false; last_price = 0.0; last_direction = OF_DIR_NONE; } //+------------------------------------------------------------------+ //| Constructor: start from an empty record | //+------------------------------------------------------------------+ CBarDelta::CBarDelta(void) { Reset(); } //+------------------------------------------------------------------+ //| Clears every figure. data_complete is false until a successful | //| aggregation sets it, so a caller that checks the flag never | //| mistakes a fresh record for a computed zero. | //+------------------------------------------------------------------+ void CBarDelta::Reset(void) { bar_time = 0; tick_count = 0; classified_count = 0; unclassified_count = 0; buy_volume = 0.0; sell_volume = 0.0; unclassified_volume = 0.0; total_volume = 0.0; delta = 0.0; delta_ratio = 0.0; delta_ratio_defined = false; data_complete = false; end_state.Reset(); } #endif // ORDERFLOWTYPES_MQH
Reading Tick Data per Bar: TickDataReader.mqh
Everything above this file is pure arithmetic. This file is the only place where the program asks the terminal for data, which makes it the only place where data can be missing, late, or wrong. Isolating that risk in one small class keeps the rest of the project testable and makes failure handling explicit.
The class does two jobs. It converts bar times into exact millisecond boundaries, and it wraps CopyTicksRange() so that a failure is reported instead of hidden.
Millisecond boundaries
CopyTicksRange() takes inclusive millisecond bounds. A bar covers the range from its open time multiplied by 1000, to the next bar open time multiplied by 1000 minus 1. The next bar then starts exactly one millisecond later, so every tick belongs to one bar, with no overlap and no gap.
BuildRange() is separate from the terminal call so the arithmetic can be tested without tick history. It rejects empty and reversed ranges. ChooseFlags() maps the price source to copy flags: the Last source needs trade ticks, and the Bid source needs quote-change ticks.
//+------------------------------------------------------------------+ //| TickDataReader.mqh | //| The only wrapper around CopyTicksRange() | //+------------------------------------------------------------------+ #ifndef TICKDATAREADER_MQH #define TICKDATAREADER_MQH #include "OrderFlowTypes.mqh" //+------------------------------------------------------------------+ //| Reads the ticks of one bar from the terminal tick history | //+------------------------------------------------------------------+ class CTickDataReader { private: int m_last_error; uint ChooseFlags(const ENUM_OF_PRICE_SOURCE source) const; public: CTickDataReader(void); ~CTickDataReader(void); bool BuildRange(const datetime bar_open, const datetime next_bar_open, ulong &from_msc, ulong &to_msc) const; int ReadBarTicks(const string symbol, const datetime bar_open, const datetime next_bar_open, const ENUM_OF_PRICE_SOURCE source, MqlTick &ticks[]); int LastError(void) const; }; //+------------------------------------------------------------------+ //| Constructor | //+------------------------------------------------------------------+ CTickDataReader::CTickDataReader(void) { m_last_error=0; } //+------------------------------------------------------------------+ //| Destructor | //+------------------------------------------------------------------+ CTickDataReader::~CTickDataReader(void) { } //+------------------------------------------------------------------+ //| Chooses the copy flags for the price source. Last price needs | //| trade ticks; bid price needs info (quote change) ticks. | //+------------------------------------------------------------------+ uint CTickDataReader::ChooseFlags(const ENUM_OF_PRICE_SOURCE source) const { if(source==OF_PRICE_LAST) return(COPY_TICKS_TRADE); if(source==OF_PRICE_BID) return(COPY_TICKS_INFO); return(COPY_TICKS_ALL); } //+------------------------------------------------------------------+ //| Converts two bar open times into inclusive millisecond bounds. | //| The range is [bar_open*1000, next_bar_open*1000-1], so the end | //| of one bar and the start of the next never overlap and leave no | //| gap. Returns false when the range is empty or reversed. | //+------------------------------------------------------------------+ bool CTickDataReader::BuildRange(const datetime bar_open, const datetime next_bar_open, ulong &from_msc, ulong &to_msc) const { from_msc=0; to_msc=0; if(bar_open<=0 || next_bar_open<=bar_open) return(false); from_msc=(ulong)bar_open*1000; to_msc=(ulong)next_bar_open*1000-1; return(true); }
Failure handling and synchronization
ReadBarTicks() returns the tick count, or -1 on failure. On failure it records GetLastError() and clears the output array, so no partial data is ever used. The caller can then mark the bar incomplete instead of plotting a false zero.
Tick history is synchronized on demand. The first request for a symbol or period may fail, or return nothing, while the terminal downloads ticks from the server. A return of 0 is therefore ambiguous, because it can mean a quiet bar or a missing download. The indicator uses the bar tick volume as a hint, and the hint has limits, as described later.
//+------------------------------------------------------------------+ //| ReadBarTicks | //+------------------------------------------------------------------+ int CTickDataReader::ReadBarTicks(const string symbol, const datetime bar_open, const datetime next_bar_open, const ENUM_OF_PRICE_SOURCE source, MqlTick &ticks[]) { m_last_error=0; ::ArrayFree(ticks); //--- millisecond boundaries ulong from_msc=0; ulong to_msc=0; if(!BuildRange(bar_open,next_bar_open,from_msc,to_msc)) { m_last_error=ERR_INVALID_PARAMETER; return(-1); } //--- request the ticks uint flags=ChooseFlags(source); ::ResetLastError(); int copied=::CopyTicksRange(symbol,ticks,flags,from_msc,to_msc); if(copied<0) { m_last_error=::GetLastError(); ::ArrayFree(ticks); return(-1); } return(copied); } //+------------------------------------------------------------------+ //| Returns the error code recorded by the last ReadBarTicks() call | //+------------------------------------------------------------------+ int CTickDataReader::LastError(void) const { return(m_last_error); } #endif // TICKDATAREADER_MQH
Classifying Ticks with the Tick Rule: TickClassifier.mqh
This class turns a single price change into a direction. It holds no state and calls no terminal functions, so the caller supplies everything the rule needs. That choice makes the tick rule the easiest part of the project to test, and the most important one to get exactly right.
The class has three methods. ClassifyDirection() applies the rule, ExtractPrice() reads the chosen price from a tick, and ExtractVolume() reads the chosen volume. The first listing shows the class declaration with its constructor and destructor.
//+------------------------------------------------------------------+ //| TickClassifier.mqh | //| Tick rule and tick field extraction | //+------------------------------------------------------------------+ #ifndef TICKCLASSIFIER_MQH #define TICKCLASSIFIER_MQH #include "OrderFlowTypes.mqh" //+------------------------------------------------------------------+ //| Pure helpers: no terminal calls, no stored state | //+------------------------------------------------------------------+ class CTickClassifier { public: CTickClassifier(void); ~CTickClassifier(void); ENUM_OF_DIRECTION ClassifyDirection(const bool has_previous, const double previous_price, const ENUM_OF_DIRECTION previous_direction, const double new_price) const; bool ExtractPrice(const MqlTick &tick, const ENUM_OF_PRICE_SOURCE source, double &price) const; bool ExtractVolume(const MqlTick &tick, const ENUM_OF_VOLUME_MODE mode, double &volume) const; }; //+------------------------------------------------------------------+ //| Constructor | //+------------------------------------------------------------------+ CTickClassifier::CTickClassifier(void) { } //+------------------------------------------------------------------+ //| Destructor | //+------------------------------------------------------------------+ CTickClassifier::~CTickClassifier(void) { }
ClassifyDirection() applies the tick rule to one price change. With no previous price, it returns none. An unchanged price has its own explicit branch and repeats the previous direction, so a zero difference is never treated as a buy or a sell. Otherwise, a rise is a buy and a fall is a sell.
OF_PRICE_EPSILON is far smaller than any real tick size, so only prices that are identical in practice count as unchanged.
//+------------------------------------------------------------------+ //| ClassifyDirection | //+------------------------------------------------------------------+ ENUM_OF_DIRECTION CTickClassifier::ClassifyDirection(const bool has_previous, const double previous_price, const ENUM_OF_DIRECTION previous_direction, const double new_price) const { //--- no earlier price: the tick cannot be classified if(!has_previous) return(OF_DIR_NONE); //--- price difference against the previous tick double difference=new_price-previous_price; //--- unchanged price: repeat the previous direction (zero is never a buy or a sell by itself) if(::MathAbs(difference)<=OF_PRICE_EPSILON) return(previous_direction); //--- price increase is a buy, price decrease is a sell if(difference>0.0) return(OF_DIR_BUY); return(OF_DIR_SELL); }
ExtractPrice() returns the field for the chosen source and reports success through its return value. A zero, negative, or non-numeric price returns false. This matters on exchange symbols, where quote-only ticks carry a zero Last price.
//+------------------------------------------------------------------+ //| ExtractPrice | //+------------------------------------------------------------------+ bool CTickClassifier::ExtractPrice(const MqlTick &tick, const ENUM_OF_PRICE_SOURCE source, double &price) const { price=0.0; double candidate=0.0; //--- pick the field that matches the source switch(source) { case OF_PRICE_LAST: candidate=tick.last; break; case OF_PRICE_BID: candidate=tick.bid; break; default: return(false); } //--- reject undefined values if(!::MathIsValidNumber(candidate)) return(false); if(candidate<=0.0) return(false); price=candidate; return(true); }
ExtractVolume() supports the two volume modes. Tick count mode always returns one, which is the proxy for symbols whose volume fields are empty. Tick volume field mode prefers volume_real and falls back to volume.
The documented rule for a zero volume field is explicit. The method returns false with volume set to 0.0. The tick still moves the tick rule state and still counts as a tick, but it adds nothing to the volume totals.
//+------------------------------------------------------------------+ //| ExtractVolume | //+------------------------------------------------------------------+ bool CTickClassifier::ExtractVolume(const MqlTick &tick, const ENUM_OF_VOLUME_MODE mode, double &volume) const { volume=0.0; //--- tick count proxy: every tick weighs one if(mode==OF_VOL_TICK_COUNT) { volume=1.0; return(true); } //--- tick volume fields if(mode==OF_VOL_TICK_VOLUME) { if(tick.volume_real>0.0) { volume=tick.volume_real; return(true); } if(tick.volume>0) { volume=(double)tick.volume; return(true); } //--- zero volume field: documented rule, no contribution return(false); } return(false); } #endif // TICKCLASSIFIER_MQH
Aggregating Delta per Bar: TickDeltaAggregator.mqh
The aggregator is the numerical heart of the project. It folds an array of ticks into one bar result, and it folds a series of bar results into a running total. Two ideas shape it. State flows through the method by reference so bars can be chained, and every tick with a valid price lands in exactly one bucket.
The class owns a CTickClassifier and reads no terminal data. The first listing shows its declaration, constructor, and destructor.
//+------------------------------------------------------------------+ //| TickDeltaAggregator.mqh | //| Per-bar delta and cumulative delta | //+------------------------------------------------------------------+ #ifndef TICKDELTAAGGREGATOR_MQH #define TICKDELTAAGGREGATOR_MQH #include "OrderFlowTypes.mqh" #include "TickClassifier.mqh" //+------------------------------------------------------------------+ //| Pure aggregation logic. Reads no terminal data. | //+------------------------------------------------------------------+ class CTickDeltaAggregator { private: CTickClassifier m_classifier; public: CTickDeltaAggregator(void); ~CTickDeltaAggregator(void); void AggregateTicks(const MqlTick &ticks[], const datetime bar_time, const ENUM_OF_PRICE_SOURCE source, const ENUM_OF_VOLUME_MODE mode, CTickState &state, CBarDelta &result); bool BuildCumulativeSeries(const double &delta[], const bool &delta_defined[], const datetime ×[], const int start, const int count, const bool reset_daily, double &cumulative[], bool &cumulative_defined[]); bool IsDifferentDay(const datetime first_time, const datetime second_time) const; int ColorIndexForDelta(const bool is_defined, const double delta) const; }; //+------------------------------------------------------------------+ //| Constructor | //+------------------------------------------------------------------+ CTickDeltaAggregator::CTickDeltaAggregator(void) { } //+------------------------------------------------------------------+ //| Destructor | //+------------------------------------------------------------------+ CTickDeltaAggregator::~CTickDeltaAggregator(void) { }
Aggregating the ticks of one bar
AggregateTicks() walks the tick array in time order. The state parameter is both input and output. It is the starting state, and it advances tick by tick. That is how state crosses bar boundaries, because the caller passes the stored state of the previous bar into the next one.
Each tick lands in exactly one bucket, and ticks with an invalid price are skipped and not counted. So tick_count is the number of valid ticks, not the number CopyTicksRange() returned. The totals are derived once at the end, so the identities hold by construction. Total volume equals buy plus sell plus unclassified volume, and delta equals buy minus sell volume. The delta ratio is guarded against a zero total.
//+------------------------------------------------------------------+ //| AggregateTicks | //+------------------------------------------------------------------+ void CTickDeltaAggregator::AggregateTicks(const MqlTick &ticks[], const datetime bar_time, const ENUM_OF_PRICE_SOURCE source, const ENUM_OF_VOLUME_MODE mode, CTickState &state, CBarDelta &result) { result.Reset(); result.bar_time=bar_time; result.data_complete=true; //--- walk every tick in chronological order int total=::ArraySize(ticks); for(int i=0; i<total; i++) { double price=0.0; if(!m_classifier.ExtractPrice(ticks[i],source,price)) continue; double volume=0.0; if(!m_classifier.ExtractVolume(ticks[i],mode,volume)) volume=0.0; //--- classify against the carried state, then advance the state ENUM_OF_DIRECTION direction=m_classifier.ClassifyDirection(state.has_price, state.last_price, state.last_direction, price); state.has_price=true; state.last_price=price; state.last_direction=direction; //--- accumulate into exactly one bucket result.tick_count++; if(direction==OF_DIR_BUY) { result.buy_volume+=volume; result.classified_count++; } else if(direction==OF_DIR_SELL) { result.sell_volume+=volume; result.classified_count++; } else { //--- OF_DIR_NONE: kept in its own bucket result.unclassified_volume+=volume; result.unclassified_count++; } } //--- totals, delta, and the guarded ratio result.total_volume=result.buy_volume+result.sell_volume+result.unclassified_volume; result.delta=result.buy_volume-result.sell_volume; if(result.total_volume>0.0) { result.delta_ratio=result.delta/result.total_volume; result.delta_ratio_defined=true; } else { result.delta_ratio=0.0; result.delta_ratio_defined=false; } //--- hand the ending state to the caller result.end_state=state; }
Cumulative series and the daily reset
BuildCumulativeSeries() converts per-bar deltas into a running total. All arrays are chronological, with index 0 as the oldest bar. The start parameter lets the caller recompute only a tail, because the running total at start minus one is the seed.
An undefined bar is flagged undefined, and the running total passes through it unchanged. Later totals are therefore offset by the missing delta, so treat cumulative values after a data hole with caution. The method returns false when the arrays are too small, and the indicator checks that result.
With the daily reset on, the total returns to zero on the first bar whose server-time day differs from the previous bar. This is a calendar day on the server clock, not an exchange trading session. Weekends, breaks, and session schedules are not modeled. The running total starts at zero at the first bar of the last full calculation, so the first day is a partial total. That base does not move as new bars arrive.
IsDifferentDay() compares whole days since the epoch. ColorIndexForDelta() gives an exact zero, or an undefined delta, the neutral index, so zero is never colored green or red.
//+------------------------------------------------------------------+ //| BuildCumulativeSeries | //+------------------------------------------------------------------+ bool CTickDeltaAggregator::BuildCumulativeSeries(const double &delta[], const bool &delta_defined[], const datetime ×[], const int start, const int count, const bool reset_daily, double &cumulative[], bool &cumulative_defined[]) { //--- validate ranges and array sizes if(count<0 || start<0 || start>count) return(false); if(::ArraySize(delta)<count || ::ArraySize(delta_defined)<count || ::ArraySize(times)<count || ::ArraySize(cumulative)<count || ::ArraySize(cumulative_defined)<count) return(false); //--- seed the running total from the bar before start double running=0.0; if(start>0) running=cumulative[start-1]; //--- accumulate for(int i=start; i<count; i++) { if(reset_daily && i>0) { if(IsDifferentDay(times[i-1],times[i])) running=0.0; } if(delta_defined[i]) { running+=delta[i]; cumulative_defined[i]=true; } else cumulative_defined[i]=false; cumulative[i]=running; } return(true); } //+------------------------------------------------------------------+ //| IsDifferentDay | //+------------------------------------------------------------------+ bool CTickDeltaAggregator::IsDifferentDay(const datetime first_time, const datetime second_time) const { long first_day=(long)first_time/86400; long second_day=(long)second_time/86400; return(first_day!=second_day); } //+------------------------------------------------------------------+ //| ColorIndexForDelta | //+------------------------------------------------------------------+ int CTickDeltaAggregator::ColorIndexForDelta(const bool is_defined, const double delta) const { if(!is_defined) return(OF_COLOR_NEUTRAL); if(delta>0.0) return(OF_COLOR_POSITIVE); if(delta<0.0) return(OF_COLOR_NEGATIVE); //--- exactly zero return(OF_COLOR_NEUTRAL); } #endif // TICKDELTAAGGREGATOR_MQH
Cumulative Delta and Divergence Theory
Before looking at the detector, we need an exact definition of divergence. A vague definition would produce a vague detector and tests that prove nothing. This section states the rule, its edge cases, and the reason signals are evaluated on closed bars only.
Per-bar delta tells us who won one bar. Cumulative delta is the running sum of those bars, so it shows whether pressure is building or fading across many bars. It can reveal that a rising market is met with steadily weaker upward pressure.
The divergence rule is exact: for bar i, find the bar j with the highest high in the preceding lookback window (excluding i ). A bearish divergence occurs when high(i) > high(j) and cumulative(i) < cumulative(j). The bullish case is symmetric. The low of bar i is strictly lower than the lowest low in the window, while cumulative delta is strictly higher than at that bar.
Equal highs, equal lows, or equal cumulative delta values are not divergences. Window bars with undefined cumulative delta are skipped. If several window bars share the extreme price, the most recent one is the reference. Bearish takes precedence if both conditions hold on the same bar.
With the daily reset on, a window that spans a server midnight would compare totals with different baselines. The indicator skips the divergence check for those bars, so the first lookback bars of each day never produce a signal. Because the rule compares two points of the same series, a constant offset in the cumulative base does not change the result. Only a reset or a data hole inside the window can.
Closed bars only
Divergence is evaluated on closed bars only. The forming bar has a changing high, low, and delta, so a signal on it can appear and vanish within seconds. Waiting for the close costs one bar of latency and removes that flicker, which is a deliberate design choice.
A closed-bar signal is stable once the tick history for its window is complete. No arrow is drawn while a window contains a missing bar. If a retry later fills the bar, signals near that bar can appear late.
The Divergence Detector: DivergenceDetector.mqh
The detector implements the rule above as a pure function. It receives arrays and indexes, returns an enum, and never touches the chart. Its main job is to say none whenever the evidence is missing, equal, or too short.
DetectAtBar() takes chronological high, low, and cumulative series, the defined flags, a bar index, and a lookback length. It validates the request first. A lookback below one, a bad index, or a window that would start before bar zero returns none, and so does an undefined cumulative value at the signal bar. The window scan then skips undefined bars and resolves ties to the most recent bar. The final comparisons are strict.
//+------------------------------------------------------------------+ //| DivergenceDetector.mqh | //| Price and cumulative delta divergence | //+------------------------------------------------------------------+ #ifndef DIVERGENCEDETECTOR_MQH #define DIVERGENCEDETECTOR_MQH #include "OrderFlowTypes.mqh" //+------------------------------------------------------------------+ //| Pure divergence test. All arrays are chronological (0 = oldest). | //+------------------------------------------------------------------+ class CDivergenceDetector { public: CDivergenceDetector(void); ~CDivergenceDetector(void); ENUM_OF_DIVERGENCE DetectAtBar(const double &high[], const double &low[], const double &cumulative[], const bool &cumulative_defined[], const int index, const int lookback) const; }; //+------------------------------------------------------------------+ //| Constructor | //+------------------------------------------------------------------+ CDivergenceDetector::CDivergenceDetector(void) { } //+------------------------------------------------------------------+ //| Destructor | //+------------------------------------------------------------------+ CDivergenceDetector::~CDivergenceDetector(void) { } //+------------------------------------------------------------------+ //| DetectAtBar | //| Tests bar index against the lookback bars before it (the bar | //| itself is excluded). Bearish: the high of the bar is strictly | //| above the highest high of the window while cumulative delta is | //| strictly below the value at that window bar. Bullish is the | //| mirror with lows and higher cumulative delta. Window bars with | //| undefined cumulative delta are skipped. If several window bars | //| share the extreme price, the most recent one is the reference. | //| Returns OF_DIV_NONE for insufficient lookback, undefined data, | //| bad indexes, or equal values. Bearish takes precedence when both | //| conditions hold on the same bar. | //+------------------------------------------------------------------+ ENUM_OF_DIVERGENCE CDivergenceDetector::DetectAtBar(const double &high[], const double &low[], const double &cumulative[], const bool &cumulative_defined[], const int index, const int lookback) const { //--- validate the request if(lookback<1 || index<0) return(OF_DIV_NONE); if(index>=::ArraySize(high) || index>=::ArraySize(low) || index>=::ArraySize(cumulative) || index>=::ArraySize(cumulative_defined)) return(OF_DIV_NONE); if(index-lookback<0) return(OF_DIV_NONE); if(!cumulative_defined[index]) return(OF_DIV_NONE); //--- find the extreme bars inside the preceding window int high_bar=-1; int low_bar=-1; for(int j=index-lookback; j<index; j++) { if(!cumulative_defined[j]) continue; if(high_bar<0 || high[j]>=high[high_bar]) high_bar=j; if(low_bar<0 || low[j]<=low[low_bar]) low_bar=j; } if(high_bar<0 || low_bar<0) return(OF_DIV_NONE); //--- bearish: strictly higher high, strictly lower cumulative delta if(high[index]>high[high_bar] && cumulative[index]<cumulative[high_bar]) return(OF_DIV_BEARISH); //--- bullish: strictly lower low, strictly higher cumulative delta if(low[index]<low[low_bar] && cumulative[index]>cumulative[low_bar]) return(OF_DIV_BULLISH); return(OF_DIV_NONE); } #endif // DIVERGENCEDETECTOR_MQH //+------------------------------------------------------------------+
Building the Indicator: OrderFlowDelta.mq5
The indicator is the only file that touches the chart. It connects the classes, owns the buffers, and decides what to recompute on each call. This section follows the order in which the terminal runs the code: declarations, initialization, calculation, and shutdown.
Display and buffer decisions
The histogram plots whichever series the display mode selects, either per-bar delta or cumulative delta. Its color always follows the sign of the per-bar delta of the same bar, in both modes. Divergence detection always uses cumulative delta, regardless of display mode.
All buffers and helper arrays are indexed chronologically, with index 0 as the oldest bar. OnInit() calls ArraySetAsSeries(false) on each of them, and OnCalculate() sets the same indexing on its input arrays explicitly, so the code does not depend on a default.
There are 8 buffers and 3 plots. Buffers 0 and 1 are the color histogram, holding values and color indexes. Buffer 2 is the bearish arrow, and buffer 3 is the bullish arrow. Buffers 4 to 7 are calculation buffers: per-bar delta, running cumulative delta, and the end-of-bar price and direction that make incremental recalculation possible.
The defaults use Bid + tick count because most symbols provide quote ticks. However, this is the weakest mode for traded-pressure analysis; use Last + tick volume whenever trade ticks are available. The first calculation processes up to InpMaxBars bars, from 10 to 100000, and each bar costs one CopyTicksRange() call. The window does not slide afterward. New bars extend it until the next full calculation, which happens on a reload, a timeframe change, or a history refresh.
The numeric defaults are safe starting values, not tuned results. InpMaxBars is 500 because each bar costs one CopyTicksRange() call, and 500 calls load quickly while still covering roughly three weeks of H1 bars. On a slow connection or an empty tick cache, lower it. On H4 or D1, 500 bars reach back further and are usually enough. InpDivLookback is 20 because it gives a window long enough to hold a clear swing and short enough to compare nearby highs and lows. Shorter windows give more signals and more noise. Longer windows give fewer signals that arrive later. A retry runs at most every 10 seconds, because tick history normally needs a few seconds to synchronize and shorter pauses only repeat the same failing call. The six retries therefore span at least one minute on an active symbol, which is long enough for a normal synchronization and short enough to stop a symbol without the selected ticks from being read again and again. For thin symbols, raise the retry interval. For very active symbols, keep InpMaxBars low, because the forming bar is re-read in full on every call.
Two details affect how the chart reads. The color shows the sign of the per-bar delta, so a green bar in cumulative mode does not mean that the total is positive. Divergence arrows sit at the plotted value of their bar, so in per-bar mode their height says nothing about the cumulative values that triggered them.
//+------------------------------------------------------------------+ //| OrderFlowDelta.mq5 | //| Order flow delta from tick data | //+------------------------------------------------------------------+ #property version "1.00" #property description "Per-bar and cumulative order flow delta from raw ticks (tick rule)." #property description "Tick count mode is a proxy, not true traded volume." #property indicator_separate_window #property indicator_buffers 8 #property indicator_plots 3 #property indicator_label1 "Delta" #property indicator_type1 DRAW_COLOR_HISTOGRAM #property indicator_style1 STYLE_SOLID #property indicator_width1 2 #property indicator_label2 "Bearish divergence" #property indicator_type2 DRAW_ARROW #property indicator_color2 clrMagenta #property indicator_width2 1 #property indicator_label3 "Bullish divergence" #property indicator_type3 DRAW_ARROW #property indicator_color3 clrAqua #property indicator_width3 1 #include <OrderFlowDelta/OrderFlowTypes.mqh> #include <OrderFlowDelta/TickDataReader.mqh> #include <OrderFlowDelta/TickDeltaAggregator.mqh> #include <OrderFlowDelta/DivergenceDetector.mqh> //--- minimum pause between retries of bars whose tick fetch failed #define OF_RETRY_INTERVAL_MS 10000 //--- maximum number of retry passes for bars whose tick fetch failed #define OF_MAX_RETRIES 6 //--- inputs input int InpMaxBars = 500; // Bars processed on a full calculation input ENUM_OF_PRICE_SOURCE InpPriceSource = OF_PRICE_BID; // Price source input ENUM_OF_VOLUME_MODE InpVolumeMode = OF_VOL_TICK_COUNT; // Volume mode input ENUM_OF_DISPLAY_MODE InpDisplayMode = OF_DISPLAY_BAR_DELTA; // Display mode input bool InpResetDaily = false; // Reset cumulative delta at server midnight input int InpDivLookback = 20; // Divergence lookback (bars) input bool InpShowDivergence = true; // Show divergence arrows //--- plot buffers (all buffers are chronological: index 0 is the oldest bar) double BufHist[]; // 0: histogram values double BufColor[]; // 1: histogram color index double BufBear[]; // 2: bearish arrows double BufBull[]; // 3: bullish arrows //--- calculation buffers double BufDelta[]; // 4: per-bar delta, EMPTY_VALUE when undefined double BufCum[]; // 5: running cumulative delta double BufEndPrice[]; // 6: end-of-bar last price, 0 when none double BufEndDir[]; // 7: end-of-bar direction (-1, 0, 1) //--- helper arrays and objects bool g_delta_def[]; bool g_cum_def[]; MqlTick g_ticks[]; CTickDataReader g_reader; CTickDeltaAggregator g_aggregator; CDivergenceDetector g_detector; int g_retry_from=-1; ulong g_last_retry_ms=0; bool g_warned=false; int g_retry_attempts=0; bool g_gave_up=false; bool g_failure_seen=false; int g_failure_error=0;
Initialization and shutdown: OnInit() and OnDeinit()
Initialization is where bad settings should fail early and loudly. OnInit() validates the inputs, warns about the Bid source with tick volume field mode, binds the buffers, and configures the plots. The three color indexes map to green, red, and gray. PLOT_EMPTY_VALUE is EMPTY_VALUE on all three plots, so bars with missing tick data plot as empty and never as zero.
The indicator short name states the settings, and in tick count mode it contains the word PROXY, so the warning stays visible on the chart. OnInit() also prints one line to the Experts tab with the symbol, timeframe, and settings. OnDeinit() prints the matching detach line with a readable reason.
//+------------------------------------------------------------------+ //| Validates inputs, binds buffers, and configures the plots | //+------------------------------------------------------------------+ int OnInit() { //--- validate inputs if(InpMaxBars<10 || InpMaxBars>100000) { Print("OrderFlowDelta: InpMaxBars must be between 10 and 100000."); return(INIT_PARAMETERS_INCORRECT); } if(InpDivLookback<2 || InpDivLookback>=InpMaxBars) { Print("OrderFlowDelta: InpDivLookback must be at least 2 and below InpMaxBars."); return(INIT_PARAMETERS_INCORRECT); } //--- bid quotes normally carry no volume, so this pairing gives an all-zero delta if(InpPriceSource==OF_PRICE_BID && InpVolumeMode==OF_VOL_TICK_VOLUME) Print("OrderFlowDelta: warning, bid quote ticks normally carry no volume field. Use tick count mode or the last price source."); //--- bind buffers: plot 0 uses buffers 0 and 1, plot 1 uses 2, plot 2 uses 3 SetIndexBuffer(0,BufHist,INDICATOR_DATA); SetIndexBuffer(1,BufColor,INDICATOR_COLOR_INDEX); SetIndexBuffer(2,BufBear,INDICATOR_DATA); SetIndexBuffer(3,BufBull,INDICATOR_DATA); SetIndexBuffer(4,BufDelta,INDICATOR_CALCULATIONS); SetIndexBuffer(5,BufCum,INDICATOR_CALCULATIONS); SetIndexBuffer(6,BufEndPrice,INDICATOR_CALCULATIONS); SetIndexBuffer(7,BufEndDir,INDICATOR_CALCULATIONS); //--- chronological indexing everywhere ArraySetAsSeries(BufHist,false); ArraySetAsSeries(BufColor,false); ArraySetAsSeries(BufBear,false); ArraySetAsSeries(BufBull,false); ArraySetAsSeries(BufDelta,false); ArraySetAsSeries(BufCum,false); ArraySetAsSeries(BufEndPrice,false); ArraySetAsSeries(BufEndDir,false); ArraySetAsSeries(g_delta_def,false); ArraySetAsSeries(g_cum_def,false); //--- histogram colors: 0 positive, 1 negative, 2 neutral PlotIndexSetInteger(0,PLOT_COLOR_INDEXES,3); PlotIndexSetInteger(0,PLOT_LINE_COLOR,OF_COLOR_POSITIVE,clrLimeGreen); PlotIndexSetInteger(0,PLOT_LINE_COLOR,OF_COLOR_NEGATIVE,clrRed); PlotIndexSetInteger(0,PLOT_LINE_COLOR,OF_COLOR_NEUTRAL,clrGray); //--- missing data plots as empty, never as zero PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,EMPTY_VALUE); PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,EMPTY_VALUE); PlotIndexSetDouble(2,PLOT_EMPTY_VALUE,EMPTY_VALUE); //--- arrow glyphs (Wingdings): 234 down arrow, 233 up arrow PlotIndexSetInteger(1,PLOT_ARROW,234); PlotIndexSetInteger(1,PLOT_ARROW_SHIFT,-12); PlotIndexSetInteger(2,PLOT_ARROW,233); PlotIndexSetInteger(2,PLOT_ARROW_SHIFT,12); //--- short name states the settings, including the proxy warning string source_text=(InpPriceSource==OF_PRICE_LAST)?"Last":"Bid"; string volume_text=(InpVolumeMode==OF_VOL_TICK_COUNT)?"tick count PROXY":"tick volume"; string display_text=(InpDisplayMode==OF_DISPLAY_CUMULATIVE)?"cumulative":"per bar"; string name=StringFormat("Order Flow Delta (%s, %s, %s)",source_text,volume_text,display_text); IndicatorSetString(INDICATOR_SHORTNAME,name); IndicatorSetInteger(INDICATOR_DIGITS,2); //--- report the attach event in the Experts tab PrintFormat("OrderFlowDelta: attached to %s %s. %s, max bars %d, daily reset %s, divergence lookback %d.", _Symbol,EnumToString(_Period),name,InpMaxBars, (InpResetDaily?"on":"off"),InpDivLookback); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Returns a readable text for an OnDeinit() reason code | //+------------------------------------------------------------------+ string DeinitReasonText(const int reason) { switch(reason) { case REASON_PROGRAM: return("indicator stopped itself"); case REASON_REMOVE: return("removed from the chart"); case REASON_RECOMPILE: return("recompiled"); case REASON_CHARTCHANGE: return("symbol or timeframe changed"); case REASON_CHARTCLOSE: return("chart closed"); case REASON_PARAMETERS: return("input parameters changed"); case REASON_ACCOUNT: return("account changed"); case REASON_TEMPLATE: return("template applied"); case REASON_INITFAILED: return("initialization failed"); case REASON_CLOSE: return("terminal closed"); } return("unknown reason"); } //+------------------------------------------------------------------+ //| Reports the detach event in the Experts tab | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { PrintFormat("OrderFlowDelta: detached from %s %s (%s, code %d).", _Symbol,EnumToString(_Period),DeinitReasonText(reason),reason); }
Restoring state and preparing arrays
Incremental calculation needs two small helpers. They restore the tick rule state at a chosen bar, and they make sure the arrays are ready before any bar is written.
LoadState() rebuilds the tick rule state from the stored end-of-bar price and direction. A stored price of zero means that no price was seen, since valid prices are always positive. PrepareArrays() resizes the two helper flag arrays and checks that the resize succeeded. On a full pass, it resets every bar to undefined, and ComputeBars() then fills the processing window.
//+------------------------------------------------------------------+ //| Rebuilds the tick rule state stored at the end of bar index | //+------------------------------------------------------------------+ void LoadState(const int index,CTickState &state) { state.Reset(); if(index<0) return; double price=BufEndPrice[index]; if(price>0.0) { state.has_price=true; state.last_price=price; state.last_direction=(ENUM_OF_DIRECTION)(int)MathRound(BufEndDir[index]); } } //+------------------------------------------------------------------+ //| Resizes the helper arrays and, on a full pass, resets every bar | //| to undefined with a zero running total. ComputeBars() then fills | //| the processing window. Returns false when a resize fails. | //+------------------------------------------------------------------+ bool PrepareArrays(const int rates_total,const bool full) { if(ArraySize(g_delta_def)!=rates_total) { if(ArrayResize(g_delta_def,rates_total)<0) return(false); } if(ArraySize(g_cum_def)!=rates_total) { if(ArrayResize(g_cum_def,rates_total)<0) return(false); } if(!full) return(true); //--- every bar starts undefined; the processing window is filled later for(int i=0; i<rates_total; i++) { BufHist[i]=EMPTY_VALUE; BufColor[i]=OF_COLOR_NEUTRAL; BufBear[i]=EMPTY_VALUE; BufBull[i]=EMPTY_VALUE; BufDelta[i]=EMPTY_VALUE; BufCum[i]=0.0; BufEndPrice[i]=0.0; BufEndDir[i]=0.0; g_delta_def[i]=false; g_cum_def[i]=false; } return(true); }
Reading and aggregating bars: ComputeBars()
ComputeBars() is the engine of the incremental design. It starts from the stored end state of bar start minus one, then processes each bar oldest first, chaining the state. That state is the only thing that crosses a bar boundary. Recomputing the forming bar from the stored end state of the previous bar therefore matches a full recomputation, unless an earlier bar has missing data.
A closed bar uses the next bar open as its range end. The forming bar uses its own open plus PeriodSeconds(). A fetch counts as failed when ReadBarTicks() returns -1, or when it returns 0 for a bar whose bar tick volume is positive.
The second rule is a heuristic, not proof. A positive bar tick volume tells us the bar had ticks of some type. If the selected source returns nothing for such a bar, the indicator assumes the data is missing. On a symbol with no ticks of the selected type, for example the Last source on spot forex, every bar is flagged incomplete.
The heuristic has two blind spots. A bar with zero returned ticks and a bar tick volume of zero is accepted as a genuine empty bar, although a missing download can look the same. A partial download, where CopyTicksRange() returns some ticks but not all, passes unnoticed, because the indicator has no reliable count to compare against. In both cases the bar is marked complete.
An incomplete bar stores an undefined delta and resets the carried tick rule state. The ticks that were lost may have moved the price, so the old state can no longer be trusted. The first valid tick after the gap becomes the new base price and stays unclassified, and classification resumes at the first price change. When a retry fills the gap, ComputeBars() starts again from that bar and recomputes every later bar with the restored state. The method also records why the first closed bar failed, so the log message can name the cause.
//+------------------------------------------------------------------+ //| Reads and aggregates the ticks of the bars from index start to | //| the newest bar (rates_total-1), chaining the tick rule state | //| from bar to bar. A bar whose ticks are missing resets the state, | //| so the tick rule restarts after the gap. Reports the index of | //| the first closed bar whose tick data is incomplete. | //+------------------------------------------------------------------+ void ComputeBars(const int start, const int rates_total, const datetime &time[], const long &tick_volume[], int &first_incomplete) { //--- forget the failure details of the previous pass g_failure_seen=false; //--- starting state comes from the stored end state of the previous bar CTickState state; LoadState(start-1,state); //--- process each bar once, oldest first for(int i=start; i<rates_total; i++) { datetime bar_open=time[i]; datetime next_open=(i<rates_total-1)?time[i+1]:(datetime)(time[i]+PeriodSeconds()); int copied=g_reader.ReadBarTicks(_Symbol,bar_open,next_open,InpPriceSource,g_ticks); //--- zero ticks for a bar that has a tick volume is treated as missing data (a heuristic) bool fetch_ok=(copied>=0); if(copied==0 && tick_volume[i]>0) fetch_ok=false; //--- remember why the first closed bar failed, for the log message if(!fetch_ok && i<rates_total-1 && !g_failure_seen) { g_failure_seen=true; g_failure_error=(copied<0)?g_reader.LastError():0; } CBarDelta bar; if(fetch_ok) g_aggregator.AggregateTicks(g_ticks,bar_open,InpPriceSource,InpVolumeMode,state,bar); else { //--- incomplete bar: the lost ticks may have moved the price, so the //--- carried state is unknown. Restart the tick rule after the gap. bar.Reset(); bar.bar_time=bar_open; bar.data_complete=false; state.Reset(); bar.end_state=state; } //--- store the bar g_delta_def[i]=bar.data_complete; BufDelta[i]=bar.data_complete?bar.delta:EMPTY_VALUE; BufEndPrice[i]=bar.end_state.has_price?bar.end_state.last_price:0.0; BufEndDir[i]=(double)bar.end_state.last_direction; BufBear[i]=EMPTY_VALUE; BufBull[i]=EMPTY_VALUE; //--- remember the earliest closed bar that needs a retry if(!bar.data_complete && i<rates_total-1 && first_incomplete<0) first_incomplete=i; } }
Plots and divergence
Once the numbers exist, two small functions translate them into what the chart shows. UpdatePlots() chooses the plotted series from the display mode, but always takes the color from the per-bar delta. An undefined bar gets an empty value and the neutral color. In per-bar mode, a bar with a delta of exactly zero has zero height. The neutral color is therefore visible only in cumulative mode, where the bar height is the running total.
UpdateDivergence() loops up to the second to last bar, so the forming bar is never evaluated. It skips windows that span a server midnight when the daily reset is on. A signal is drawn at the plotted value of its bar, which is the per-bar delta in per-bar mode and the running total in cumulative mode. It also skips any window that contains a bar with missing tick data. Because the tick rule restarts after a gap, bars after the gap carry no state from before it, so this window check is enough to keep a gap from distorting a signal.
//+------------------------------------------------------------------+ //| Writes histogram values and colors for the bars from index start | //| to the newest bar | //+------------------------------------------------------------------+ void UpdatePlots(const int start,const int rates_total) { for(int i=start; i<rates_total; i++) { if(g_delta_def[i]) { BufHist[i]=(InpDisplayMode==OF_DISPLAY_CUMULATIVE)?BufCum[i]:BufDelta[i]; //--- color always follows the sign of the per-bar delta BufColor[i]=g_aggregator.ColorIndexForDelta(true,BufDelta[i]); } else { BufHist[i]=EMPTY_VALUE; BufColor[i]=OF_COLOR_NEUTRAL; } } } //+------------------------------------------------------------------+ //| Evaluates divergence on closed bars only (never the last bar). | //| A bar is skipped when its lookback window contains a bar with | //| missing tick data, because the hole offsets the running total | //| inside the window. With the daily reset on, windows that span a | //| server midnight are skipped as well, because the totals on the | //| two sides of the reset have different baselines. | //+------------------------------------------------------------------+ void UpdateDivergence(const int start, const int rates_total, const datetime &time[], const double &high[], const double &low[]) { if(!InpShowDivergence) return; for(int i=start; i<=rates_total-2; i++) { if(!g_cum_def[i]) continue; //--- a window that is too short cannot be evaluated if(i<InpDivLookback) continue; //--- a window that contains a data hole has a distorted baseline bool has_hole=false; for(int j=i-InpDivLookback; j<i; j++) { if(!g_delta_def[j]) { has_hole=true; break; } } if(has_hole) continue; //--- a window that spans a reset mixes two baselines if(InpResetDaily) { if(g_aggregator.IsDifferentDay(time[i-InpDivLookback],time[i])) continue; } ENUM_OF_DIVERGENCE signal=g_detector.DetectAtBar(high,low,BufCum,g_cum_def,i,InpDivLookback); if(signal==OF_DIV_BEARISH) BufBear[i]=BufHist[i]; else if(signal==OF_DIV_BULLISH) BufBull[i]=BufHist[i]; } }
Diagnostics and incremental calculation: OnCalculate()
OnCalculate() decides how much work each call deserves. The first call computes up to InpMaxBars bars. Later calls start at prev_calculated minus one, which recomputes the forming bar. When a new bar appears, that index is the bar that just closed, so it gets one last pass with its full tick range, and the new bar follows.
When tick fetch fails, the indicator retries at most every 10 seconds and up to 6 times, starting from the earliest incomplete closed bar. This prevents endless re-reading on symbols that lack the selected tick type. ReportMissingData() prints the first failure with its error code, or a note that no ticks were returned, and prints a second message when the retries end.
The forming bar is read in full on every call, so the cost of each call grows with its tick count. The cumulative series is rebuilt from the start, which is cheap arithmetic. Every array resize and the cumulative build are checked, and the function returns 0 if one fails.
//+------------------------------------------------------------------+ //| Writes each diagnostic message once: the first failure and the | //| end of the retries | //+------------------------------------------------------------------+ void ReportMissingData(void) { if(g_retry_from<0) return; //--- first failure: say why the bar is incomplete if(!g_warned && g_failure_seen) { g_warned=true; if(g_failure_error!=0) PrintFormat("OrderFlowDelta: CopyTicksRange() failed for a closed bar (error %d). Tick history may still be synchronizing.", g_failure_error); else Print("OrderFlowDelta: no ticks of the selected price source were returned for a closed bar that has tick volume. Tick history may still be synchronizing, or this symbol has no such ticks (for example, last price on spot forex)."); } //--- retries exhausted: the bars stay empty if(!g_gave_up && g_retry_attempts>=OF_MAX_RETRIES) { g_gave_up=true; PrintFormat("OrderFlowDelta: %d retries finished and some bars still have no tick data. They stay empty until the next full recalculation or reload.", OF_MAX_RETRIES); } } //+------------------------------------------------------------------+ //| Incremental calculation: a full pass computes up to InpMaxBars | //| bars; later calls recompute the forming bar, any new bars, and | //| (at most every 10 seconds, at most OF_MAX_RETRIES times) the | //| bars whose tick fetch failed. The processing window does not | //| slide after the first full pass: new bars extend it until the | //| next full calculation. The forming bar is read in full on every | //| call, so its cost grows with its tick count. | //+------------------------------------------------------------------+ int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { if(rates_total<2) return(0); //--- the input arrays must be chronological, like the buffers if(!ArraySetAsSeries(time,false) || !ArraySetAsSeries(high,false) || !ArraySetAsSeries(low,false) || !ArraySetAsSeries(tick_volume,false)) { Print("OrderFlowDelta: the input arrays could not be set to chronological indexing."); return(0); } //--- decide where to start int first_bar=MathMax(0,rates_total-InpMaxBars); bool full=(prev_calculated<=0 || prev_calculated>rates_total); int start=first_bar; if(full) { g_retry_from=-1; g_retry_attempts=0; g_gave_up=false; } else start=MathMax(first_bar,prev_calculated-1); //--- throttled, limited retry of earlier incomplete bars if(!full && g_retry_from>=0 && g_retry_from<start && g_retry_attempts<OF_MAX_RETRIES) { ulong now_ms=GetTickCount64(); if(now_ms-g_last_retry_ms>=OF_RETRY_INTERVAL_MS) { start=MathMax(first_bar,g_retry_from); g_last_retry_ms=now_ms; g_retry_attempts++; } } int first_incomplete=-1; if(g_retry_from>=0 && g_retry_from<start) first_incomplete=g_retry_from; //--- compute if(!PrepareArrays(rates_total,full)) { Print("OrderFlowDelta: helper arrays could not be resized."); return(0); } ComputeBars(start,rates_total,time,tick_volume,first_incomplete); g_retry_from=first_incomplete; if(g_retry_from<0) { g_retry_attempts=0; g_gave_up=false; } ReportMissingData(); //--- cumulative series, plots, divergence if(!g_aggregator.BuildCumulativeSeries(BufDelta,g_delta_def,time,start,rates_total,InpResetDaily,BufCum,g_cum_def)) { Print("OrderFlowDelta: the cumulative series could not be built (array size mismatch)."); return(0); } UpdatePlots(start,rates_total); UpdateDivergence(start,rates_total,time,high,low); return(rates_total); }
Testing the Pure Logic: TestOrderFlowDelta.mq5
Tests give the pure classes a fixed reference to be measured against. The script uses synthetic ticks with known answers, so a failure always points to the logic and never to the feed. It needs no tick history and no network.
The scope is limited on purpose. The script does not test CopyTicksRange(), the incremental recalculation in OnCalculate(), LoadState(), plotting, or the retry logic. Passing it shows that the classes return the expected values for the chosen examples. It does not prove correct behavior on real feeds. The tests also confirm only that the code follows the rules stated in this article. They say nothing about whether those rules describe real aggressor behavior. Array order, buffer handling, window growth, history reloads, plotting, and the restart of the tick rule after a gap of missing data are checked by hand. The last of these was checked on a demo chart by forcing one closed bar to fail and reading the bars around it.
The script contains 61 assertions. It was run on MetaTrader 5 x64 build 6316 on Windows 11, with the MetaQuotes-Demo server, attached to an EURUSD H1 chart. The Experts tab shows these lines:
2026.11.13 12:29:20.795 Scripts script TestOrderFlowDelta (EURUSD,H1) loaded successfully 2026.11.13 12:29:20.808 TestOrderFlowDelta (EURUSD,H1) TestOrderFlowDelta: 61 passed, 0 failed. 2026.11.13 12:29:20.808 TestOrderFlowDelta (EURUSD,H1) RESULT: PASS
A different build, or a changed script, can print a different count.
An ASSERT macro forwards the line number to CheckAssert(), NearlyEqual() compares doubles with a tolerance, and MakeTick() builds an MqlTick. The first listing shows the script header and these helpers.
//+------------------------------------------------------------------+ //| TestOrderFlowDelta.mq5 | //| Verification script for the project | //+------------------------------------------------------------------+ #property version "1.00" #property description "Runs deterministic tests on the pure project classes." #include <OrderFlowDelta/OrderFlowTypes.mqh> #include <OrderFlowDelta/TickClassifier.mqh> #include <OrderFlowDelta/TickDeltaAggregator.mqh> #include <OrderFlowDelta/TickDataReader.mqh> #include <OrderFlowDelta/DivergenceDetector.mqh> int g_pass=0; int g_fail=0; #define ASSERT(condition,message) CheckAssert((condition),(message),__LINE__) //+------------------------------------------------------------------+ //| Records one check result | //+------------------------------------------------------------------+ void CheckAssert(const bool condition,const string message,const int line) { if(condition) { g_pass++; return; } g_fail++; PrintFormat("FAIL (line %d): %s",line,message); } //+------------------------------------------------------------------+ //| Compares two doubles with a tolerance | //+------------------------------------------------------------------+ bool NearlyEqual(const double first,const double second,const double tolerance=1.0e-9) { return(MathAbs(first-second)<=tolerance); } //+------------------------------------------------------------------+ //| Builds a synthetic tick | //+------------------------------------------------------------------+ MqlTick MakeTick(const double bid, const double last, const ulong volume, const double volume_real, const ulong time_msc) { MqlTick tick; ZeroMemory(tick); tick.bid=bid; tick.ask=bid; tick.last=last; tick.volume=volume; tick.volume_real=volume_real; tick.time_msc=(long)time_msc; tick.time=(datetime)(time_msc/1000); return(tick); }
Tick rule and extraction tests
TestTickRule() covers the up tick, the down tick, an unchanged tick after a buy, an unchanged tick after a sell, an unchanged tick with no direction, and the first tick. The last assertion confirms that a stale direction is ignored when no previous price exists. TestExtraction() covers both price sources, a zero price, both volume modes, and a zero volume field.
//+------------------------------------------------------------------+ //| Tick rule: up, down, unchanged, and the first tick | //+------------------------------------------------------------------+ void TestTickRule() { CTickClassifier classifier; ASSERT(classifier.ClassifyDirection(true,1.0,OF_DIR_NONE,1.1)==OF_DIR_BUY,"up tick is a buy"); ASSERT(classifier.ClassifyDirection(true,1.1,OF_DIR_NONE,1.0)==OF_DIR_SELL,"down tick is a sell"); ASSERT(classifier.ClassifyDirection(true,1.0,OF_DIR_BUY,1.0)==OF_DIR_BUY,"unchanged after buy repeats buy"); ASSERT(classifier.ClassifyDirection(true,1.0,OF_DIR_SELL,1.0)==OF_DIR_SELL,"unchanged after sell repeats sell"); ASSERT(classifier.ClassifyDirection(true,1.0,OF_DIR_NONE,1.0)==OF_DIR_NONE,"unchanged with no direction is unclassified"); ASSERT(classifier.ClassifyDirection(false,0.0,OF_DIR_NONE,1.0)==OF_DIR_NONE,"first tick is unclassified"); ASSERT(classifier.ClassifyDirection(false,0.0,OF_DIR_BUY,1.0)==OF_DIR_NONE,"no previous price ignores stale direction"); } //+------------------------------------------------------------------+ //| Price and volume extraction | //+------------------------------------------------------------------+ void TestExtraction() { CTickClassifier classifier; double value=0.0; MqlTick tick=MakeTick(1.2300,1.2345,5,0.0,1000); ASSERT(classifier.ExtractPrice(tick,OF_PRICE_LAST,value) && NearlyEqual(value,1.2345),"last price extracted"); ASSERT(classifier.ExtractPrice(tick,OF_PRICE_BID,value) && NearlyEqual(value,1.2300),"bid price extracted"); MqlTick zero_last=MakeTick(1.2300,0.0,5,0.0,1000); ASSERT(!classifier.ExtractPrice(zero_last,OF_PRICE_LAST,value) && NearlyEqual(value,0.0),"zero last price rejected"); MqlTick zero_bid=MakeTick(0.0,1.2345,5,0.0,1000); ASSERT(!classifier.ExtractPrice(zero_bid,OF_PRICE_BID,value),"zero bid price rejected"); //--- volume modes ASSERT(classifier.ExtractVolume(tick,OF_VOL_TICK_VOLUME,value) && NearlyEqual(value,5.0),"integer tick volume used"); MqlTick real_tick=MakeTick(1.0,1.0,2,2.5,1000); ASSERT(classifier.ExtractVolume(real_tick,OF_VOL_TICK_VOLUME,value) && NearlyEqual(value,2.5),"real volume preferred"); MqlTick zero_volume=MakeTick(1.0,1.0,0,0.0,1000); ASSERT(!classifier.ExtractVolume(zero_volume,OF_VOL_TICK_VOLUME,value) && NearlyEqual(value,0.0),"zero volume field reports false"); ASSERT(classifier.ExtractVolume(zero_volume,OF_VOL_TICK_COUNT,value) && NearlyEqual(value,1.0),"tick count mode returns one"); }
Aggregation, empty bars, and state carry
TestAggregation() uses six ticks with known results: buy 9, sell 6, unclassified 2, total 17, and delta 3. It checks both identities and the end state. TestEmptyArray() shows that an empty array yields a defined zero-tick bar with an undefined ratio.
TestStateCarry() targets the bar boundary. Bar B starts with a price drop from the end of bar A, so its first tick must be a sell, while a fresh state would leave those ticks unclassified. The test also checks that two chained bars equal a single pass over all ticks.
//+------------------------------------------------------------------+ //| Aggregation of one synthetic bar and its identities | //+------------------------------------------------------------------+ void TestAggregation() { CTickDeltaAggregator aggregator; MqlTick ticks[]; ArrayResize(ticks,6); ticks[0]=MakeTick(99.99,100.0,2,0.0,1000); ticks[1]=MakeTick(100.49,100.5,3,0.0,1001); ticks[2]=MakeTick(100.49,100.5,4,0.0,1002); ticks[3]=MakeTick(100.19,100.2,1,0.0,1003); ticks[4]=MakeTick(100.19,100.2,5,0.0,1004); ticks[5]=MakeTick(100.69,100.7,2,0.0,1005); CTickState state; CBarDelta bar; aggregator.AggregateTicks(ticks,1000,OF_PRICE_LAST,OF_VOL_TICK_VOLUME,state,bar); ASSERT(bar.data_complete,"bar is data complete"); ASSERT(bar.tick_count==6 && bar.classified_count==5 && bar.unclassified_count==1,"tick counts"); ASSERT(NearlyEqual(bar.buy_volume,9.0),"buy volume"); ASSERT(NearlyEqual(bar.sell_volume,6.0),"sell volume"); ASSERT(NearlyEqual(bar.unclassified_volume,2.0),"unclassified volume"); ASSERT(NearlyEqual(bar.total_volume,17.0),"total volume"); ASSERT(NearlyEqual(bar.buy_volume+bar.sell_volume+bar.unclassified_volume,bar.total_volume),"volume identity"); ASSERT(NearlyEqual(bar.delta,bar.buy_volume-bar.sell_volume) && NearlyEqual(bar.delta,3.0),"delta identity"); ASSERT(bar.delta_ratio_defined && NearlyEqual(bar.delta_ratio,3.0/17.0),"delta ratio"); ASSERT(bar.end_state.has_price && NearlyEqual(bar.end_state.last_price,100.7) && bar.end_state.last_direction==OF_DIR_BUY,"end state"); } //+------------------------------------------------------------------+ //| Empty tick array gives a defined, zero-tick, ratio-undefined bar | //+------------------------------------------------------------------+ void TestEmptyArray() { CTickDeltaAggregator aggregator; MqlTick ticks[]; ArrayResize(ticks,0); CTickState state; CBarDelta bar; aggregator.AggregateTicks(ticks,2000,OF_PRICE_LAST,OF_VOL_TICK_VOLUME,state,bar); ASSERT(bar.data_complete && bar.tick_count==0,"empty array is a defined zero-tick bar"); ASSERT(NearlyEqual(bar.delta,0.0) && NearlyEqual(bar.total_volume,0.0),"empty array has zero totals"); ASSERT(!bar.delta_ratio_defined,"empty array leaves ratio undefined"); ASSERT(!bar.end_state.has_price,"empty array leaves state empty"); } //+------------------------------------------------------------------+ //| State carry across two bars, and equality with a single pass | //+------------------------------------------------------------------+ void TestStateCarry() { CTickDeltaAggregator aggregator; MqlTick bar_a[]; MqlTick bar_b[]; MqlTick both[]; ArrayResize(bar_a,2); ArrayResize(bar_b,2); ArrayResize(both,4); bar_a[0]=MakeTick(99.9,100.0,1,0.0,1000); bar_a[1]=MakeTick(100.3,100.4,1,0.0,1001); bar_b[0]=MakeTick(100.2,100.3,2,0.0,2000); bar_b[1]=MakeTick(100.2,100.3,1,0.0,2001); both[0]=bar_a[0]; both[1]=bar_a[1]; both[2]=bar_b[0]; both[3]=bar_b[1]; CTickState state; CBarDelta first_bar; CBarDelta second_bar; aggregator.AggregateTicks(bar_a,1000,OF_PRICE_LAST,OF_VOL_TICK_VOLUME,state,first_bar); ASSERT(NearlyEqual(first_bar.end_state.last_price,100.4) && first_bar.end_state.last_direction==OF_DIR_BUY,"first bar end state"); //--- the second bar starts from the stored end state of the first CTickState carried=first_bar.end_state; aggregator.AggregateTicks(bar_b,2000,OF_PRICE_LAST,OF_VOL_TICK_VOLUME,carried,second_bar); ASSERT(NearlyEqual(second_bar.sell_volume,3.0),"first tick of bar two is classified against bar one"); ASSERT(second_bar.unclassified_count==0,"no unclassified ticks after carry"); //--- a fresh state would have lost that information CTickState fresh; CBarDelta isolated; aggregator.AggregateTicks(bar_b,2000,OF_PRICE_LAST,OF_VOL_TICK_VOLUME,fresh,isolated); ASSERT(NearlyEqual(isolated.unclassified_volume,3.0),"fresh state leaves the bar unclassified"); //--- chained bars equal one pass over all ticks CTickState single_state; CBarDelta single; aggregator.AggregateTicks(both,1000,OF_PRICE_LAST,OF_VOL_TICK_VOLUME,single_state,single); ASSERT(NearlyEqual(single.buy_volume,first_bar.buy_volume+second_bar.buy_volume),"chained buy equals single pass"); ASSERT(NearlyEqual(single.sell_volume,first_bar.sell_volume+second_bar.sell_volume),"chained sell equals single pass"); ASSERT(NearlyEqual(single.unclassified_volume,first_bar.unclassified_volume+second_bar.unclassified_volume),"chained unclassified equals single pass"); }
Range, cumulative, divergence, and color tests
TestRange() shows that adjacent bars leave no gap and no overlap, and that empty and reversed ranges are rejected. TestCumulative() uses six bars across two days with one undefined bar. It checks the running totals with and without the daily reset, the tail recomputation, and the day boundary helper.
TestDivergence() builds a bearish and a bullish scenario, then checks equal highs, equal delta, insufficient lookback, undefined data, and equal lows. TestColorIndex() checks that an exact zero delta gets the neutral index. OnStart() runs every group and prints the summary.
//+------------------------------------------------------------------+ //| Time range boundaries | //+------------------------------------------------------------------+ void TestRange() { CTickDataReader reader; ulong from_a=0,to_a=0,from_b=0,to_b=0; ASSERT(reader.BuildRange(1000,1060,from_a,to_a),"range builds"); ASSERT(reader.BuildRange(1060,1120,from_b,to_b),"next range builds"); ASSERT(from_a==1000000 && to_a==1059999,"first range bounds"); ASSERT(from_b==to_a+1,"adjacent bars leave no gap and no overlap"); ASSERT(!reader.BuildRange(1060,1060,from_a,to_a),"empty range rejected"); ASSERT(!reader.BuildRange(1060,1000,from_a,to_a),"reversed range rejected"); } //+------------------------------------------------------------------+ //| Cumulative series with an undefined bar and the daily reset | //+------------------------------------------------------------------+ void TestCumulative() { CTickDeltaAggregator aggregator; datetime base=(datetime)(86400*20); datetime times[6]; times[0]=base+3600; times[1]=base+7200; times[2]=base+10800; times[3]=base+86400+3600; times[4]=base+86400+7200; times[5]=base+86400+10800; double delta[6]= {3.0,-2.0,0.0,4.0,1.0,-1.0}; bool flags_ok[6]= {true,true,false,true,true,true}; double cumulative[6]; bool cumulative_defined[6]; //--- no reset ASSERT(aggregator.BuildCumulativeSeries(delta,flags_ok,times,0,6,false,cumulative,cumulative_defined),"cumulative builds"); ASSERT(NearlyEqual(cumulative[0],3.0) && NearlyEqual(cumulative[1],1.0),"running total on defined bars"); ASSERT(!cumulative_defined[2] && NearlyEqual(cumulative[2],1.0),"undefined bar is flagged and carries the total"); ASSERT(NearlyEqual(cumulative[3],5.0) && NearlyEqual(cumulative[4],6.0) && NearlyEqual(cumulative[5],5.0),"total continues across days without reset"); //--- daily reset aggregator.BuildCumulativeSeries(delta,flags_ok,times,0,6,true,cumulative,cumulative_defined); ASSERT(NearlyEqual(cumulative[2],1.0),"day one is unchanged by the reset"); ASSERT(NearlyEqual(cumulative[3],4.0) && NearlyEqual(cumulative[4],5.0) && NearlyEqual(cumulative[5],4.0),"total restarts on the first bar of the new day"); //--- tail recomputation equals the full pass cumulative[3]=-999.0; cumulative[4]=-999.0; cumulative[5]=-999.0; aggregator.BuildCumulativeSeries(delta,flags_ok,times,3,6,true,cumulative,cumulative_defined); ASSERT(NearlyEqual(cumulative[3],4.0) && NearlyEqual(cumulative[5],4.0),"tail recomputation matches"); ASSERT(aggregator.IsDifferentDay(times[2],times[3]) && !aggregator.IsDifferentDay(times[0],times[1]),"day boundary helper"); } //+------------------------------------------------------------------+ //| Fills the baseline arrays used by the divergence tests | //+------------------------------------------------------------------+ void FillFlat(double &high[],double &low[],double &cumulative[],bool &flags_ok[]) { ArrayResize(high,7); ArrayResize(low,7); ArrayResize(cumulative,7); ArrayResize(flags_ok,7); for(int i=0; i<7; i++) { high[i]=10.0; low[i]=5.0; cumulative[i]=0.0; flags_ok[i]=true; } } //+------------------------------------------------------------------+ //| Divergence cases | //+------------------------------------------------------------------+ void TestDivergence() { CDivergenceDetector detector; double high[],low[],cum[]; bool flags_ok[]; //--- bearish: new high, lower cumulative delta than at the previous high FillFlat(high,low,cum,flags_ok); double bear_high[7]= {9,10,12,11,11,11.5,13}; double bear_cum[7]= {0,10,50,30,20,25,40}; for(int i=0; i<7; i++) { high[i]=bear_high[i]; cum[i]=bear_cum[i]; } ASSERT(detector.DetectAtBar(high,low,cum,flags_ok,6,5)==OF_DIV_BEARISH,"bearish divergence"); //--- equal highs high[6]=12.0; ASSERT(detector.DetectAtBar(high,low,cum,flags_ok,6,5)==OF_DIV_NONE,"equal highs give no divergence"); high[6]=13.0; //--- equal delta cum[6]=50.0; ASSERT(detector.DetectAtBar(high,low,cum,flags_ok,6,5)==OF_DIV_NONE,"equal delta gives no divergence"); cum[6]=40.0; //--- insufficient lookback ASSERT(detector.DetectAtBar(high,low,cum,flags_ok,3,5)==OF_DIV_NONE,"insufficient lookback gives no divergence"); //--- undefined cumulative delta at the signal bar flags_ok[6]=false; ASSERT(detector.DetectAtBar(high,low,cum,flags_ok,6,5)==OF_DIV_NONE,"undefined data gives no divergence"); //--- bullish: new low, higher cumulative delta than at the previous low FillFlat(high,low,cum,flags_ok); double bull_low[7]= {9,8,5,6,7,6.5,4}; double bull_cum[7]= {0,-10,-50,-30,-20,-25,-30}; for(int i=0; i<7; i++) { low[i]=bull_low[i]; cum[i]=bull_cum[i]; } ASSERT(detector.DetectAtBar(high,low,cum,flags_ok,6,5)==OF_DIV_BULLISH,"bullish divergence"); low[6]=5.0; ASSERT(detector.DetectAtBar(high,low,cum,flags_ok,6,5)==OF_DIV_NONE,"equal lows give no divergence"); } //+------------------------------------------------------------------+ //| Color index mapping, including the exact zero case | //+------------------------------------------------------------------+ void TestColorIndex() { CTickDeltaAggregator aggregator; ASSERT(aggregator.ColorIndexForDelta(true,5.0)==OF_COLOR_POSITIVE,"positive delta is green"); ASSERT(aggregator.ColorIndexForDelta(true,-5.0)==OF_COLOR_NEGATIVE,"negative delta is red"); ASSERT(aggregator.ColorIndexForDelta(true,0.0)==OF_COLOR_NEUTRAL,"exact zero delta is neutral"); ASSERT(aggregator.ColorIndexForDelta(false,5.0)==OF_COLOR_NEUTRAL,"undefined delta is neutral"); } //+------------------------------------------------------------------+ //| Script entry point | //+------------------------------------------------------------------+ void OnStart() { g_pass=0; g_fail=0; TestTickRule(); TestExtraction(); TestAggregation(); TestEmptyArray(); TestStateCarry(); TestRange(); TestCumulative(); TestDivergence(); TestColorIndex(); PrintFormat("TestOrderFlowDelta: %d passed, %d failed.",g_pass,g_fail); if(g_fail==0) Print("RESULT: PASS"); else Print("RESULT: FAIL"); }
Interpreting the Chart
This section shows the indicator running on a live XAUUSD H1 chart and explains how to read what it draws. Three screenshots cover the three things a reader needs to recognize: the cumulative view, the per-bar view with divergence arrows, and the two views side by side. The screenshots show how the output looks, not how well it predicts. The chart cannot show whether a signal was right.
All screenshots and table values come from a demo account on the MetaQuotes-Demo server, on XAUUSD H1 and H4 charts, captured on 7 October 2026 in server time. The indicator used the Bid source, tick count mode, the default InpMaxBars of 500, a divergence lookback of 20, and no daily reset. Each cumulative total counts from the first bar of the last full calculation on its chart, which lies to the left of the visible bars. The numbers will differ on another feed, another start point, or another history depth.
Reading the cumulative histogram
Figure 2 shows the indicator in cumulative mode. The sub-window title confirms the settings: Bid source, tick count PROXY, cumulative. Each bar height is the running total of per-bar delta, and each bar color is the sign of that bar's own delta. A tall green bar therefore means that the total is high, and that the latest bar had more upward than downward bid updates.
Cumulative delta on an H1 chart

Figure 2 — Cumulative delta on an H1 chart: The sub-window plots the running total of per-bar delta, with green bars where upward bid updates exceeded downward updates, and red bars for the opposite.
The shape of the histogram carries the information. The total climbs through the rally, flattens near the price high, and then falls steadily as price declines. In this chart, pressure and price moved together, which is the ordinary case. The final bar is red while its candle is green. That bar is still forming, so its delta can change until the hour closes.
Read the shape and not the level. The running total starts at zero at the first bar of the last full calculation, so its absolute value depends on how many bars that calculation loaded and how many bars have arrived since. The vertical axis here spans roughly 298,000 to 314,000 and does not include zero. Compare slopes and turning points, not heights against zero.
Reading per-bar delta and divergence arrows
Figure 3 shows per-bar mode, where each bar height is the delta of one hour. Bars above the zero line had more upward than downward bid updates, and bars below it had the opposite. Magenta down arrows mark bearish divergences, and cyan up arrows mark bullish divergences.
Per-bar delta with divergence arrows

Figure 3 — Per-bar delta with divergence arrows.
Two points matter when reading the arrows. First, the arrows sit at the plotted value of their bar, which is the per-bar delta in this mode. Their height says nothing about the divergence itself, only which bar produced it. Second, the signal is always computed from cumulative delta, even when the histogram shows per-bar delta. This screenshot does not show the cumulative series, so it cannot confirm the rule by itself. The arrows do sit on bars where price reaches a new high or a new low, which is the first half of the rule.
To check a specific arrow, switch the display mode to cumulative and compare the total at the signal bar with the total at the extreme bar it refers to. Also remember that an arrow appears only after its bar closes, and that a late tick history update can change it.
Comparing the two views
Figure 4 puts both display modes on one chart, with the per-bar window above the cumulative window. This is the best way to learn the relationship between the two series.
Per-bar and cumulative delta on the same chart

Figure 4 — Per-bar and cumulative delta on the same chart. The upper sub-window shows the delta of each hour, and the lower sub-window shows the running total. Runs of green bars in the upper window lift the lower window, and runs of red bars bring it down.
A run of green bars in the upper window lifts the lower window, and a run of red bars lowers it. The colors follow the same rule in both windows, so the two views agree on direction while differing in height. Near the right edge, price falls sharply while the per-bar bars turn mostly red, and the cumulative total falls with them. A single large per-bar bar can look dramatic in the upper window and still move the lower window only slightly, because the running total is large.
Reading the scale on higher timeframes
In tick count mode, delta is a count of ticks, so its size grows with the number of ticks in the bar. Hover the mouse over any bar, and the Data Window shows that bar's values for every plot.
Two delta values appear for each bar. The per-bar delta is the buy count minus the sell count of that one bar. The cumulative delta is the running total through that bar. Both Data Window rows carry the plot name Delta, so use the window number to tell them apart. Indicator window 1 is the cumulative window, and Indicator window 2 is the per-bar window.
The table lists five bars read this way from an XAUUSD demo chart. The share column divides the size of the per-bar delta by the bar tick volume.
| Timeframe | Bar (server time) | Bar tick volume | Cumulative delta | Per-bar delta | Per-bar delta as a share of bar tick volume |
|---|---|---|---|---|---|
| H1 | 5 Oct 01:00 | 5,606 | 304,970 | +638 | about 11% |
| H1 | 7 Oct 03:00 | 12,543 | 311,200 | -1,098 | about 9% |
| H4 | 16 Sep 20:00 | 111,789 | 131,052 | +15,692 | about 14% |
| H4 | 22 Sep 16:00 | 124,410 | 196,531 | +9,353 | about 8% |
| H4 | 28 Sep 16:00 | 126,431 | 204,350 | +228 | about 0.2% |
Three points stand out:
- Scale follows tick count: The H1 bars hold 5,606 and 12,543 ticks, and their per-bar deltas are in the hundreds to just over a thousand. The H4 bars hold more than 110,000 ticks each, so an imbalance of 8% to 14% already reaches five figures.
- The share varies on the same timeframe: The H4 bar of 28 September is nearly balanced at about 0.2%, while the H4 bar of 16 September leans about 14% toward upward bid updates. The share is a better basis for comparison than the raw delta. It is rough, because the bar tick volume counts every tick, while the indicator counts only the ticks it classifies.
- The cumulative level depends on where the total starts: It begins at zero at the first bar of the last full calculation, so a value near 300,000 on H1 cannot be compared with a value near 200,000 on H4. Compare slopes and turning points within one chart.
The Data Window also confirms divergence arrows. When a bar carries an arrow, the matching Bullish divergence or Bearish divergence row shows the plotted histogram value of that bar. Otherwise, the row is blank. Here, the bars of 5 October (H1), 28 September (H4), and 16 September (H4) carry bullish arrows, and the other two carry none.
Five hand-read bars are an illustration, not a statistical sample. Raw delta magnitudes are not comparable across timeframes or symbols. Compare signs and relative bar sizes within one chart, or divide the delta by the bar total yourself. CBarDelta stores delta_ratio, but the indicator does not plot it.
Extending the Indicator
The structure leaves room for several upgrades without touching the divergence detector. The most useful one is flag-based classification, which also allows a stricter Bid mode, followed by a normalized view and some performance work.
With flag-based classification, a tick that carries TICK_FLAG_BUY or TICK_FLAG_SELL would bypass ClassifyDirection(), and the tick rule would remain the fallback. A stricter Bid mode would also ignore ticks whose flags do not include TICK_FLAG_BID, so that ask-only updates are not counted. Only CTickClassifier and the aggregator loop would change.
A normalized view would plot delta_ratio, which makes bars comparable across timeframes. A volume threshold could ignore very small bars. A stored tick cache could keep the retry logic from re-reading old bars.
Limitations and Design Tradeoffs
Delta from tick count mode is a proxy, because it counts quote updates and not traded volume. The Bid source is weaker than the Last source, and ask-only updates repeat the previous direction. Results depend on the depth and quality of the broker tick history, and the missing-data check is a heuristic. It catches only an empty result for a bar that has tick volume. It cannot detect an empty bar with zero tick volume or a partial download. The indicator says nothing about spread, liquidity, or hidden orders. The Bid source supports no conclusion about buyers or sellers. It describes only the direction of quote changes. The numbers in the screenshots depend on the broker feed and on the first bar of the calculation, so they illustrate the output and cannot be reproduced exactly on another terminal.
Divergence is a context signal, not a timing signal. It can persist for many bars before price reacts, or it may never lead to a reversal. Closed-bar evaluation delays signals by one bar, late tick data can change earlier arrows, and data holes offset later cumulative values. The daily reset follows the server calendar day. The first tick of the first processed bar has no earlier price, and the same is true for the first bar after a gap of missing data, where the indicator restarts the tick rule. In both places, that tick and any later ticks before the first price change fall into the unclassified bucket. Every other tick is classified normally.
The first pass makes one CopyTicksRange() call per bar, and the forming bar is read in full on every call. Very large windows or very busy bars can therefore slow the terminal. The retries are capped at six passes. The test script covers the pure logic only, so check the numbers against real ticks before relying on them.
Conclusion
Delta turns a stream of ticks into an estimate of pressure, and this project shows that the statement can be computed cleanly inside MetaTrader 5. Three habits carry the design: keep the terminal at the edge, carry state explicitly, and never plot a missing value as zero. Together they produce an indicator that recalculates only what changed, plots gaps as gaps, and can be tested without a single real tick.
The output deserves the same discipline from the person reading it. The tick rule is an inference, tick count mode is a proxy, and a divergence is an invitation to look closer, not a reason to act. Test the indicator on the symbols and timeframes you trade, compare the Last and Bid sources where both exist, and verify a few bars by hand. Then extend it, and let the evidence decide how much weight the signal earns.
Programs used in the article:
| # | Name | Type | Description |
|---|---|---|---|
| 1 | OrderFlowTypes.mqh | Include File | This file defines the enums, color constants, CTickState, and CBarDelta used by every other component. |
| 2 | TickClassifier.mqh | Include File | This file applies the tick rule and extracts price and volume from a tick. |
| 3 | TickDeltaAggregator.mqh | Include File | This file aggregates ticks into per-bar delta, builds the cumulative series, and maps delta to a color index. |
| 4 | TickDataReader.mqh | Include File | This file wraps CopyTicksRange() and builds the millisecond range for one bar. |
| 5 | DivergenceDetector.mqh | Include File | This file detects bearish and bullish divergence between price and cumulative delta. |
| 6 | OrderFlowDelta.mq5 | Custom Indicator | This indicator plots per-bar or cumulative delta in a sub-window and marks divergences with arrows. |
| 7 | TestOrderFlowDelta.mq5 | Script | This script tests the pure classes with synthetic ticks and prints a pass and fail summary. |
| 8 | OrderFlowDelta.zip | Zip Archive | Zip archive containing all the attached files and their paths relative to the terminal's root folder. |
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.