# MQL5 # Article-490717-Dijkstra-Algorithim-Applied-In-Trading This repository is an article-derived reference project based on the original MQL5 article. It does not claim to reproduce the full original source code unless files are explicitly attached. ## Overview This project documents an experimental MQL5 trading system that applies **Dijkstra's shortest-path algorithm** to financial market structure. Instead of treating price action as a series of isolated candles, the system models the market as a graph where swing highs and swing lows become nodes and price distances between those nodes become weighted connections. The Expert Advisor automatically: * Detects swing highs and swing lows * Builds a graph of market structure * Assigns edge weights using price distance * Applies Dijkstra's shortest-path algorithm * Identifies the most probable next swing target * Generates buy or sell signals from the resulting path * Calculates stop loss and take profit levels using node distances * Visualizes swings and shortest-path relationships directly on the chart * Filters invalidated swing points and removes obsolete market structure The project demonstrates how graph theory concepts can be adapted to price-action trading and market structure analysis within MetaTrader 5. --- ## Original Article **Article ID:** 490717 **Author:** Hlomohang John Borotho **Publication Date:** 2025.07.09 **Category:** Experts **URL:** https://www.mql5.com/en/articles/18760 --- ## Repository Purpose This repository should be treated as a reference or reconstruction project derived from the article content. Its purpose is to: * Study practical applications of graph theory in trading * Explore Dijkstra's shortest-path algorithm within financial markets * Demonstrate market structure modeling using swing highs and lows * Provide a foundation for advanced pathfinding-based Expert Advisors * Serve as a framework for future liquidity and structure-based trading systems --- ## Key Concepts ### Graph Representation of Market Structure The market is modeled as a graph consisting of: * Swing highs * Swing lows * Connections between swings * Weighted paths representing movement costs ### Swing Points as Nodes Every valid swing high or swing low becomes a graph node. Each node contains: * Bar index * Timestamp * Price level * Swing type (high or low) * Distance from source node * Previous node reference * Visited state * Usage state ### Edge Weights The weight between two nodes is calculated using the absolute price difference: ```text Weight = |Price(Node A) - Price(Node B)| ``` This represents the cost required for price to travel between two structural points. ### Source Node The algorithm begins from the selected starting node, which can be: * The earliest detected swing * The most recent valid swing * A user-defined structure point ### Visited Nodes Once a node has been processed by Dijkstra's algorithm, it is marked as visited and excluded from future shortest-path calculations. ### Distance Table Each node maintains a cumulative distance value representing the lowest known cost from the source node. --- ## Algorithm / Architecture Summary ### 1. Swing Detection The EA scans historical candles and identifies: * Swing highs * Swing lows using configurable left and right bar lookback periods. ### 2. Node Construction Each detected swing is converted into a graph node. Node attributes include: * Price * Time * Index * Distance * Previous node * Visited status ### 3. Swing Validation Detected swings are validated by checking whether future price action has already passed through them. Invalid swings are discarded. Valid swings remain available for graph analysis. ### 4. Graph Creation A graph is formed where: * Nodes = Swing highs and lows * Edges = Price relationships between nodes * Weights = Price distance between nodes ### 5. Dijkstra Processing The algorithm: 1. Starts from the source node 2. Finds the nearest unvisited node 3. Updates neighboring node distances 4. Records shortest paths 5. Marks processed nodes as visited This continues until all reachable nodes have been processed. ### 6. Path Reconstruction Using the `previous` node references, the EA reconstructs the shortest path through market structure. ### 7. Signal Generation Trading signals are generated using the relationship between connected nodes. #### Buy Signal ```text Next Node Price > Current Node Price ``` #### Sell Signal ```text Next Node Price < Current Node Price ``` ### 8. Risk Management Stop Loss and Take Profit are calculated from node distances. ```text Distance = |Current Node - Previous Node| ``` A configurable point buffer can be added. ### 9. Trade Execution Orders are executed using the MQL5 `CTrade` class. Supported functionality: * Buy orders * Sell orders * Stop loss placement * Take profit placement * Position management ### 10. Visualization The EA draws: * Swing highs * Swing lows * Dijkstra path connections * Valid structure levels directly on the chart. ### 11. Cleanup Old swing objects are automatically removed to prevent chart clutter. --- ## Dijkstra Interpretation in Trading | Dijkstra Term | Trading Interpretation | | -------------- | ------------------------------------------------ | | Graph | Market structure built from swing highs and lows | | Node | Swing high or swing low | | Edge | Price relationship between swings | | Weight | Price distance between swings | | Source Node | Starting swing point | | Visited Set | Processed or invalidated swings | | Distance Table | Lowest-cost route through market structure | | Shortest Path | Most probable route price may follow | --- ## Mentioned or Attached Files ### Primary Components * Dijkstra Swing EA.mq5 * README.md ### Possible Future Components * DijkstraVisualizer * SwingDetector * GraphBuilder * LiquidityEngine * RiskManager --- ## Statistics ### Trading Components * Swing Detection Module: 1 * Graph Construction Module: 1 * Dijkstra Engine: 1 * Signal Generator: 1 * Visualization Module: 1 * Trade Execution Module: 1 ### Market Structure Features * Swing High Detection * Swing Low Detection * Node Validation * Pathfinding * Structure Visualization * Dynamic SL/TP ### Algorithm Complexity Dijkstra Complexity: ```text O(V²) ``` where: ```text V = Number of swing nodes ``` --- ## Tags MQL5, MetaTrader5, Graph-Theory, Dijkstra, Swing-Trading, Price-Action, Market-Structure, Expert-Advisor, Algorithmic-Trading, Pathfinding, Quantitative-Finance --- ## Difficulty Moderate Requires familiarity with: * MQL5 Expert Advisor development * Market structure concepts * Swing high and swing low analysis * Graph theory fundamentals * Dijkstra's shortest-path algorithm * Risk management * Trade execution using CTrade --- ## Limitations * Price distance alone may not fully represent market behavior. * Dijkstra's algorithm assumes static edge weights. * Liquidity, volume, and volatility are not incorporated unless explicitly added. * Swing quality depends on the chosen lookback parameters. * The shortest path does not guarantee future price movement. * Performance may decrease when processing large numbers of nodes. --- ## Future Improvements Potential enhancements include: * ATR-adjusted edge weights * Liquidity-based weighting * Volume profile integration * Multi-timeframe graph construction * A* search implementation * Dynamic graph updates * Reinforcement learning assisted node selection * Order block and fair value gap nodes * Market regime detection * Probabilistic path scoring --- ## Reference Original MQL5 article: https://www.mql5.com/en/articles/18760 Related Concepts: * Dijkstra's Shortest Path Algorithm * Graph Theory * Market Structure Trading * Swing High and Swing Low Analysis * Pathfinding Algorithms * Algorithmic Trading MQL5 Algo Forge / [johnhlomohang](https://www.mql5.com/en/users/johnhlomohang)