OPEN-SOURCE SCRIPT

CQ_(9)_Zig Zag Auto Fibonacci Retracement

575
================================================================================
CQ_(9)_[ZIG ZAG AUTO FIBONACCI RETRACEMENT]
USER MANUAL
================================================================================
Author handle : CQuevedo345
Platform : TradingView
Language : Pine Script v6
Type : Overlay indicator
Built from : Section 1 = CQ_(5)_Zig Zag Trend Metrics (ported verbatim)
Section 2 = CQ_(8)_Auto Fibonacci Retracement (adapted to be
fed by the zigzag's last confirmed leg)

--------------------------------------------------------------------------------
1. WHAT THIS INDICATOR DOES
--------------------------------------------------------------------------------
This script merges two tools into one overlay:

A) A ZIG ZAG SWING ENGINE that detects confirmed swing highs and lows over
a user-defined lookback period, connects them with lines, labels each
swing with its price/percent change and bar-time distance from the prior
opposite swing, and (optionally) shows a running statistics table of the
average up-leg and down-leg size/duration.

B) An AUTO FIBONACCI RETRACEMENT + GAUGE that is automatically anchored to
whatever the zigzag currently considers its LAST CONFIRMED LEG. As the
zigzag confirms new swings, the Fibonacci grid re-anchors itself with no
manual drawing required.

Because the retracement math is direction-agnostic (0% is always the newest
pivot, 100% is always the older pivot), the readout flips meaning depending on
the leg type:

- Last leg is BEARISH (High -> Low) => retracement is measured UP from the
low, i.e. it reads as a potential BULLISH bounce.
- Last leg is BULLISH (Low -> High) => retracement is measured DOWN from
the high, i.e. it reads as a potential BEARISH pullback.

--------------------------------------------------------------------------------
2. HOW THE ZIG ZAG ENGINE WORKS (SECTION 1)
--------------------------------------------------------------------------------
- Every bar, the script checks whether the current bar's high is the highest
high of the last "Period" bars (a confirmed pivot high) or the current low
is the lowest low of the last "Period" bars (a confirmed pivot low).
- "direction" flips to +1 on a new pivot high context and -1 on a new pivot
low context. A swing point is only "added" the first time direction flips;
while direction stays the same, the existing extreme point is simply
UPDATED (extended) if price makes a more extreme high/low.
- Each swing point gets a label showing:
* Pattern tag: HH / LH (higher high / lower high) or LL / HL
(lower low / higher low)
* The price or percent change versus the most recent OPPOSITE swing
(format controlled by the "Δ Format" input)
* Elapsed bars ("⏱") since that opposite swing
* Optionally, a second "cycle" line showing elapsed bars since the
previous SAME-type swing (Show "Display Cycle")
- Connecting lines:
* Thin "range lines" link consecutive same-type swings (high-to-high,
low-to-low) if "Range Lines" is enabled.
* Thick colored lines link low-to-high (bullish leg, up color) and
high-to-low (bearish leg, down color) — these are the zigzag's main
visible backbone and are what Section 2 anchors to.
* A fill (linefill) shades the area between the most recent high-to-high
and low-to-low lines.
- A statistics table (optional) shows the GEOMETRIC AVERAGE of the last N
("Averaging") up-leg and down-leg price changes and their average bar
durations. Geometric averaging is used instead of arithmetic to better
represent compounding percentage moves.

--------------------------------------------------------------------------------
3. HOW THE FIBONACCI ENGINE WORKS (SECTION 2)
--------------------------------------------------------------------------------
- A "leg bridge" watches the zigzag's internal arrays every bar. Whenever the
zigzag's lastSwingType is "high" and a bullish line exists, that bullish
line becomes the active Fibonacci anchor (0%=high just made, 100%=the low
it came from). Whenever lastSwingType is "low" and a bearish line exists,
that bearish line becomes the anchor instead (0%=low just made, 100%=the
high it came from).
- The active leg line is automatically restyled DASHED with hollow circle (◯)
markers at both ends so you can see at a glance which leg is currently
driving the Fibonacci grid. When a newer leg takes over, the old leg is
reverted back to its normal solid zigzag styling.
- Standard retracement levels drawn: 0%, 25%, 40%, 50%, 60%, 75%, 90%, 100%
(each individually toggleable).
- Extended/projection levels are drawn AUTOMATICALLY, only when price has
actually traded through the prior threshold level: -25%, -50%, -100%,
-150%, -200%, 125%, 150%, 200%. These auto-lines fade in only when needed,
keeping the chart clean during normal retracements.
- Each level shows:
* A short horizontal "identifier" line from the pivot's opposite end out
to the current bar (dotted for internal levels, solid+thick for 0%/100%)
* A small tick/handle at the right-hand gauge column
* A label with the level percentage and (optionally) the exact price
- GAUGE (drawn at the 100% level position, right side of chart by default):
* Outer dotted box + white/colored end lines = the highest/lowest price
reached since the anchor leg was confirmed (the "extreme" reading,
also shown as a small ▲/▼ % label).
* Inner solid box + thick colored line = current CLOSE plotted against
the 0% pivot price, i.e. a compact visual "how far has price already
retraced/extended" bar.
- PROFIT LABEL (drawn at the 0% level): shows the raw $ change of the current
close versus the 0% pivot price, with a tooltip giving the % change too.
- An optional raw CLOSE PRICE line/area/histogram/step/cross/column/circle
plot can be overlaid for reference (off by default).

--------------------------------------------------------------------------------
4. INPUT REFERENCE
--------------------------------------------------------------------------------
♦ lines (zigzag)
- Period : Lookback bars used to confirm a pivot high/low
- Color ↑ / ↓ : Colors of the bullish/bearish zigzag legs
- Width : Line width of the zigzag legs
- Range Lines / color : Toggle + color for the thin high-to-high /
low-to-low connector lines
- Highlight Last Confirmed Leg : Toggle the dashed+circle styling on the
active leg
- Marker Size : Size of the hollow circle end markers

♦ labels (zigzag)
- Δ Format : "Percent" or "Absolute" for the swing-label
price change readout
- Text Size : Size of zigzag swing labels
- Display Cycle : Adds a second same-type elapsed-time line to
each swing label

♦ statistics table (zigzag)
- Show Stats table : Toggle the table on/off
- Location / Size : Table position and text size
- Averaging : Number of past legs used in the geometric
average calculation

🪙 Fibonacci Retracement — ⚙ Master Control
- Enable Fibonacci Gauge : Master on/off switch for Section 2
- 25% / 40% / 50% / 60% / 75% / 90% : Toggle each standard retracement level

Close Price Plot
- Show Line Graph, Color, Width, Style : Optional raw price plot overlay

Color Settings
- BEARISH / BULLISH theme colors (note: named for the CURRENT tendency the
retracement implies, not the leg direction itself — see Section 1 note
above)
- Use Trend Colors for Labels (+ independent label colors if disabled)
- Label Side (vs Gauge) : Left or Right label placement
- Gauge ⁞▌ toggle + Bullish/Bearish highlight colors
- Gauge X-Offset : Horizontal offset of the gauge column from the
anchor bar
- Level Tick Length (Right) : Length of the small tick marks at the gauge
- Show Price on Labels : Adds the exact price under each % label
- Label Size
- Gauge at Line End (vs Current Bar) : Anchors the gauge column to the end
of the active leg line instead of following the
live/current bar

♦ Last Confirmed Leg
- Dash Last Leg : Restyle the active leg as dashed
- Mark Start/End (Hollow Circles) : Add ◯ markers at both ends
- Circle Size

--------------------------------------------------------------------------------
5. READING THE CHART — QUICK GUIDE
--------------------------------------------------------------------------------
1. Find the DASHED leg with ◯ markers — that is the leg currently driving the
Fibonacci grid.
2. Check which color theme is active at the gauge (BULLISH vs BEARISH theme
color) to know whether the retracement is reading as an up-bounce or a
down-pullback.
3. Use the OUTER gauge box to see how far price has already run beyond the
0%/100% pivots (the extreme reached since the leg was confirmed).
4. Use the INNER gauge box/line to see where the current close sits relative
to the 0% pivot right now.
5. The PROFIT label at 0% gives you a quick $ (and, via tooltip, %) read of
how far price has moved from the most recent extreme pivot.
6. Auto-extension levels (125%, 150%, 200%, -50%, -100%, etc.) only appear
once price has actually traded past the prior level — their absence means
price hasn't reached that extension yet.

--------------------------------------------------------------------------------
6. TECHNICAL NOTES / ARCHITECTURE
--------------------------------------------------------------------------------
- indicator() flags: max_labels_count=500, max_lines_count=500,
max_boxes_count=500, explicit_plot_zorder=true, max_bars_back=4000.
- Section 1 is ported VERBATIM from CQ_(5)_Zig Zag Trend Metrics — no logic
was altered, only reused as the pivot/leg source of truth.
- Section 2 does not run its own pivot detection; it reads directly from the
Section 1 arrays (swingHighValues/BarIndexes, swingLowValues/BarIndexes,
bullishLines, bearishLines, lastSwingType) each bar via the "leg bridge"
block, so the two sections always stay in sync.
- Persistent var objects (lines/boxes/labels) are reused and repositioned in
place each bar rather than deleted/recreated, following the standard CQ
collect-then-update pattern for efficient rendering.
- request.security() is used once to pull a small multi-value tuple
(volume, OHLC variants, ATR14, RSI-of-PVT, etc.) — several of these fields
are legacy/reserved from the source script and only k_atr14 and k_high/
k_low are actively used by the current Fibonacci logic.
- Colors for the "BULLISH"/"BEARISH" theme inputs are intentionally reversed
relative to leg direction — they represent the TENDENCY implied by the
retracement, not the raw zigzag leg color. This mirrors the source script
(CQ_(8)) naming convention; see Section 3 note if this feels
counter-intuitive at first.

--------------------------------------------------------------------------------
7. VERSION / COMPATIBILITY
--------------------------------------------------------------------------------
- Written for Pine Script v6.
- overlay=true — must be applied directly to the price chart, not a
separate pane.
- No alerts or strategy logic included; this is a pure visual/analysis tool.

================================================================================
END OF MANUAL
================================================================================

免責事項

これらの情報および投稿は、TradingViewが提供または承認する金融、投資、取引、またはその他の種類の助言もしくは推奨であることを意図したものではなく、またこれらに該当するものでもありません。詳細は利用規約をご覧ください。