Rolling Median Filter
A moving median is a genuinely different smoother from a moving average: instead of averaging every price in the window, it reports the middle value once the window is sorted. That makes it immune to a single outlier bar - one wild spike or a bad tick pushes an ordinary average, but it barely moves a median, since one value out of many is still just one value away from the middle. The naive way to compute a rolling median is to sort the whole window from scratch at every single bar - correct, but wasteful, since only one price actually changes between one bar's window and the next one's. This implementation instead keeps a running sorted copy of the current window and, moving forward one bar at a time, removes the one price leaving the window and inserts the one price entering it, both located with a binary search into the already-sorted array rather than a fresh full sort. The full O(n log n) sort only happens once, to build the very first window; every step after that is a targeted remove-and-insert. The median itself is read straight off the middle of the maintained sorted array - the value at the centre for an odd window, or the average of the two centre values for an even one. Notes and limitations - Not recursive and never repaints - each bar's median depends only on that bar's own fixed window of past prices. - Needs InpPeriod bars of history before it starts plotting. - The remove/insert step is O(n) worst case per bar because the underlying array still needs to shift elements after the binary search locates the position - the saving over the naive approach is dropping the O(n log n) sort cost on every bar, not achieving a theoretical O(log n) update (which needs a balanced tree or skip list, deliberately not used here to keep the implementation self-contained and auditable in plain MQL4).
Indicator · MT4 · v1.0 · Free
About Rolling Median Filter
Rolling Median Filter is an indicator for MetaTrader 4. It has 2 settings, such as Period and Applied price. MQL source code included.
Files in the download: RollingMedianFilter.mq4, RollingMedianFilter.txt.
Settings
| Setting | Default | What it does |
|---|---|---|
| Period | 21 | Window size (odd values give a clean single-price median) |
| Applied price | PRICE_CLOSE | Applied price |
How to install
- Download the ZIP from your PolyMaria library and unzip it.
- In MetaTrader 4 open File → Open Data Folder, then go to MQL4 → Indicators.
- Copy the .mq4 file(s) there. Put any .mqh files in MQL4 → Include.
- Open the .mq4 file in MetaEditor and press Compile (F7) if MetaTrader does not show it.
- Drag the indicator from the Navigator onto a chart and adjust the settings.
Tags: Moving Average · MT4 Indicator · MQL4 Source Code