K-Means Clustering
K-means answers a question that comes up constantly once you start looking at market data quantitatively: given a pile of numeric readings, which ones behave like each other? Feed it pairs of, say, average-true-range and hourly return and it will find the volatility/direction regimes in the data instead of you guessing three fixed bands and hoping they hold up out of sample. Most from-scratch implementations get two things wrong. The first is data shape: neither MQL4 nor MQL5 allows more than the first dimension of a multi- dimensional array to be dynamic, so a genuine double[][] locks the dimension count in at compile time on both platforms. This header stores points in a single flat double[] instead, point p and dimension d at index p*dims+d, so the number of dimensions is a runtime parameter like everything else. The second is centroid seeding. The textbook algorithm starts from k random points, which means the same dataset can cluster differently every time you run it - exactly the kind of nondeterminism that makes a bug impossible to reproduce. This header seeds centroids deterministically instead: the first centroid is point zero, and each subsequent centroid is whichever point is currently farthest from every centroid already chosen. It is a well known technique (the deterministic relative of k-means++) that both removes the run-to-run randomness and tends to avoid the empty-cluster and slow- convergence failures that naive random init is famous for. Convergence is Lloyd's algorithm: assign every point to its nearest centroid, move each centroid to the mean of its assigned points, repeat until no centroid moves more than a tolerance or an iteration cap is hit. An empty cluster - one nobody was assigned to on a given pass - keeps its previous centroid rather than collapsing to the origin, so it has a fair chance to pick up points on the next pass instead of vanishing outright. Notes and limitations - Data must be a flat array: point p, dimension d lives at data[p*dims+d]. Passing a genuine 2-D array will compile but read the wrong values. - Distances are plain Euclidean. Features on very different scales (say, price in the thousands next to an oscillator in 0..100) should be normalised by the caller before fitting, or the larger-scale feature will dominate every distance calculation. - Farthest-point seeding is deterministic given the data, not given a random seed - the same dataset always produces the same starting centroids and, almost always, the same final clustering. - No standard way to choose k is built in. Run KMeansFit across a small range of k and inspect KMeansInertia yourself, as the demo does. - Pure computation, no chart or trade calls - safe to call from an indicator, script or expert with no side effects, on either platform.
Script · MT5 · v1.0 · Free
About K-Means Clustering
K-Means Clustering is a script for MetaTrader 5. It has 2 settings, such as Cluster count and Max iterations. MQL source code included.
Files in the download: KMeans.mq5.mqh, KMeans.txt, KMeansDemo.ex5, KMeansDemo.mq5.
Settings
| Setting | Default | What it does |
|---|---|---|
| Cluster count | 3 | k for the main clustering pass |
| Max iterations | 100 | cap on Lloyd's algorithm iterations |
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: Trading Sessions · MT5 Script · MQL5 Source Code