OPEN-SOURCE SCRIPT

Fibonacci Retracement Depth & Retest Grid - Swing High Low

962
OVERVIEW

Fibonacci Retracement Depth & Retest Grid - Swing High Low is an open-source chart overlay for measuring retracement depth inside an automatically selected price leg.

The script combines an automatic right-confirmed swing engine, a bounded local-range fallback, optional manual-origin control, rolling-range analysis, configurable Fibonacci ratios, distinct touch-episode tracking, fixed-horizon response measurements, larger-range ratio proximity, factual alerts, and a compact context readout.

It is a descriptive research tool. It does not generate entries, exits, targets, stops, position sizes, probability estimates, win rates, or performance claims. It does not use artificial intelligence, machine learning, external datasets, or third-party libraries.

CORE FIBONACCI CALCULATION

For an active origin and terminal, each level is calculated as:

level = terminal + (origin - terminal) * ratio

The terminal anchor is 0%, and the origin anchor is 100%.

Current retracement depth is calculated as:

depth = (reference price - terminal) / (origin - terminal)

This produces the same interpretation for upward and downward legs:

- 0% means price is at the terminal anchor.
- 100% means price is at the origin anchor.
- A value below 0% means price has moved beyond the terminal.
- A value above 100% means price has moved beyond the origin.

The current-depth cursor displays the actual calculated value. Its chart position is bounded between the two anchors so that an extreme value does not distort the visible layout.

ANCHOR ENGINES

The script provides three anchor engines.

1. Automatic swing

Automatic swing is the default.

The engine detects pivot highs and lows from either wicks or closing prices. A pivot is accepted only after the configured number of right-side bars has closed. Accepted pivots must alternate between high and low.

A new opposite-side pivot must satisfy:

- Minimum spacing in chart bars.
- A non-zero price distance.
- An optional minimum leg size expressed in ATR.

A later pivot of the same type can revise the active terminal only when it is more extreme by at least the configured minimum-tick threshold. This reduces small live revisions and visual flicker.

When a complete confirmed pivot pair is not yet available, the script uses a bounded local high-low range so the chart does not remain blank. The default local window is 120 finalized bars. The fallback is replaced automatically when a valid confirmed swing pair becomes available.

2. Manual origin

Manual origin is an explicit optional mode.

The user selects a paired time-and-price point as the structural origin. The script then searches after that point for the most extreme valid terminal in the selected direction.

Direction can be:

- Auto from point
- Up leg
- Down leg

The origin price can snap to the selected bar or preserve the exact selected price. By default, the terminal uses closed bars only to reduce intrabar movement of the complete Fibonacci structure.

Manual origin does not silently fall back to an automatic structure. If the selected point or terminal is invalid, no manual grid is displayed until the point or settings are corrected.

3. Rolling range

Rolling range uses the highest and lowest selected source values inside a fixed lookback. The chronological order of the two extremes determines whether the leg is upward or downward.

A minimum span in bars is required between the extremes. The anchors can change as the lookback advances, so current-structure statistics reset whenever the active pair changes.

CONFIRMATION AND HISTORICAL PLACEMENT

In Automatic swing mode, an H or L marker is placed at the historical pivot bar after that pivot becomes confirmed.

The diagonal anchor leg connects the actual origin and terminal bars. However, the horizontal Fibonacci levels do not begin before the complete structure became available to the script. They begin from the availability point rather than being extended backward through bars where the completed pair was not yet knowable.

This distinction is intentional:

- The anchor marker shows where the pivot occurred.
- The level start shows when the active structure became available.

A marker on a historical pivot bar should not be interpreted as evidence that the pivot was known on that original bar.

If a high pivot and low pivot are both confirmed from the same chart bar, finalized OHLC data cannot prove which extreme occurred first inside that bar. When a previous terminal type exists, the engine prefers the opposite candidate to preserve alternation. It does not invent an intrabar order that the available data cannot establish.

PAST-CHART STUDY

When Use visible right edge in past charts is enabled and the chart is scrolled away from the latest bar, the visible right edge becomes the study endpoint.

Inside the configurable local window, the script first looks for a recent accepted confirmed swing. If a suitable pair is not available, it uses a bounded local high-low range ending at the visible right edge.

This prevents historical study from automatically expanding to the absolute high and low of an excessively large viewport.

Past-chart auto-follow is retrospective. The completed visible period is already known. Therefore:

- Sequential touch-response statistics are disabled.
- Price-event alerts are disabled.
- The readout changes from Response to Study.

For chronology-sensitive historical testing, use Automatic swing with TradingView Bar Replay. Pivots will become available only after the configured right-side confirmation bars.

CONFIGURABLE FIBONACCI LEVELS

The script contains ten independently editable ratio slots.

The default enabled ratios are:

- 0.000
- 0.236
- 0.382
- 0.500
- 0.618
- 0.786
- 1.000

The following ratios are available but disabled by default:

- 0.650
- 0.705
- 0.886

Each slot can be enabled, disabled, or changed. Inputs accept values from -2.000 to 3.000, allowing custom retracement or extension research.

The script does not assume that a custom ratio is predictive or statistically significant.

DEPTH BANDS

Three optional visual bands organize the interior of the active retracement.

By default, they represent:

- 38.2% to 50.0%
- 50.0% to 61.8%
- 61.8% to 78.6%

The bands are built from configurable ratio slots. Changing those inputs changes the corresponding band boundaries.

The readout classifies proportional location as:

- Shallow
- Mid
- Deep
- T+ for beyond the terminal
- O+ for beyond the origin

These labels describe location only. They do not describe trade quality or reversal probability.

DISTINCT TOUCH EPISODES

Reaction research is available for enabled interior ratios greater than 0 and less than 1.

A level is contacted when the bar range intersects the configured tolerance around that price. Tolerance can be defined using:

- ATR
- A percentage of the active leg
- Minimum ticks

The script does not count every consecutive bar near a level as a separate reaction.

After an initial touch, price must move completely outside the wider re-arm envelope before another touch can be counted. This separates repeated contact into distinct touch episodes and reduces inflated counts caused by several bars remaining near the same price.

The latest counted touch for each level can be marked on the chart.

Touch statistics belong only to the current active anchor structure. They reset whenever the active origin or terminal changes.

FIXED-HORIZON RESPONSE RESEARCH

Each new touch episode creates an independent pending measurement.

After the configured number of chart bars has elapsed, the script measures the closing price relative to the touched level and normalizes the result by the active leg size.

The sign is aligned with the active leg direction:

- A positive response means the horizon close moved toward the terminal direction.
- A negative response means the horizon close moved toward the origin direction.

The readout uses:

- T for counted touch episodes.
- R for completed fixed-horizon measurements.

The displayed average is the arithmetic mean of completed measurements for the nearest enabled ratio within the current active structure.

This measurement is not:

- A bounce rate.
- A support or resistance score.
- Maximum favorable excursion.
- Maximum adverse excursion.
- A win rate.
- A probability estimate.
- A strategy result.

If the active anchors change before a pending response reaches its horizon, that pending measurement is discarded with the other statistics from the previous structure.

LARGER-RANGE RATIO PROXIMITY

The script can calculate a second Fibonacci structure from a longer rolling high-low range.

Each enabled primary level is compared with every enabled level in the larger-range structure. Proximity tolerance can be defined using:

- ATR
- A percentage of the primary leg
- Minimum ticks

When a primary level is sufficiently close to a larger-range ratio:

- Its line is highlighted.
- Its line width is increased.
- A diamond is added to its label.

This is a distance comparison only. It does not mean that the level is stronger, that price will reverse, or that the level will hold.

VISUAL OUTPUT

The default visual structure includes:

- A directional origin-to-terminal anchor leg.
- H and L anchor markers.
- Configurable Fibonacci level lines.
- Ratio and price labels.
- Three optional depth bands.
- A current-depth cursor.
- Latest-touch markers.
- Larger-range proximity diamonds.
- A compact bold context readout.

The readout summarizes:

- Active anchor engine and leg span.
- Current retracement depth.
- Nearest enabled level and ATR-normalized distance.
- Touch and response information, or historical study scope.
- Larger-range proximity and event-timing context.

Detailed explanations are available through cell and label tooltips so the visible panel can remain concise.

The readout also reserves a transparent horizontal edge-clearance lane. This keeps TradingView High/Low labels and price-scale markers visible when the panel is placed at a chart edge. The default clearance is 6% and can be adjusted in Settings.

Colors, line style, line widths, label content, label size, table position, table size, edge clearance, band opacity, and individual ratios are configurable.

ALERTS

The script provides factual alert conditions for:

- New confirmed Fibonacci swing structure
- Confirmed Fibonacci terminal revision
- Fibonacci level touch episode
- Core Fibonacci band entered
- Fibonacci origin crossed
- Fibonacci terminal crossed

The core band is defined by the Ratio 4 and Ratio 5 inputs.

Dynamic touch alerts are also available. When enabled, create a TradingView alert using Any alert() function call. The message reports the touched ratios, symbol, chart timeframe, and current close.

Confirmed-bar event evaluation is enabled by default.

Past-chart retrospective mode does not generate these price-event alerts.

Alerts report observed chart events only. They are not trade recommendations.

SUGGESTED WORKFLOWS

For current-market observation:

1. Keep Anchor engine on Automatic swing.
2. Keep Evaluate events on confirmed bars only enabled.
3. Select Wicks or Closes according to the research definition.
4. Adjust pivot left and right bars to control swing sensitivity.
5. Use Minimum leg ATR and Minimum bars between alternating pivots to reduce minor structures.
6. Use Automatic local window bars to control the warm-up and historical fallback horizon.
7. Read current depth and responses as descriptive context, not as an entry instruction.

For chronology-sensitive historical study:

1. Keep Anchor engine on Automatic swing.
2. Start TradingView Bar Replay before the period being studied.
3. Advance one bar at a time or at a controlled speed.
4. Observe when pivots become confirmed and when the Fibonacci grid becomes available.
5. Review touch episodes and completed fixed-horizon responses as replay advances.

For fast retrospective study:

1. Keep Use visible right edge in past charts enabled.
2. Scroll to the historical period.
3. Adjust the chart so the desired local structure is near the visible right edge.
4. Adjust Automatic local window bars if more or less structural context is required.
5. Review the Past swing or Past range readout state.

For a user-defined structural start:

1. Select Manual origin.
2. Set or reset the paired Origin point.
3. Choose Auto from point, Up leg, or Down leg.
4. Choose whether to snap to the selected bar or use the exact selected price.
5. Keep closed-bar terminal updates enabled for the more stable live behavior.

For an objective fixed-window range:

1. Select Rolling range.
2. Set the desired lookback.
3. Increase Minimum range span bars when short high-low pairs create excessive changes.

WHAT MAKES THIS IMPLEMENTATION DISTINCT

Fibonacci ratios and arithmetic retracement geometry are established public concepts. This script does not claim ownership of them.

Its distinct implementation choices include:

- Separation of historical pivot location from the later time when the structure becomes available.
- Availability-gated horizontal levels rather than unrestricted backward extension.
- Automatic confirmed-swing selection with a bounded finalized-bar warm-up fallback.
- Local past-chart auto-follow that avoids forcing the absolute extremes of a large viewport.
- Optional manual-origin and rolling-range engines in the same open implementation.
- Minimum spacing, ATR size, range-span, and tick-based terminal-revision filters.
- Distinct touch episodes controlled by a re-arm envelope.
- Independent fixed-horizon measurements normalized by active leg size.
- Direction-aligned descriptive responses rather than predictive bounce scores.
- Larger-range ratio proximity with configurable tolerance.
- Explicit separation of live, Bar Replay, and retrospective chart study.
- Compact tooltips and an edge-clearance lane designed to preserve chart-label visibility.
- Factual alerts without entries, exits, or performance claims.

The implementation uses conventional Fibonacci arithmetic and Pine Script built-ins. It does not import another author's library, reproduce a paper-specific model, request outside-market data, or present a proprietary trading methodology.

LIMITATIONS

- Fibonacci levels are proportional reference levels. They do not guarantee support, resistance, reversal, continuation, or any other future outcome.
- Confirmed pivots require right-side bars, so recognition necessarily occurs after the pivot bar.
- The active terminal can be revised when a later confirmed same-side pivot exceeds it by the configured threshold.
- During automatic warm-up, the bounded local-range fallback can change as finalized bars change until a confirmed pivot pair becomes available.
- The script displays one active Fibonacci structure rather than a permanent archive of every historical grid.
- Rolling range changes as its lookback advances and can reset all current-structure statistics.
- Past-chart auto-follow is retrospective and changes when the visible right edge or local-window setting changes.
- Finalized OHLC bars do not reveal the sequence of price movement inside each bar.
- If one bar intersects several levels, each level can be recorded, but their exact intrabar order is unknown.
- If confirmed-bar evaluation is disabled, realtime event states can change before the bar closes. Reloaded historical bars contain finalized OHLC, not the original realtime tick sequence.
- The calculation uses the chart's current symbol, timeframe, session, and price series. It does not request higher-timeframe or external-market data.
- Results depend on the history supplied by TradingView and the selected data provider.
- The Fibonacci calculation is arithmetic in price. Changing the chart to logarithmic scale changes visual spacing but does not change the underlying formula.
- Heikin-Ashi, Renko, Kagi, Line Break, and other non-standard charts can contain synthetic prices. Use standard candles when actual traded-price geometry is required.
- ATR-normalized filters and distances depend on the selected symbol and timeframe.
- Custom ratios can be duplicated, reordered, or placed outside the 0-to-1 interval. Users are responsible for interpreting custom configurations.
- Default settings are general research starting points. They are not optimized for any instrument, timeframe, market, or outcome.
- This is an indicator, not a strategy or backtest engine.
- Nothing displayed by the script constitutes financial or investment advice.

OPEN-SOURCE NOTE

The source is published under the Mozilla Public License 2.0 so users can inspect, verify, modify, and study the implementation.

The script is intended to support transparent chart research without hidden calculations, restricted access, or performance promises.

Haftungsausschluss

Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.