OPEN-SOURCE SCRIPT
تم تحديثه

AMD Po3 with Live Edge Stats [WillyAlgoTrader]

86 421
📊 AMD Po3 with Live Edge Stats is a free overlay indicator that detects the complete Power of Three cycle — Accumulation → Manipulation → Distribution — using a strict finite-state machine, validates every liquidity sweep by its return (not its depth), projects a Fibonacci-extension target from the full manipulation leg, and then does something most pattern indicators never do: it tracks its own results bar by bar and shows you the honest walk-forward statistics right on the chart.

The core insight: in the AMD model, a "smart money" cycle starts with a quiet accumulation range, continues with a manipulation (a fake breakout that sweeps resting stop-losses beyond the range boundary), and resolves with a distribution — the real move in the opposite direction. The single detail that separates a manipulation from a genuine breakout is the return: manipulated price snaps back inside the range quickly, a real breakout does not. This indicator is built entirely around that distinction.

New to the concept? Here is the whole idea in plain language. Markets often pause in a sideways box (accumulation). Below and above that box sit thousands of stop-loss orders. Sometimes price pokes out of the box just far enough to trigger those stops (manipulation), then reverses hard and travels through the box to the other side (distribution). This indicator finds the box, waits for the poke, demands proof that it was a fake-out (the return), and only then marks the expected move with an Entry, a Stop, and a Target — while a built-in scoreboard counts how often the pattern actually reaches that target on your symbol.

Works on all markets — crypto, forex, stocks, indices, futures — and all timeframes (tuned by default for 15M). Completely free.


🧩 WHY THESE COMPONENTS WORK TOGETHER

A range detector alone draws boxes but cannot tell a fake-out from a breakout. A sweep detector alone fires on every wick beyond a level with no context of where the range came from. A fib tool alone needs you to pick the anchors by hand. And none of them ever tell you whether the pattern has been working lately.

This indicator chains them into one pipeline where each stage feeds the next:

Compression detection → Range anchoring with impulse-tail trim → Boundary breach → Return-based sweep validation → Trade-at-manipulation reference model (Entry / Stop) → Fib-extension target from the manipulation leg → Outcome tracking → Walk-forward statistics dashboard

Compression finds ranges that are statistically quiet, not just visually flat. Tail trimming keeps the leftovers of the previous impulse out of the boundaries, so the box measures real accumulation. The breach arms a candidate sweep; the return deadline decides whether it was a manipulation or a breakout. Only a confirmed return opens the reference trade — and because the sweep extreme is known at that exact bar, the stop and the fib target are fully determined with zero lookahead. Finally, every closed cycle feeds the statistics engine, so the dashboard always answers the only question that matters: does this pattern currently have an edge on this chart?

Remove any link and the chain breaks: without compression the boxes are arbitrary; without the return rule every breakout poisons the signal set; without the reference model there is nothing to measure; without the statistics you are trading a story instead of data.


🔍 WHAT MAKES IT ORIGINAL

1️⃣ The full AMD cycle as a strict finite-state machine.

Most Po3 scripts paint boxes and arrows independently. Here the cycle is a formal FSM with phases IDLE → ACCUMULATION → SWEEP? → DISTRIBUTION, where every transition fires only on a confirmed bar close. A cycle cannot skip a stage, cannot exist twice, and every cycle ends in exactly one outcome: TARGET, STOP, TIMEOUT, EXPIRED, FAILED or BREAKOUT. This is what makes honest statistics possible — each detected cycle is one countable experiment.

2️⃣ Statistical compression detection with impulse-tail trimming.

A range is anchored only when the market is measurably quiet:

— Donchian(20) width must sit in the bottom N-th percentile (default 25) of its own distribution over a 200-bar window: percentrank(high20 − low20, 200) ≤ 25
— Minimum range width filter (default 0.15% of price) rejects micro-ranges where stop and target would drown in the spread
Impulse-tail trim (default 15%): while removing the oldest bar of the anchoring window shrinks the range width by more than 15%, that bar is dropped — so the tail of a preceding impulse leg never contaminates the boundaries. The window can never shrink below the minimum range maturity
— Boundaries come from confirmed pivots (default) or absolute extremes, and may "breathe" within a tolerance (default 10% of width) without resetting the range

3️⃣ Sweep validation by RETURN, not by depth.

A breach beyond the boundary (plus tolerance) does not make a sweep. The close must come back inside the range within a hard deadline (default 6 bars). If it does — manipulation confirmed. If it does not — the move is labeled BREAKOUT, no trade is ever opened, and the cycle is excluded from trade statistics (it is counted separately as pattern diagnostics). Optional strictness filters: sweep depth capped at a True Range percentile, required equal highs/lows (min 2 confirmed pivots within 0.1× width over 96 bars) beyond the boundary, and London / New York killzone session windows.

4️⃣ Trade-at-manipulation reference model — everything is fixed on one bar.

The reference trade opens on the very bar where the manipulation confirms (the M/D bar). All three levels are fully determined by data already printed:

— Entry = the close of that bar
— Stop = beyond the FULL sweep excursion (including that bar's wick) ± a buffer of 0.4 × ATR-anchor
— ATR-anchor is ATR(14) taken from the bar BEFORE the range started — this cures a subtle circularity where volatility measured inside the compression would shrink the buffer exactly when it matters most
— riskR = |entry − stop|, floored at one tick, so R math can never divide by zero

No waiting for extra confirmation candles, no repainting, no lookahead anywhere.

5️⃣ Fibonacci-extension target of the manipulation leg.

The target is not a fixed multiple of the range width — it scales with the manipulation itself. A fib grid is anchored from the sweep extreme (level 0) to the OPPOSITE accumulation boundary (level 1); the target sits at the extension level (default 1.5):

— Short: target = rangeLow − (fibExt − 1) × (sweepExtreme − rangeLow)
— Long: target = rangeHigh + (fibExt − 1) × (rangeHigh − sweepExtreme)

A deeper stop-hunt means a longer measured leg and a farther target — target and stop scale from the same extreme, which keeps the R:R profile consistent across cycles. Common values: 1.272, 1.5, 1.618, 2.0. Important: this level is the expected reach of the distribution, a structural projection — not a take-profit ladder.

6️⃣ Honest, conservative walk-forward statistics.

Every closed cycle is scored in R against the reference model, in strict chronological order, with three deliberately pessimistic rules:

— If one bar touches BOTH the target and the stop, the cycle counts as a STOP (−1R) and increments a separate "ambiguous" counter — intrabar order is unknowable, so the model refuses to guess in its own favor
— Percentages and Average R stay hidden until a minimum sample (default 10 cycles) is collected — a "78% win rate" built on 4 trades is noise dressed as insight
— TIMEOUT cycles (neither level within 64 bars) close at the actual R from the final close and are included in Average R, not silently dropped

7️⃣ Period statistics engine with a form strip.

The Stats section can be switched between 24 Hours, 30 Days and All-Time. Period figures come from a rolling timestamped buffer (31-day horizon); All-Time reads the full-history counters. A target-rate gauge (▰▰▰▰▱▱▱▱) and a form strip of the last 10 cycles (▰ = target, ▱ = stop, ◌ = timeout) let you read the recent behavior of the pattern in one glance.

8️⃣ Re-arm — the double-sweep scenario.

When the optional higher-timeframe bias filter (HTF close vs EMA50, fetched repaint-free from the last CLOSED HTF bar) rejects the projected direction, the range is not discarded: it re-arms and waits for a sweep of the opposite side, with a fresh time budget and a block on repeating the same side. Double-sweep cycles are tracked with their own Average R so you can see whether the second sweep carries a different edge.

9️⃣ Pattern diagnostics separated from trade results.

BREAKOUT (sweep never returned) and FAILED (returned, but the HTF filter rejected it with no re-arm left) are counted outside the trade statistics — no trade was opened, so there is nothing to score. The Failed / Breakout row answers a different question than the Target rate: not "does the trade work?" but "how often does this market actually play the manipulation game at all?"


⚙️ HOW IT WORKS — CALCULATION FLOW

Step 1 — Warm-up: the indicator waits for the statistics window (default 200 bars) before detecting anything.

Step 2 — Compression: on each confirmed bar in IDLE, the Donchian width percentile and minimum-width checks decide whether a range is born; the impulse tail is trimmed and boundaries are anchored (pivot or absolute mode). A 10-bar cooldown separates cycles.

Step 3 — Accumulation: the range ages, boundaries may breathe within tolerance. A breach of both boundaries on one bar (news spike) resets the cycle; exceeding the max age (default 96 bars) expires it; a breach before minimum maturity (default 12 bars) is an early break, not a sweep.

Step 4 — Sweep candidate: a qualifying breach starts the return countdown. The excursion extreme keeps updating with every wick.

Step 5 — Resolution: close back inside within the deadline → manipulation confirmed → the M and D labels print, the reference trade opens (Entry / Stop / Target drawn, DIST alert fires). No return in time → BREAKOUT. HTF filter rejection → re-arm or FAILED.

Step 6 — Outcome: from the next bar, each confirmed bar is checked against target and stop (conservative ambiguity rule) until TARGET, STOP or TIMEOUT closes the cycle, prints the outcome label with its R value, fires the outcome alert and updates every statistic.


📖 HOW TO USE

🎯 Quick start:
1. Add the indicator to a 15M chart (any symbol; other timeframes work too)
2. Let it load history — the dashboard starts collecting cycles immediately
3. Watch the phases: blue box = accumulation, orange box = sweep in progress, M = manipulation confirmed, D ▲/▼ = distribution direction with Entry / Stop / Target lines
4. Do nothing until the Stats section reaches the minimum sample (default 10 cycles)
5. Then read Target rate and Avg R — that is the measured edge of the pattern on THIS symbol and timeframe

👁️ Reading the chart:
— 🔵 Dashed blue box = accumulation range (boundaries + fill)
— 🟠 Orange box = manipulation excursion beyond the boundary; solid when the sweep is confirmed
M label = manipulation confirmed at the sweep extreme (M ↻ = re-armed, M ✗ = failed)
D ▲ / D ▼ = distribution direction, below the bar for longs, above for shorts; hover it for a tooltip with sweep side, all levels and R:R
— 📏 Level lines: subtle dotted Entry, solid Stop, dashed Target — each with a price label and % distance from entry
— 🟢 Target line turns solid teal with "Target ✓" when reached; it dims gray on timeout
— 🏷️ Outcome labels: ✓ +xR (target), ✗ −1R (stop), AMB ✗ (ambiguous bar), ◌ xR (timeout), plus EXPIRED / NEWS BAR / BREAKOUT markers
— Older cycles fade to outlines (or hide) — configurable history depth

📊 Dashboard fields:
Header: current phase, colored green/red during a live distribution
Market: Phase (+ bars in it), Compression percentile with a tightness gauge, active Range boundaries, HTF Bias, timeframe (with a ⚠ hint when off 15M)
Cycle: Long/Short @ Entry, Stop, Target, R:R, Risk %, Age — or a one-line status when no cycle is live
Stats: Cycles (with double-sweep count), Target / Stop / Timeout with percentages, Target rate gauge, Avg R, Form strip, Failed / Breakout diagnostics — all switchable between 24H / 30D / All-Time
— Every row has a hover tooltip explaining exactly what it measures

🔧 Tuning guide:
Too few cycles: raise the compression percentile (25 → 35) or lower minimum range width
Too many breakouts: your market resolves ranges by trending — raise "Max bars until return" (6 → 8-12) to admit slower manipulations, or enable the sweep depth cap to reject wide breaches early
Targets rarely reached: lower the fib extension (1.5 → 1.272); targets too easy — raise it (1.618 / 2.0)
Stopped by wick retests: increase the stop buffer (0.4 → 0.6 × ATR-anchor)
Only trade with the trend: enable HTF bias — rejected directions will re-arm for the opposite sweep


⚙️ KEY SETTINGS

⚙️ Range (Accumulation):
Min range maturity (default 12 bars): breaches before this = reset, not sweep
Max range age (default 96): time budget before EXPIRED
Compression threshold (default 25): width percentile ceiling
Distribution window (default 200): statistical lookback for percentiles
Boundary tolerance (default 0.10), Min range width % (default 0.15), Boundary method (pivot / absolute), Impulse-tail trim (default 15%)

🌀 Manipulation (Sweep):
Max bars until return (default 6): the manipulation deadline
Require liquidity beyond boundary (off): EQH/EQL confirmation
Soft depth cap (100 = off): True Range percentile ceiling for the excursion
Allow re-arm (on): double-sweep second chance under the HTF filter

🎯 Reference Model & Stats:
Stop buffer (default 0.4 × ATR-anchor), Fib extension target (default 1.5)
— Level lines / price labels / % distance toggles, line styles per level
Distribution timeout (default 64 bars)

🔍 Filters: Killzones (London / New York sessions, any timezone), HTF bias (EMA50, any higher timeframe, validated at load)

🎨 Visual: Auto / Dark / Light theme, per-layer toggles (boxes, event labels, killzone highlight, watermark), event and level label font sizes, history depth and style, Min sample for % and Avg R (default 10)

📊 Dashboard: position, font size, per-section toggles (Market / Cycle / Stats), stats period (24 Hours / 30 Days / All-Time)


🔔 ALERTS

— 🌀 SWEEP — boundary swept: side, ticker, TF, price, time, cycle id
— 🟢/🔴 DIST — manipulation confirmed and the reference trade opened: direction, sweep side, Entry, Stop, Target, R:R
— 🎯/🛑/⏱ OUTCOME — cycle closed: result (target / stop / ambiguous / timeout), R value, reference entry
All alerts fire once per bar close, support plain text and JSON webhook payloads, and are wired via a single "Any alert() function call" condition. A master switch disables everything at once.


⚠️ IMPORTANT NOTES

— 🚫 No repainting. Every FSM transition, signal and outcome is evaluated strictly on confirmed bar closes (barstate.isconfirmed). Higher-timeframe data uses the last CLOSED HTF bar via the [1] + lookahead idiom. Alerts fire once per bar close. Boundaries use confirmed pivots with equal left/right lookback — delayed confirmation, not repainting of future values.
— 📐 The statistics measure a reference model, not your execution: fills at bar close, no commissions, no slippage, no position sizing. Real results will differ. Past performance does not guarantee future results.
— 📐 The ambiguity rule is intentionally pessimistic: same-bar target+stop counts as a stop. Your live numbers can only be equal or better than this assumption, never worse because of it.
— ⚖️ Statistics reset when the chart reloads and depend on the loaded history depth. The period stats buffer covers a rolling 31 days.
— ⚖️ This is a cycle DETECTOR with an embedded measurement model — it does not manage positions, trail stops or scale out. The target is a structural projection, not trade advice.
— 🛠️ This is an analysis tool, not an automated trading bot. It detects AMD cycles, projects levels and reports honest statistics — trade decisions remain yours.
— 🌐 Works on all markets and timeframes; defaults are tuned for 15M charts (the dashboard reminds you when you are on a different timeframe).
ملاحظات الأخبار
🔧 MAJOR UPDATE — v2.4.0 (includes the v2.3.0 correctness release)

This update is the result of a full external audit of the model with reproduced counterexamples. Every confirmed finding is fixed. The detection pipeline is the same AMD cycle you know — it just cheats less now, draws honestly, and reports more.

⚠️ IMPORTANT: signal composition and R statistics differ from v2.2.0. Several fixes change which cycles get detected and how outcomes are scored, so numbers collected on older versions are not comparable. Let the walk-forward sample rebuild from zero before judging the edge.

🎯 MODEL CORRECTNESS

— 🌀 Sweep depth cap now actually caps the sweep. The threshold is frozen at the breach bar (prior-bar True Range percentile) and re-checked against the CUMULATIVE excursion on every bar of the pending sweep. A sweep that keeps digging past the cap is rejected as "TOO DEEP" instead of quietly confirming with a stretched stop
— ⚡ Two-sided bars no longer fake a one-sided manipulation. If the OPPOSITE boundary is breached while waiting for the return, the cycle resets ("2-SIDE") — the mirror of the news-bar rule that always existed in accumulation
— ⏱ Distribution timeout is now exact. The cycle lives precisely N bars after the open (inclusive boundary); touches still win over the timeout on the final bar. Previously one extra bar could sneak a TARGET past the deadline
— 📏 Displayed price = trigger price. Stop and target are tick-rounded at creation — the stop OUTWARD so the buffer is never rounded away, the target to the nearest tick. What you see on the label is exactly what the model checks
— 🧲 EQH/EQL filter finds real clusters. It now requires at least 2 confirmed pivots near the boundary that are ALSO within 0.1× width of each other — genuine equal highs/lows, not two distant points that happened to share a band
— 🧱 No more degenerate cycles. A pivot-anchored range is rejected when price already closed outside its boundaries, and a trade opens only with at least one tick of directional reward — target-at-entry geometry can no longer produce fake 0R outcomes
— 🔒 Boundary "breathing" can't drift anymore. The tolerance band is frozen in price at range birth — compounding expansion of the accumulation box is impossible
— 📡 HTF filter edge cases. Missing higher-timeframe data resets the cycle WITHOUT consuming the re-arm and without counting FAILED; an exactly-flat HTF now displays "Flat" instead of a misleading "Bearish"

📊 HONEST STATISTICS

— 🕳 Gaps are no longer flattered. A gap through the stop exits at the open — a stop-out can now honestly record worse than −1R. A gap through the target exits at the open too, crediting the actual favorable fill
— 🕐 Period stats (24H / 30D) are keyed by bar CLOSE time, matching the "cycles closed within the window" definition
— 🌡 New dashboard row "RR left" — the reward:risk remaining from the CURRENT price. It answers the question every late reader of an alert has: is it too late to enter now? Shows "past target" / "past stop" when the moment is gone
— 🧮 Reject-reason counters (expired / news & 2-side / too young / filtered) in a new diagnostics row — see exactly WHY ranges die before a sweep resolves, and tune the filters on facts
— 🏷 The Failed / Breakout row is explicitly tagged All-Time; the target-rate tooltip now states plainly that it is NOT a probability of profit — judge the edge by Avg R


👁️ VISUAL ACCURACY

— 📍 The M label anchors at the bar where the sweep extreme was ACTUALLY made — no more backpainted tips at coordinates that never existed on that candle
— 📦 Every phase box now includes its last bar: accumulation extends to the sweep bar, the sweep box to the return/reject bar, and the distribution box absorbs the outcome bar's full range — the candle that hit the target is inside the box that claims it
— 🗂 "Show last N cycles" keeps exactly N (was N+1), retires the oldest cycle the moment a new one is born, and outline mode now dims lines and labels too — not just box fills
— ⚠️ Non-standard charts (Heikin Ashi, Renko, etc.) trigger a visible warning — synthetic OHLC makes execution statistics meaningless, and the indicator now says so

🔔 ALERT PROTOCOL 2.0

— 🎚 Independent toggles for SWEEP / DIST / OUTCOME events — keep only the working signal if that's all you need
— ⚪ New optional CANCELED events (EXPIRED, BREAKOUT, TOO DEEP, 2-SIDE, FAILED) — webhook consumers can now track the full cycle lifecycle instead of wondering why a SWEEP was never followed by anything
— 🧾 Webhook JSON gains a schema version, the indicator version, the confirmation timestamp and a stable composite event id (ticker | TF | range bar | cycle) for reliable deduplication
— 🎯 R:R is transmitted at 0.01 precision (was 0.1)


⚙️ UNDER THE HOOD

— 🚀 The dashboard table is rebuilt only when its row structure changes; otherwise cells update in place
— 🧹 One consistent forward-projection policy for level lines; the Auto theme detects the background by weighted RGB luminance instead of the red channel alone; warm-up extended so every percentile window is fully formed before the first detection

Settings, layout and workflow are unchanged — existing chart templates keep working. Rebuild your sample, watch the new diagnostics row, and let the numbers speak. 📈
ملاحظات الأخبار
Fixed the correct version of the indicator.

إخلاء المسؤولية

لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.