This Pine Script code implements an Automatic Fibonacci Levels indicator for TradingView, designed to analyze market trends and visualize key Fibonacci retracement levels dynamically on the chart.
1. User Inputs and Settings
The script begins by defining several user-configurable settings. These include options to extend the Fibonacci lines left or right, display an anchor line (a diagonal line connecting the most recent swing high and low), and customize its color and width. Additionally, users can select the size of the swing detection (small, medium, or large) and enable or disable individual Fibonacci levels such as 0, 0.236, 0.382, and so forth, allowing for personalized adjustments based on trading preferences.
2. Trend Information
The script also incorporates a label that provides real-time trend information. Users can choose where to position this trend label on the chart (e.g., top right, bottom left), enhancing the indicator's usability by providing context on the market’s current direction.
3. Swing Detection
A crucial part of the script involves detecting swing highs and lows based on the selected swing size. This is achieved by applying a lookback period (34, 89, or 144 bars) to determine the highest and lowest points within that range. This detection is pivotal for accurately calculating the Fibonacci levels based on the identified swing points.
4. Fibonacci Level Calculation
The Fibonacci levels are drawn dynamically based on the trend direction determined by comparing the current price with a simple moving average (SMA) over 50 periods.
In a downtrend, Fibonacci levels are calculated from the swing low to the swing high, indicating potential resistance levels where prices might retrace.
Conversely, in an uptrend, Fibonacci levels are calculated from the swing high to the swing low, highlighting potential support levels where prices could bounce back.
For each Fibonacci level that is enabled, the script creates a line and a corresponding label displaying the level value and price, providing clear visual cues for traders.
5. Anchor Line Feature
The anchor line visually connects the most recent swing high and low points, offering a quick reference for traders to gauge the price action's context. This line is updated dynamically as new swing points are detected, reflecting the most current market conditions.
6. Trend Label
The trend label provides a summary of the market trend—either positive (uptrend), negative (downtrend), or flat. This label updates in real time, ensuring traders can quickly ascertain the prevailing market sentiment at a glance.
7. Cleanup Mechanism
Finally, the script includes mechanisms to clean up the drawn lines and labels whenever conditions change or when settings are modified. This ensures that the chart remains uncluttered and only displays relevant information based on the user's current settings.