Binary Heap Priority Queue
The naive way to always process "whatever is most urgent right now" is to keep a plain array and re-scan it for the minimum every time - O(n) per lookup, and O(n) again if you then remove it and want the array to stay contiguous. That is fine for a handful of items and quietly expensive once a strategy is scheduling dozens of pending timers, staged orders or news events at once. A binary heap keeps the minimum at the root at all times, in an implicit tree stored flat in an array (child i lives at 2i+1 and 2i+2 - no pointers, no allocation per node). Push places a new item at the end and sifts it up; Pop swaps the last item into the root and sifts it down. Both are O(log n), and the backing array doubles on overflow rather than growing by one slot per Push, so amortised Push cost stays O(1) rather than degrading into repeated one-element resizes. This is a min-heap: the lowest priority value comes out first, which matches "smallest number of seconds until due" or "nearest price to trigger" directly. Using it as a max-heap instead needs no second class - push with the priority negated and negate the popped value back, a one-line convention documented in the demo, rather than a near-duplicate CBinaryHeapMax shipped just to flip one comparison. Notes and limitations - payload is a long, sized for a ticket number, an array index or any other integer identifier - not a struct or object. Store the identifier and look the full record up elsewhere if the payload needs to carry more than one value. - This is a min-heap. Popping in descending-priority order needs the negate convention shown in the demo, not a different function. - Not thread-safe in any sense that matters in either platform's single-threaded-per-chart execution model, but also not safe to mutate from inside a callback that is itself running as a result of a Pop on the same instance. - Clear() resets the count but leaves the backing array's capacity as-is, so a heap that once grew large keeps that memory reserved for reuse rather than releasing it immediately.
Script · MT5 · v1.0 · Free
About Binary Heap Priority Queue
Binary Heap Priority Queue is a script for MetaTrader 5. MQL source code included.
Files in the download: BinaryHeap.mq5.mqh, BinaryHeap.txt, BinaryHeapDemo.ex5, BinaryHeapDemo.mq5.
How to install
- Download the ZIP from your PolyMaria library and unzip it.
- In MetaTrader 5 open File → Open Data Folder, then go to MQL5 → Scripts.
- Copy the .mq5 file(s) there. Put any .mqh files in MQL5 → Include.
- Open the .mq5 file in MetaEditor and press Compile (F7) if MetaTrader does not show it.
- Drag the script onto a chart to run it once.
Tags: News Trading · Binary Options · MT5 Script · MQL5 Source Code