OPEN-SOURCE SCRIPT

Magic Touch Line Detector

Updated
Summary of the Magic Touch Line Detector Script:
Purpose:
The Magic Touch Line Detector script is designed to identify significant price points in the market by analyzing candlestick wicks and bodies. It plots lines based on the detected wicks, classifying them as either ascending or descending. The script tracks how frequently price touches these lines and highlights the "most touched" lines for both ascending and descending categories. This script is particularly useful for traders looking to identify key price levels and trends over time.

How It Works:
Wick and Body Detection:
The script starts by analyzing the highs and lows of candlestick wicks relative to their bodies over a user-defined lookback period. A significant wick is identified based on a specified wick-to-body ratio and a deviation threshold measured against the Average True Range (ATR).

Line Creation:
Once a significant upper or lower wick is detected, the script calculates unconventional highs and lows (i.e., points that differ from the absolute highs and lows of the lookback period). Lines are then drawn from these unconventional price points using the slope between the detected wick and the current bar, ensuring a smooth extension.

Line Refinement and Touch Tracking:
As new bars are added, the script tracks how often the price touches the previously drawn lines. The number of touches each line receives is counted and updated in real-time, and the script ensures that only the most touched line is highlighted.

Highlighting and Labeling:
For each category (ascending and descending), the most touched line is identified and given special highlighting with thicker lines and different colors. Labels are also generated to show the number of touches that the most touched line has received. Old labels are cleared to avoid clutter.

Explanation of the Settings:
Lookback Period for Highs and Lows:
This sets the number of bars the script will use to detect the highest highs and lowest lows. A larger lookback period gives the script a broader context to work with, potentially identifying more significant price points.

Minimum Wick-to-Body Ratio:
This ratio determines what qualifies as a "significant" wick. It compares the length of the wick to the body of the candle. A higher ratio means that only wicks that are much longer than the candle body will be considered significant.

Price Deviation Threshold (in ATR multiples):
This setting controls how much price deviation from the ATR is required for a wick to be deemed significant. It acts as a filter to reduce noise by ignoring smaller wicks that are within normal price movements.

Line Touch Tolerance Factor (ATR multiple):
When checking if a price touches a line, the script uses this setting to define how close the price must be to the line to count as a "touch." This tolerance is a multiplier of the ATR, allowing for some flexibility in what is considered a touch.

Price Difference Threshold:
This defines the minimum price difference required to plot a line. If the price difference between the high and low of a detected wick is too small, the script can avoid plotting a line for insignificant moves.

Slope Adjustment Multiplier:
This multiplier adjusts the slope of the lines that are drawn from detected price points. It affects the length and angle of the lines, allowing users to control how far and at what angle the lines should extend across the chart.

Customization Options:
Show Ascending/Descending Lines:
These toggles allow users to decide whether ascending (bullish) or descending (bearish) lines should be shown on the chart.

Line Color, Style, and Width (for Ascending and Descending Lines):
These settings give users control over how the lines appear visually. You can customize the color, style (solid, dashed, dotted), and width of both ascending and descending lines.

Most Touched Line Color:
Users can define a different color for the "most touched" line, which is automatically identified by the script. This setting helps highlight the line that has been interacted with the most by the price.

How to Use the Script:
Setup the Lookback Period and Deviation Filters:
Start by setting the lookback period and the filters for wick-to-body ratio and deviation threshold. These settings help control the script's sensitivity to market movements.

Refine the Tolerance and Slope:
Adjust the line touch tolerance and slope adjustment multiplier to control how closely the script tracks price touches and how the lines are extended on the chart.

Customize Visuals:
Once the lines are being drawn, customize the colors, styles, and widths to ensure the lines are easy to read on your chart. You can also decide if you want to display both ascending and descending lines or focus on just one.

By setting up the script based on these inputs and parameters, you can get a real-time view of significant price levels and how often the price interacts with them, helping you make more informed trading decisions.
Release Notes
Independent Customization for Most Touched Lines:

Most Touched Ascending: Customizable color, style, and width (mostTouchedAscLineColor, mostTouchedAscLineStyle, mostTouchedAscLineWidth).

Most Touched Descending: Customizable color, style, and width (mostTouchedDescLineColor, mostTouchedDescLineStyle, mostTouchedDescLineWidth).

showOnlyMostTouched:
If true, only the most touched ascending and descending lines are displayed.

If false, all lines will be shown, but the most touched lines will still be highlighted with their respective custom styles.
Release Notes
Refined Slope Adjustment Settings:
The script was updated to allow separate control over the slope adjustment multiplier for ascending and descending lines. This provided more flexibility in managing how each line type extends and behaves visually.

Removed Unnecessary Settings:
The “Price Difference Threshold” and “Line Touch Tolerance Factor” inputs were non-functional. After removing them from the script, the logic was simplified.
Release Notes
Toggle for Touch Count Labels:

Added the ability to toggle the display of touch count labels for ascending and descending lines independently.

Two new settings were introduced:
Show Touch Counts for Ascending Lines
Show Touch Counts for Descending Lines

The touch count labels are only displayed if the corresponding toggle is selected. This allows for cleaner chart displays when the touch counts are not needed.

Customizable Label Colors and Text:

Added settings to customize the label colors and text colors for ascending, descending, and most touched lines. These settings allow users to personalize how the labels appear on the chart for better visual clarity.

Prevention of Duplicate Labels:

Modified the logic to prevent duplicate labels on the most touched lines. Previously, the most touched lines were being labeled twice because they were also part of the ascending/descending lines. Now, the script checks to ensure the most touched lines are only labeled once.

Outcome:
The script now allows for dynamic customization of touch counts, offering clear control over when and how the touch count labels are displayed.
Release Notes
Ensured Consistency of Most Touched Lines:
Issue: The most touched ascending and descending lines would change position or disappear when toggling the "Show Only Most Touched Lines" option.
Fix: Decoupled the calculation of the most touched lines from the visibility toggle. This means that regardless of whether you choose to display only the most touched lines or all lines, the calculations for determining the most touched lines remain consistent. The most touched lines now retain their positions and touch counts irrespective of display settings.

Avoided Deleting Lines to Preserve Arrays and Indices:
Issue: Deleting non-most touched lines when hiding them caused the line arrays to change size, leading to incorrect indexing and touch count mismatches.
Fix: Instead of deleting lines, the script now hides non-most touched lines by setting their color to transparent (na). This approach preserves the line arrays and their indices, ensuring that touch counts and line references remain accurate.

Maintained Consistent Indexing and Touch Counts:
Issue: Altering the line arrays by deleting lines caused the indices of remaining lines to shift, which led to incorrect associations between lines and their touch counts.
Fix: By keeping all lines in the arrays and only modifying their visibility, the indices remain consistent throughout the script's execution. This ensures that each line's touch count is accurately maintained and associated with the correct line.

Updated Touch Counts on Every Bar:
Issue: Touch counts were not being updated consistently, especially when lines were hidden or shown, leading to inaccurate identification of the most touched lines.
Fix: The script now updates touch counts for all lines on every bar, regardless of their visibility. This ensures that the most touched lines are always identified based on up-to-date touch counts, maintaining accuracy in their selection.

Corrected Variable Reassignment:
Issue: Using the wrong assignment operator (= instead of :=) when reassigning variables declared with var caused variable shadowing warnings and potential logic errors.
Fix: Replaced the = operator with the correct reassignment operator := for variables declared with var. This prevents variable shadowing and ensures that variables are updated properly within the script's scope.

Separated Calculation Logic from Display Logic:
Issue: Calculations for touch counts and determining the most touched lines were inadvertently dependent on the visibility settings, causing inconsistencies when toggling display options.
Fix: Separated the logic for calculations from the display settings. The script now performs all necessary calculations independently of whether lines are visible or hidden. This ensures that changing display options does not affect the underlying calculations or the accuracy of the most touched lines.

Consistent Application to Both Ascending and Descending Lines:
Issue: Inconsistent logic between ascending and descending lines led to one type of line behaving correctly while the other did not.
Fix: Applied the same corrections and logic to both ascending and descending lines. This ensures that both types of lines behave consistently, with their most touched lines remaining accurate and stable regardless of display settings.

Improved Label Handling:
Issue: Labels for touch counts and most touched lines were not always displaying accurate information or were not positioned correctly, especially when toggling visibility settings.
Fix: Adjusted label creation functions to accurately reflect the current state of lines and their touch counts. Labels for the most touched lines now display the correct number of touches and are positioned appropriately. Labels for other lines are also displayed correctly when toggled.
Release Notes
Touch count labels now only display when their corresponding lines are visible on the chart.
Labels for hidden lines (e.g., when "Show Only Most Touched Lines" is enabled) no longer clutter the chart.
Release Notes
No Minimum Wick-to-Body Ratio (0) Integration:

No Wick Candle Detection:
When the Minimum Wick-to-Body Ratio is set to 0, the logic detects candles that have no wicks (i.e., the open/close and high/low points are at the same levels). This identifies bullish or bearish no-wick candles where the price action shows strong momentum without any significant retracement.

What Is Detected with the No Wick Logic:
Bullish No Wick Candle: When the close price equals the high and the open price equals the low, this indicates a strong bullish move without a wick on either side.
Bearish No Wick Candle: When the open price equals the high and the close price equals the low, this indicates a strong bearish move without any wicks.

Doji Surrounded No Wick Detection:
The logic also detects no-wick candles surrounded by doji candles (candles with small body sizes). This pattern highlights potential reversal or continuation zones with significant price compression.

Separate Slope Logic:
When the Minimum Wick-to-Body Ratio is 0, the slope adjustment multipliers for no wicks are applied, allowing the script to adjust line projections accordingly, differentiating between no-wick and wick candles for more accurate line placements.

Separate Slope Logic for Wicks and No Wicks:
Introduced separate slope adjustment multipliers for ascending and descending lines when wicks are present versus when there are no wicks (Minimum Wick-to-Body Ratio = 0). This ensures that the logic adapts based on whether the candle has wicks or not.

Silo Detection Logic Enhancements:
A second toggle was added to detect silos formed by candles with almost identical body sizes. This is in addition to the existing silo detection logic for candles with no top or bottom wicks.
Option to Hide Touch Counts for Most Touched Lines:

A setting was added to hide the touch counts for the most touched lines, while still showing the lines themselves. This offers better control over how much information is displayed on the chart.

Silo Pattern Highlighting:
The script was enhanced to highlight both traditional rejection silos (based on wicks) and silos of equal or nearly identical candle body sizes, using distinct colors for bullish and bearish patterns.

These changes have made the script more flexible and customizable, providing better control over line detection and display.

**NOTE* This script is highly experimental. I'd enjoy feedback in comments of what you've discovered, any issues, ideas, and what use cases you've found for it and whether or not its helped you discover anything.**
Release Notes
Enhanced Label Management
Streamlined Labels: Labels for the most touched ascending and descending lines are now managed more efficiently. This prevents clutter on your chart by ensuring only relevant labels are displayed.

Dynamic Updates: Labels automatically update their position and information in real-time as touch counts change, providing you with up-to-date insights without manual adjustments.

Improved Stability and Error Handling
Explicit Variable Typing: Variables that previously caused assignment errors have been explicitly defined. This enhances the script’s stability, ensuring it runs smoothly without unexpected interruptions.

Boundary Checks: Added safeguards to ensure that all line indices are within valid ranges before being accessed. This prevents potential crashes or glitches, especially when dealing with multiple lines.

Refined Toggle Functionality
"Show Only Most Touched Lines" Toggle:
Accurate Display: When enabled, this toggle now reliably displays only the most touched ascending and descending lines, hiding all others seamlessly.

Conditional Labels: Labels for non-most-touched lines appear only when this toggle is disabled, maintaining a clean and focused chart view.

"Show Touch Counts for All Lines" Toggles:
Independent Control: Separate toggles for ascending and descending lines allow you to display touch counts for each category independently.

Exclusion of Highlighted Lines: The most touched lines are intelligently excluded from these touch count displays to avoid redundant information and enhance clarity.

Robust Most Touched Line Identification
Accurate Tracking: The indicator now more reliably tracks and identifies the lines with the highest touch counts, ensuring that the most significant lines are always highlighted.
Single Instance Highlighting: Only the top ascending and descending lines are highlighted at any given time, preventing multiple lines from competing for attention and enhancing readability.

Optimized Performance
Preventing Label Overload: By reusing label instances and updating them instead of creating new ones continuously, the update significantly reduces potential performance issues and keeps the chart clean.

Efficient Line Management: Lines are now managed more effectively, with older or less significant lines being automatically hidden or reset based on your settings and touch counts.

Enhanced User Experience and Customization
Intuitive Visuals: Improved label positioning and styling ensure that all information is presented clearly without obstructing your view of the chart or other indicators.

User-Friendly Toggles: The refined toggle options provide greater control over the indicator’s display, allowing you to tailor the visualization to your specific trading strategies and preferences.

Consistent Styling: Enhanced consistency in line colors, styles, and widths across ascending and descending lines ensures a harmonious and professional appearance on your chart.

Comprehensive Error Resolution
NA Assignment Fixes: Resolved issues related to assigning na (not available) to variables without explicit type declarations. This ensures that the indicator operates without errors, providing a smoother experience.
Release Notes
Conditional Label Creation for Most Touched Lines:
Ascending Lines: Before creating or updating the label for the most touched ascending line, the script now checks if hideTouchCountsForMostTouched is disabled. If it's enabled, any existing label for the most touched ascending line is deleted.

Descending Lines: Similarly, for descending lines, the script checks the toggle's state before handling label creation or deletion.

Ensuring Labels Are Hidden When Toggle Is Enabled:
If hideTouchCountsForMostTouched is enabled, the script ensures that labels for the most touched lines are not created or are removed if they already exist.
forecastingPivot points and levelsTrend Analysis

Open-source script

In true TradingView spirit, the author of this script has published it open-source, so traders can understand and verify it. Cheers to the author! You may use it for free, but reuse of this code in publication is governed by House rules. You can favorite it to use it on a chart.

Want to use this script on a chart?


Also on:

Disclaimer