Institutional-level Tangle Theory EA Development Document (MT4 Simulated Trading Version) ## 1. Project Overview - Goal: Build a simulated trading system based on the Tangle Theory structure on the MT4 platform with risk control and visualization capabilities. The EA only simulates real trading logic on the chart and does not send real orders. - Features: - De-indexed, completely based on price structure. - Supports multi-cycle structure recognition (such as H4 + H1) and prevents center drift. - Introduce governance mechanisms such as winning rate, profit-loss ratio, transaction frequency, and central health score. - Display structural information through graphical objects, including premium/discount areas, liquidity sweep areas, and stop-profit and stop-loss indicators. - All trading actions are only recorded as simulations (drawings, logs), and OrderSend is not called. ## 2. Core Concepts and Key Points### 2.1 The structural principles of the entangling theory - the structure identification process of type → pen → center, based on the confirmed K-line (avoid drifting). - Multi-level anchoring: lower-level centers need to be attached to upper-level centers to prevent cross-level drift. - Trend judgment: Confirm the main direction through HH/HL or LL/LH combination. ### 2.2 Anti-drift mechanism - only use closed K lines to calculate the type. - The pen and hub are locked immediately once confirmed and no retroactive modification is allowed. - Distinguish between historical segments and real-time segments; real-time segments are only used for early warning and are not included in structure confirmation. ### 2.3 Three core parameters - Win Rate: The success rate of statistical center breakthrough to achieve the goal. - Profit/loss ratio (R/R): The ratio of the target distance to the stop loss distance (based on the order flow sweep area). - Trade Frequency: The number of valid signals per unit time, dynamically adjusted according to the central rhythm. ### 2.4 Center Health Score [ \text{Score} = \frac{\text{Win Rate} \times \text{Profit and Loss Ratio}}{\text{Frequency}} \times \text{Stability Coefficient} ] - The stability coefficient combines factors such as the center duration, transaction density, and coordination of upper- and lower-level structures. - When the Score falls below the threshold, shrink the strategy, reduce the position, or suspend trading. ### 2.5 Stop loss in order flow sweep area - Stop loss is placed outside the liquidity sweep area, not at the bare high/low. - Cleaning area identification: Liquid accumulation near the extreme value of the previous structure + extending outward by 3~5 points. - Avoid false breakout loss sweeps and only trigger when real order flow fails. ## 3. Visualization requirements ### 3.1 Premium area/discount area - Definition: - Premium area: the area above the center (prompts that the price is high). - Discount area: the area below the center (prompts that the price is low). - Display: - Use OBJ_RECTANGLE to draw translucent color blocks. - Recommended colors: light red for the premium area, light green for the discount area. - After the center is locked, the area is fixed and does not fluctuate with the price. ### 3.2 Liquidity Sweeping Area + Take Profit and Stop Loss - Draw a narrow rectangle or horizontal bar (available blue-violet/orange) in the sweeping area. - The stop loss and take profit levels of the current simulated transaction are deepened or framed in this area. - Can be used with OBJ_ARROW and OBJ_TEXT to mark "SL"/"TP". ## 4. System module division 1. Data management module - Use iOpen/iHigh/iLow/iClose/iTime and iVolume to cache multi-cycle data. - Manage historical segment and real-time segment data structures. 2. Structure Recognition Module - Type recognition → Pen generation → Center detection and locking. - Multi-cycle anchoring to ensure that subordinate structures are constrained by superior ones. 3. Signal filtering module - Trend judgment (HH/HL, LL/LH). - Central breakthrough + retracement confirmation, combined with tick volume to filter out false signals. 4. Risk Control Module - Calculate stop loss position based on sweep area. - Estimated positions (only used for simulation statistics, not real orders). - Continuous loss/retracement threshold triggers frequency reduction or pause. 5. Execute Simulation Module - Generate a virtual order record structure and save the entry price/SL/TP. - Draw premium area, discount area, sweep area and SL/TP mark. - Do not call OrderSend, only reflect transactions in charts and logs. - Use Print and FileOpen to output simulated trading results. 6. Performance and Adaptive Module - Real-time statistics of winning rate, profit-loss ratio, frequency and calculation of Score. - Automatically adjust strategy activation status or recommended positions when Score decreases. - Record the structural text, Score, and risk parameters of each simulated transaction. ## 5. Data and tool preparation - market data: MT4 comes with multi-period OHLC and tick volume. - Graphic drawing: using MT4 graphic object API (ObjectCreate, etc.). - Log output: Print, FileOpen (CSV/text) for review. - Parameter configuration: color, transparency, Score threshold, risk threshold, etc. require external input. ## 6. Key verification matters - the effectiveness and visualization accuracy of the cleaning area algorithm in historical data. - Stability of multi-cycle synchronization and central anchoring logic. - The adaptability of Score threshold and frequency reduction rules in different market environments. - Cleanup strategy for graphics objects to prevent chart accumulation. - Simulate the rationality of slippage and handling fee assumptions (affecting winning rate and profit-loss ratio statistics). ## 7. Development milestone suggestions 1. Structural logic verification: Verify typing, pen, and hub identification and visualization on historical data. 2. Signal and Risk Module: Realizes stop loss in cleaning area, drawing of premium/discount area and Score calculation, and detects retracement structure in discount area/premium area, triggering color enhancement or prompt information. 3. Execute Simulation: Build virtual order management, graphic annotation and log output. 4. Strategic Governance: Complete the joint control of winning rate, profit-loss ratio, frequency, and Score. 5. Testing and iteration: Simulate operations on multiple varieties and different cycles, and optimize parameters. ## 8. Current EA implementation details (chan_structure_sim.mq4) ### 8.1 Global architecture - Time-driven: Use CheckNewBar() in OnTick() to identify the new K-line of the main cycle, and only update the structure after closing to ensure no drifting. - Data structure: All use dynamic arrays (g_fractals/g_pens/g_zhongshus/g_trades) to store historical data and limit the maximum capacity (InpMaxRecords). - Module process: 1. ProcessPrimary(): Refresh parting, pen, center → drawing → update simulated transaction. 2. UpdateSimulation(): detect premium/discount trigger → generate/close simulated order → refresh overlay information panel. 3. UpdateTradePanel(): Summarizes current positions, structural status, and multi-period trends, and pushes them to the upper right/lower left corner of the chart to overlay text. ### 8.2 Visual elements - Central body: gray rectangular frame (foreground layer) + solid line and lower edge + dotted midline, label ZS #number is placed on the upper edge of the center. - Premium/Discount Block: - Use ColorWithAlpha() to generate a translucent color block. By default, the background is not laid to avoid blocking the K-line. - The upper rectangle is labeled "Premium" and the lower rectangle is labeled "Discount", and a 2-pixel dotted warning line is drawn at the same time. - HighlightDiscountRetest() adds text prompts and bright rectangles when stepping back to the discount area. - In Progress Hub: If not locked, draw a dotted rectangle with label ZS(dev) / ZS(fb) through DrawDevelopingZone(). - Synchronized Line: Read the H1 pivot key price on the M15 chart (via global variables) and draw a horizontal line for cross-cycle reference. - Overlay text: - TRADE_OVERLAY (font size 7) in the upper right corner: displays simulated positions in transit, order flow benchmarks and profit and loss tips. - STRUCT_OVERLAY (font size 9) in the lower left corner: displays HH/HL status, trend description, multi-period interval and risk control suggestions. - Text color automatically matches the chart theme (foreground color or background brightness). ### 8.3 Simulated trading logic - Trigger condition: - Closing price in the discount zone → simulate long order (OpenSimTrade(..., true, ...)). - The closing price in the premium zone → simulates a short order. - Only one open position is allowed per pivot in the same direction (to prevent duplication through FindOpenTradeIndex()). - Position and risk control: - Default lot size InpSimLots (currently fixed at 0.01), stop loss level = zone.zd - pad / zone.zg + pad, and take profit is 1:2 expansion. - The closing signal is based on the high and low of the next completed candlestick touching SL/TP. - The results are written to CSV through WriteLog() to facilitate subsequent review. - Overlay display: UpdateTradePanel() is responsible for generating panel text, updating global variables, and calling UpdateTradeOverlayText() and UpdateStructureOverlayText(). ### 8.4 Multi-period trend panel - ComputeTrendInfo() collects and types the specified period → generates a pen → searches for the nearest center (or fallback interval). - Output fields: high and low point status (HH/HL/LH/LL), trend text, range price, stop loss recommendation, RR prompt. - AppendTrendPanelLine() forms a single-line summary in the shape of H1 HH/HL Uplink Area [xxx-xxx] SLxxx/xxx RR Stable in the lower left corner panel. ### 8.5 Logs and files - PrepareLog() creates yyyy.mm.dd_hh.mm_chan_sim_log.csv and writes the time, type and details. - WriteLog() is called to record each position opening/closing/discount prompt. - CloseLog() closes and cleans up the handle in OnDeinit(). ### 8.6 Cleanup strategy - CleanupObjects() / ClearDevelopingZoneObjects() Remove old objects before redrawing (based on OBJ_PREFIX). - TrimFractals/Pens/Zhongshus/Trades() controls the length of history records to prevent memory expansion. - OnDeinit() clears the array, text overlay, and file handle to ensure a clean environment when the EA is mounted again. ### 8.7 Configurable parameters - InpPrimaryTF/InphigherTF: primary and superior time frames. - InpFractalDepth: K number left and right of fractal (default 2).- InpLiquidityPad: Premium/discount extension points, and also affects the stop loss distance and text label position. - InpPremiumColor/InpDiscountColor/InpLiquidityColor: The colors of the premium area, discount area, and cleaning prompts can be adjusted according to the theme. - InpEnableLogging: Controls CSV output. - InpShowDevelopingZhongshu: Whether to draw the ongoing pivot prediction box. ## 9. Follow-up development suggestions 1. Score system implementation: Introduce winning rate/profit and loss ratio statistics into the current simulated trading module, and dynamically adjust trigger conditions or lot sizes. 2. Multiple Position Management: Supports multiple batch entries/position additions within the same hub, and provides layered take-profit strategies. 3. Strategy Playback Tool: Develop a simple review script based on existing logs to restore CSV to a signal timeline. 4. Parameter Dashboard: Add a configurable small panel (object button) on the chart to quickly switch periods/thresholds. 5. Performance Optimization: Add incremental updates to the loops in UpdateFractals() and BuildPens() to reduce full traversal.
💡 Featured Recommendations
🔗 You May Be Interested In