Skip to content
All library documents

Implementing Parallel K-Means Clustering in MQL5 with OpenCL

Article MQL5 articles

Summary

The article describes implementing k-means clustering in MQL5, using OpenCL to parallelize computations. It motivates a native implementation for cases where Python integration limits access to terminal data, indicators, or event handling, or when clustering results need to be used by other MQL5 programs. The algorithm repeatedly assigns each sample to its nearest center and updates the centers to the arithmetic means of their assigned samples until assignments stop changing.

The implementation divides the work into kernels for calculating squared distances, selecting the closest center and flagging changed assignments, updating centers, and evaluating model loss. The article explains which operations can run independently across sample states, clusters, and vector dimensions. It reports that testing identified about 500 patterns and produced a result similar to a Python implementation, which the author treats as evidence that the algorithm was reproduced correctly. This is an implementation demonstration rather than evidence that the clusters predict market behavior or improve trading performance; practical use of the results is left for later discussion.

Key ideas

  • K-means alternates between assigning observations to the nearest center and recalculating centers as cluster means.
  • Squared Euclidean distances are sufficient for comparing candidate centers, so square roots can be omitted.
  • OpenCL can parallelize distance calculations across observations and clusters.
  • Cluster assignment changes can indicate when the iterative training loop has converged.
  • Matching a Python implementation supports algorithmic consistency but does not establish trading value.

Tags

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.