Trendline Retest Planner [AGPro Series]Trendline Retest Planner
🧠 Core Idea
Is the active trendline retest constructive enough to keep the setup under review, or is it starting to fail?
📌 Overview / What it does
Trendline Retest Planner is a chart-first decision tool for traders who review price behavior around active support and resistance trendline retests.
Instead of drawing many trendlines or flagging every break, the script focuses on one active trendline retest context at a time. It measures line age, touch count, retest depth, close response, and volume support, then converts that evidence into a 0-100 Retest Score and a clear next-action state.
The script produces an active trendline, retest pocket, hold/fail labels, invalidation edge, target path, alerts, and a compact AGPro planning panel. It does not predict price movement, automate execution, or provide guaranteed outcomes.
🎯 Purpose & Design Philosophy
This script was built to fill the gap between auto-trendline drawing and practical retest planning.
Many tools can draw diagonals or detect a break. The harder question is what to do after price returns to the line: is the retest holding, weakening, failing, or still waiting for confirmation?
Trendline Retest Planner supports a decision workflow: identify the active retest, read the score, locate the invalidation edge, compare the target path, and decide what deserves review next.
⚡ Why This Script Is Different
Most trendline tools focus on drawing many lines, ranking confluence, or detecting trendline breaks.
This script does NOT clone Auto Trendline Break Quality, Auto Trendlines MTF - Break/Retest, Trendline Confluence Map, Break-Retest Quality, Structure Retest Planner, Swing Retest Quality, or a generic support/resistance zone map.
Instead, it narrows the workflow to one active support or resistance trendline retest and evaluates whether that retest is constructive or failing. The main output is not a buy or sell signal. It is a decision state: READY, MONITOR, FAILING, INVALIDATED, WATCH, WAIT, or SCAN.
⚙️ Methodology
1. Context Detection
The script builds the latest support and resistance trendline candidates from confirmed swing pivots, then selects the nearest valid retest context.
2. Reference Mapping
It maps the active trendline, a retest pocket around the line, an invalidation edge, and a forward target path.
3. Reaction Evaluation
The 0-100 model scores line age, touch count, retest depth, close response, and volume support.
4. Visual Output
The chart shows the active planning objects, compact state labels, and a clean AGPro decision panel.
🗺️ How to Read the Chart
Trendline = the active support or resistance line being evaluated.
Retest Pocket = the ATR-based area around the trendline where a retest is considered active.
Invalidation Edge = the planning reference where the active retest context is considered broken.
Target Path = a forward guide based on the trendline-to-risk distance.
Labels = compact TEST, READY, MONITOR, WEAK, INVALID, PATH, and sparse context labels.
Colors = teal marks support-side retest context, pink marks resistance-side retest context, amber marks caution, indigo marks monitoring/follow-through, and red marks invalidation.
Panel = the AGPro panel summarizes Trendline Side, Retest Score, Hold State, Risk Edge, and Action.
🚦 Signals & States
• READY → the retest is active, holding on the correct side, and the score is strong enough for structured review.
• MONITOR → the retest is developing, but confirmation or score quality is still incomplete.
• FAILING → price touched the pocket, but the response is weak or on the wrong side.
• INVALIDATED → price crossed the invalidation edge and the active context should be rebuilt.
• WATCH → price is approaching the trendline pocket.
• WAIT → a valid trendline exists, but price is not close enough for useful retest review.
• SCAN → no valid trendline context is active yet.
🔔 Alerts Logic
Alerts trigger when price touches the active retest pocket, when READY state appears, when MONITOR state appears, when a failing retest is detected, when the invalidation edge is crossed, and when follow-through appears after an active retest.
Alerts are attention markers only. They are not trade instructions, automated strategy commands, or outcome promises.
🧩 Confluence Logic
The strongest context appears when the active line is fresh enough, has enough touches, retests with controlled depth, closes back on the correct side, and receives supportive relative volume.
When these components conflict, the panel moves toward MONITOR, FAILING, WATCH, WAIT, or INVALIDATED.
📊 When to Use
• Trendline support retests during constructive pullbacks
• Trendline resistance retests during bearish continuation attempts
• Price-action review after a diagonal support or resistance line is already visible
• Retest planning where invalidation and target path matter
• Liquid markets where pivots, candles, and volume behavior are readable
⚠️ When NOT to Use
• Very low-liquidity symbols with irregular candles
• Extremely noisy micro-timeframes
• News-driven spikes where trendline geometry becomes distorted
• Markets where swing pivots are too compressed to form useful lines
• Situations where the user expects a signal-only or auto-trading tool
🎛️ Key Inputs
• Trendline Side → selects Auto, Support Retest, or Resistance Retest.
• Trendline Pivot Length → controls how confirmed swing anchors are detected.
• Max Trendline Age → controls how old a trendline can be before it is ignored.
• Touch Count Lookback → controls how extra line touches are counted.
• Sensitivity → adjusts retest pocket width and activation distance.
• READY Score → sets the score threshold for stronger review states.
• Label and Panel Font Size → controls chart-label and panel readability.
• Panel Location and Theme → adjusts the AGPro panel layout.
🖥️ Interface & Visual Design
The interface is designed to stay chart-first and decision-led.
The active trendline is the main reference. The retest pocket is drawn around that line with centered text so the chart stays readable. The invalidation edge and target path explain where the planning context weakens and what forward room is being mapped.
The AGPro panel uses a merged blue title row and five compact rows so the user can read side, score, hold state, risk edge, and action quickly.
🧪 Practical Usage Workflow
1. Read the panel state and Retest Score.
2. Check whether price is approaching or touching the retest pocket.
3. Compare current price with the invalidation edge.
4. Review whether the label says TEST, READY, MONITOR, WEAK, INVALID, or PATH.
5. Confirm the broader market context before making any decision.
🔍 Interpretation Guidelines
Think in terms of retest quality, not prediction.
A higher score means multiple retest components align inside the script's rule set. A weaker score means the line may be too old, the retest may be too shallow, too deep, missing a constructive close, or lacking participation.
The script helps organize the review process. It does not replace judgment.
🚫 What This Script Is NOT
• Not a prediction engine
• Not financial advice
• Not an auto-trading system
• Not a guaranteed signal tool
• Not a broad auto-trendline map
• Not a trendline confluence scanner
• Not a break-and-retest scanner
• Not a generic support/resistance zone map
• Not an order block, FVG, or supply/demand tool
⚠️ Limitations & Transparency
• Pivot-based trendlines appear only after pivots are confirmed.
• Scores can vary across symbols, sessions, and timeframes.
• Volume scoring depends on exchange-provided volume data.
• Fast volatility can cross a trendline before a clean retest can be measured.
• In Live Updating mode, active-bar values can change before the bar closes.
🧠 Market Context Notes
Trendline retests are easiest to interpret when liquidity, volatility, and swing structure are readable.
A trendline touch is not enough by itself. Line quality, response, invalidation distance, and target path all matter.
🧾 Use Case Examples
When price returns to an upward support trendline and closes back above the pocket with a high score, the panel may move toward READY.
When price touches a downward resistance trendline but cannot close back below it, the planner may move toward FAILING or INVALIDATED.
When price is near the line but has not touched the pocket yet, the panel can stay in WATCH or WAIT.
🧱 System Philosophy
Trendline Retest Planner follows the AGPro decision-engine approach: identify context, score quality, map risk, show the next action, and keep the chart readable.
It is designed to help traders evaluate a specific planning question instead of adding another generic signal layer.
🔐 Non-Promise Statement
No score, label, alert, or chart object guarantees any market outcome.
The script organizes retest context and highlights conditions for review. It does not provide certainty.
📉 Risk Disclosure
Trading involves risk.
Users remain responsible for their own decisions, position sizing, execution, and risk management.
This script is for educational and analytical purposes only and does not provide financial advice.
📚 Educational Note
Use the planner as a structured reading layer: trendline context first, retest quality second, invalidation and target path third, broader market context always.
Indicator

Target Path Quality [AGPro Series]Target Path Quality
🧠 Core Idea
Is the path toward the next practical target reference clean, blocked, or too risky to review?
📌 Overview / What it does
Target Path Quality is a chart-first target path planning tool built to evaluate the route between current price and a practical target reference.
Instead of drawing a target and implying certainty, the script studies the path itself. It maps a forward path corridor, recent structure blockers, target room, invalidation context, a 0-100 Path Quality score, state labels, alerts, and a clean AGPro decision panel.
It does not predict that a target will be reached, automate execution, print buy/sell commands, or replace broader market context. Its purpose is to help traders judge whether the route toward a target is clean enough to deserve attention.
🎯 Purpose & Design Philosophy
This script was built for traders who already have a directional idea but need a cleaner way to evaluate the target path before focusing on execution.
Many tools draw target levels, projection zones, or take-profit ladders. Those visuals can be useful, but they often skip the more important question: what is between current price and the target?
Target Path Quality fills that gap by converting path cleanliness, blockers, risk edge, target room, volatility fit, and reaction history into one readable decision workflow.
⚡ Why This Script Is Different
Most tools focus on where price could go.
This script does NOT promise a target hit, build a take-profit ladder, or behave like a projection suite.
Instead, it asks whether the route toward the target reference is structurally clean, blocked by recent pivots, too close to justify attention, or too exposed to invalidation risk.
⚙️ Methodology
1. Context Detection
The engine identifies the active path side using EMA context or the user-selected directional mode.
2. Reference Mapping
The script maps a practical target reference, an invalidation review rail, and a forward path corridor.
3. Reaction Evaluation
It evaluates structure blockers, target-room distance, risk edge, trend support, volatility fit, and recent directional reaction history.
4. Visual Output
The result is shown through a centered path corridor label, blocker markers, target/invalidation rails, compact event labels, deterministic alerts, and a premium AGPro panel.
🗺️ How to Read the Chart
Path Corridor = the active review route between current price and the practical target reference. Its label is centered inside the corridor.
Blocker Markers = recent confirmed pivots sitting inside the path. These represent possible structural obstacles.
Target Rail = the practical target reference used for path-quality review. It is not a guaranteed destination.
Invalidation Rail = the risk edge behind the active path. It is an analytical reference, not a stop recommendation.
Labels = compact state markers such as PATH READY, WATCH PATH, BLOCKED PATH, TARGET REVIEW, or INVALID REVIEW.
Colors = teal supports cleaner long-side path quality, pink supports short-side or risk context, amber marks blocker/review states, and indigo marks target-reference context.
Panel = summarizes Path Quality, Blockers, Target Room, Risk Edge, and Action.
🚦 Signals & States
• PATH READY → the path quality score is strong, target room is acceptable, and blockers are limited.
• WATCH PATH → the route is improving but does not meet the strongest review conditions.
• BLOCKED PATH → one or more structure blockers reduce route cleanliness.
• TARGET REVIEW → price has reached the active target reference area and context should be reviewed.
• INVALID REVIEW → price crossed the active invalidation rail and the path should be reassessed.
• WAIT → the current route does not provide enough path quality for active review.
🔔 Alerts Logic
Alerts can trigger when the path becomes ready, enters watch mode, becomes blocked, reaches the target reference review area, or crosses the invalidation review rail.
Each alert is an attention marker. Alerts are not trade instructions, entry commands, exit commands, or automated strategy rules.
🧩 Confluence Logic
Path quality improves when target room is practical, blockers are limited, EMA context supports the active side, volatility is neither too quiet nor overheated, and recent candles show directional reaction history.
When these elements align, the route becomes cleaner. When blockers or invalidation risk rise, the route becomes weaker.
📊 When to Use
• When reviewing a directional setup that already has a target idea
• During breakout continuation review
• During pullback continuation planning
• When comparing whether target room is clean or structurally blocked
• When a trader wants target context without a promise-based target tool
⚠️ When NOT to Use
• Extremely low-liquidity symbols
• Very noisy ranges where pivots form too frequently
• News-driven volatility spikes
• Markets where target references are too close to current price
• Situations where broader context contradicts the active path
🎛️ Key Inputs
• Path Side → controls whether the script evaluates Auto, Long Path, or Short Path context.
• Sensitivity → changes pivot strictness and blocker selectivity.
• Target Path Lookback → controls how far back the script searches for target references and blockers.
• Minimum / Ideal / Maximum Target Room ATR → controls how target room affects the score.
• Max Clean Path Blockers → defines how many blockers are tolerated before the path becomes blocked.
• Label and panel settings → control visibility, location, theme, and font sizes.
🖥️ Interface & Visual Design
The panel follows the AGPro public-release standard with one merged blue header row containing only the panel title.
The chart is designed to stay active without becoming crowded. It uses one main path corridor, up to three blocker markers, target and invalidation rails, and controlled state labels.
Label and panel font sizes are adjustable, with Normal as the default.
🧪 Practical Usage Workflow
1. Read the panel Path Quality score.
2. Check whether blockers appear inside the path corridor.
3. Compare target room against the invalidation rail.
4. Review whether the action state says Path review, Track path, Clear blockers, Review target, or Review risk.
5. Confirm the broader market context before making any independent decision.
🔍 Interpretation Guidelines
A clean path does not mean price must reach the target reference.
A blocked path does not mean price cannot continue.
The script is best read as a route-quality filter. It helps organize whether the path is clean, obstructed, risky, or ready for review.
🚫 What This Script Is NOT
• Not a prediction engine
• Not financial advice
• Not an auto trading system
• Not guaranteed signals
• Not a take-profit ladder
• Not a promise that price will reach any target
⚠️ Limitations & Transparency
Target path quality can change quickly when volatility expands, pivots update, or price crosses a key reference.
Different timeframes may produce different blocker structures and target-room readings.
Low-liquidity or high-noise markets can create unstable path evaluations.
🧠 Market Context Notes
Target path analysis is strongest when combined with liquidity, structure, volatility, and trend context.
A route can look attractive by distance but still become lower quality when recent pivots block the path or the invalidation rail is too exposed.
🧾 Use Case Examples
When price trends upward and the path to the next swing reference is open, the script may show PATH READY.
When a recent pivot high sits between current price and the target reference, the script may show BLOCKED PATH.
When price reaches the target reference rail, the script may show TARGET REVIEW.
When price crosses the invalidation rail behind the path, the script may show INVALID REVIEW.
🧱 System Philosophy
AGPro Series tools are designed to support structured decision review, not emotional signal chasing.
Target Path Quality follows that philosophy by focusing on route cleanliness, blocker context, risk edge, and next-action state instead of a simple directional signal.
🔐 Non-Promise Statement
No target reference is certain.
No path score guarantees continuation.
No alert should be treated as a trade instruction.
📉 Risk Disclosure
Trading involves risk.
Users are responsible for their own decisions, position sizing, risk controls, and market interpretation.
This script is for educational and analytical use only and does not provide financial advice.
📚 Educational Note
Use this tool to study how target path quality changes as blockers appear, target room expands or contracts, and invalidation risk shifts.
The strongest value comes from comparing the path corridor, blocker markers, risk rail, and broader market context together.
Indicator

Trend Stability Ribbon [AGPro Series]Trend Stability Ribbon
🔹 OVERVIEW
Most trend tools tell you WHICH WAY price is going. Trend Stability Ribbon tells you HOW WELL it is getting there. By pairing an ATR-normalized slope engine with a Kaufman path-efficiency score, it projects every bar into one of four rules-based states — Stable Up, Noisy Up, Stable Down, Noisy Down — and paints them onto a clean, adaptive ribbon that stays out of the candles' way. The result is a context layer that separates decisive trending from directional-but-choppy travel, without adding a second indicator pane.
🧭 UNIQUE EDGE — WHY THIS IS NOT "JUST ANOTHER TREND INDICATOR"
Direction alone is cheap. Every moving-average cross, every supertrend, every slope color tells you "up" or "down" — and then leaves you holding the bag when the trend is technically up but structurally a mess.
Trend Stability Ribbon adds the missing second dimension: path quality. The same 34-bar window that defines direction also feeds a Kaufman efficiency calculation (net travel divided by total path travel). An ER near 1.00 means price walked a near-straight line; an ER near 0.00 means it zig-zagged its way to the same point. Mapping that score against a calibrated threshold band produces the four composite states — and a visual language that finally distinguishes "trend worth trusting" from "trend worth fading".
Additional design choices that set it apart:
• Dual-layer event engine — direction flips, stability upgrades, and stability downgrades are tracked as independent transitions, each with its own alert.
• Badge/alert separation — on-chart badges are throttled by a cooldown for visual hygiene, but alerts are always raw so automation pipelines never miss an event.
• Reset state — when the slope-confirmation filter rejects a direction, the ribbon goes neutral instead of flipping false. Chop gets ignored, not misreported.
🧪 METHODOLOGY
1. TREND DIRECTION ENGINE
• A slow EMA (default length 34) anchors the trend path and serves as the ribbon centerline.
• Slope is measured over a 3-bar lookback and normalized by a 14-period ATR, making it instrument-agnostic across crypto, FX, equities, and futures.
• With Slope Confirmation enabled (default), direction is only accepted when price position AND slope agree. Disagreement returns a Reset state.
2. PATH EFFICIENCY (STABILITY) ENGINE
• ER = |close − close | ÷ Σ|close − close | over the same trend window.
• Three classes: Stable (ER ≥ 0.45), Noisy (ER ≤ 0.25), Mixed (between). Thresholds scale with the Stability Sensitivity input.
• The Mixed zone is a deliberate dead-band — during uncertain phases the previous state persists rather than flickering.
3. COMPOSITE STATE MACHINE
• Direction × Stability yields five possible states: Stable Up, Noisy Up, Stable Down, Noisy Down, Reset.
• Bars-in-state is tracked live, giving a simple persistence read on each state.
4. RIBBON RENDERING
• Ribbon is anchored to the EMA centerline with height driven by ATR × a user-selected multiplier (Thin / ATR-Adaptive / Thick).
• Fill opacity and border weight shift by state — Stable states are saturated, Noisy states are faded, Reset is a soft amber.
🔔 SIGNALS & ALERTS
Three transition events are detected and exposed as separate, user-toggled alerts:
• Trend State Flipped — direction changed (Up ↔ Down). Raw, never throttled.
• Stability Improved — path upgraded from Noisy to Stable while direction held. Raw — delivered regardless of badge cooldown.
• Stability Degraded — path downgraded from Stable to Noisy while direction held. Raw — delivered regardless of badge cooldown.
Matching on-chart badges appear at the same moments, subject to the Stability Badge Cooldown for visual cleanliness. Direction-flip badges are never throttled.
⚙️ KEY INPUTS
Engine
• Trend Length (default 34) — lookback for both direction and path-efficiency windows.
• Stability Sensitivity (default 1.0) — scales the Stable / Noisy thresholds.
• Require Slope Confirmation (default on) — enforces price-and-slope agreement; rejects chop.
Ribbon & Badge
• Ribbon Height — Thin / ATR-Adaptive / Thick.
• Show State Badge — toggle on-chart transition labels.
• Label Font Size — tiny / small / normal / large (default normal).
• Minimal Mode — hides panel and badges for pairing with other overlays.
• Stability Badge Cooldown (default 5 bars) — visual throttle for stability transitions.
Info Panel
• Panel Position, Panel Font Size, Efficiency Ratio display, Active Thresholds display.
Alerts
• Independent toggles for each of the three transition events.
🧠 HOW TO USE
• CONTEXT FILTER — use Stable states as a "green light" for continuation setups on your primary system; treat Noisy states as a headwind.
• REGIME BREAKS — a Stability Degraded event mid-trend is often an early warning that the move is maturing, even before price has flipped.
• CLEAN ENTRIES — pair a direction flip (Trend Up / Trend Down) with an immediate Stable classification to filter out whipsaw-prone breakouts.
• CHOP AVOIDANCE — when the ribbon sits in a Reset or Mixed state, the script is telling you the underlying path is not tradeable as a trend. Stand aside or switch to range tactics.
• PAIRING — with Minimal Mode on, the ribbon layers cleanly under structure tools, VWAPs, or S/R zones without visual conflict.
⚠️ LIMITATIONS & TRANSPARENCY
• This is an indicator, NOT a strategy. It does not generate buy or sell orders, has no backtest, and makes no claim of performance.
• Efficiency Ratio is a lagging measure — it describes the path already travelled. The ribbon should be read as context, not as a leading signal.
• The Mixed zone is intentional persistence; expect the composite state to hold through brief chop rather than flipping on every bar.
• Lower timeframes (<5m on thin-liquidity markets) can push ER values into erratic ranges. Start with the defaults on 15m–4h and tune from there.
• All calculations are closed-bar. Intra-bar values may shift until the bar confirms.
🛡️ RISK DISCLOSURE
This script is published for educational and analytical purposes only. It is not financial advice, not a signal service, and not a solicitation to buy or sell any instrument. Past behavior of markets does not predict future results. Always do your own research, apply proper risk management, and consult a licensed professional before making trading decisions. The author assumes no responsibility for losses incurred through use of this indicator. Indicator

Realtime Non-Repaint PathName:
Realtime Non-Repaint Path
Searchable Name:
Realtime Non-Repaint Path
Technical name:
Realtime Non-Repaint Percentage-Reversal Path
Short title:
RT NR Path
Summary
Realtime Non-Repaint Path is a standalone path-visualization and path-state script designed to show live non-repainting directional path structure and a simplified hidden path reveal. It uses a percentage-reversal path model to classify live path direction, maintain a live anchor/candidate structure, draw a live eased path, rebuild a simplified hidden path from reversal pivots, and display state labels, alerts, and a compact status table. Its strongest advantages are live path clarity, non-repainting state transitions on closed bars, simpler path interpretation, and visual structure that can complement entry-focused scripts. Its main known weakness is that it is not a full trading engine: it does not perform full pivot confirmation, trade management, advanced filtering, replay-state reconstruction, or broader regime/stat handling.
This script is best understood as a path-focused operational visualization and state-classification script rather than a complete trading engine. It is designed to be useful on its own while remaining simple enough to inspect, test, and modify.
How it works
The script begins with a simple percentage-reversal path model. It tracks a live anchor price, a live candidate extreme, and a current live path direction. When price moves far enough away from the current anchor by the user-defined reversal percentage, a live directional path is established. As long as price continues making new extremes in that direction, the live candidate continues updating. When price reverses enough from that candidate extreme by the same percentage threshold, the live path flips and a new anchor/candidate cycle begins.
The displayed live path is not drawn as a raw straight jump between points. Instead, it is eased between the current live anchor and live candidate so that the path remains visually readable while still staying tied to the current live state model. Because the live state is updated bar by bar using only information available so far, the live path is intended to function as a non-repainting path-state view on closed bars rather than as a hindsight-only reconstruction.
In addition to the live path, the script can also reveal a simplified hidden path. That hidden path is rebuilt from percentage-reversal pivots over a user-defined recent history window. It detects reversal pivots using the same percentage-reversal logic and then draws an eased pivot-to-pivot hidden path across the selected history range. This keeps the script path-focused, visually useful, and easier to interpret.
The script also displays optional confirmed turn labels, a last-bar live state label, path-up/path-down alerts, background coloring based on current path direction, and a compact status table showing the current live state, anchor, candidate, and percentage distances. These features make it useful as a visual path-state companion script rather than as a full signal-and-execution engine.
Path model note
This script’s path model is based on percentage reversal. That makes it intentionally simpler and easier to understand, but it also means it does not attempt to replicate the broader complexity of a full trading engine. The hidden path shown here should be interpreted as a simplified path reveal, not as a complete trade-selection or execution model.
Features
Live non-repainting path state machine
User-defined percentage reversal threshold
Live anchor and candidate path structure
Eased live path display
Simplified hidden path reveal over recent history
Confirmed path turn labels
Last-bar live state label
Background coloring by live path direction
Path-up and path-down alerts
Compact status table with anchor/candidate/path-distance information
Strengths
Path Clarity edge — provides a cleaner live view of path direction than raw candles alone.
Non-Repainting State edge — live path direction and flips are based on the current bar-by-bar percentage-reversal model rather than hindsight-only reconstruction.
Simplicity edge — simpler structure makes it easier to inspect, test, and modify.
Companion Script edge — pairs naturally with entry-oriented scripts by showing whether path direction is currently up, down, or neutral.
Visual Structure edge — live path, hidden path, labels, background, and status table make path structure easier to read quickly.
Interpretability edge — the script is straightforward enough to be useful as both a live visual aid and a path-study tool.
Weaknesses
Not a full trading engine weakness — does not include full trade management, entry/exit handling, or execution logic.
No advanced filtering weakness — does not include broader filtering or replay/stat reconstruction layers.
Threshold sensitivity weakness — path behavior depends heavily on the user-selected reversal percentage, so different settings can materially change the path and turn structure.
Path-state, not profit-state weakness — path direction does not guarantee profitable entries or strong follow-through.
Simplified hidden path weakness — the hidden path is intentionally simplified and should not be mistaken for a complete internal market model.
No regime/stat engine weakness — does not contain broader regime scoring, detailed replay diagnostics, or a larger state/stat engine.
Who it’s for
This script is best suited for traders and PulseWire users who want a simpler live path script, users interested in non-repainting path direction on closed bars, users who want a visual companion to entry-focused scripts, users who want to inspect market path structure with less complexity than a full trading engine, and users interested in learning from or modifying a smaller path-focused script. It is especially suited for users who want a practical path/state layer rather than a complete trading engine.
Who it’s not for
This script is not best suited for:
users looking for a complete pre-built trading engine
users expecting advanced pre-entry classification
users expecting full entry/exit/trade management
users looking for advanced regime, replay, and state/stat reconstruction
users expecting this script by itself to solve the false-pivot or follow-through problem
users looking for a complete trade-selection and execution workflow rather than a smaller standalone path script
Known limitations
Realtime Non-Repaint Path is much better at showing live path direction and simplified path structure than it is at acting as a complete trading system. The live path is driven by a percentage-reversal state machine and the hidden path is rebuilt from simplified percentage-reversal pivots with eased pivot-to-pivot connections. Because of that, it should be viewed primarily as a path/state visualization and classification script, not as a complete trade-selection or execution engine. Different reversal-percentage settings can also materially change how often the path flips and how sensitive the script is to movement.
Final note
This is a standalone path script, not a guaranteed predictive system and not a full operational trading engine. Its strengths are concentrated in live path visibility, simplified hidden path structure, non-repainting state handling on closed bars, and quick visual interpretation. It is best used as a path-focused companion or as a simpler standalone script for studying live path behavior rather than as a substitute for a more complete engine. Indicator

Seasonality Monte Carlo Forecaster [BackQuant]Seasonality Monte Carlo Forecaster
Plain-English overview
This tool projects a cone of plausible future prices by combining two ideas that traders already use intuitively: seasonality and uncertainty. It watches how your market typically behaves around this calendar date, turns that seasonal tendency into a small daily “drift,” then runs many randomized price paths forward to estimate where price could land tomorrow, next week, or a month from now. The result is a probability cone with a clear expected path, plus optional overlays that show how past years tended to move from this point on the calendar. It is a planning tool, not a crystal ball: the goal is to quantify ranges and odds so you can size, place stops, set targets, and time entries with more realism.
What Monte Carlo is and why quants rely on it
• Definition . Monte Carlo simulation is a way to answer “what might happen next?” when there is randomness in the system. Instead of producing a single forecast, it generates thousands of alternate futures by repeatedly sampling random shocks and adding them to a model of how prices evolve.
• Why it is used . Markets are noisy. A single point forecast hides risk. Monte Carlo gives a distribution of outcomes so you can reason in probabilities: the median path, the 68% band, the 95% band, tail risks, and the chance of hitting a specific level within a horizon.
• Core strengths in quant finance .
– Path-dependent questions : “What is the probability we touch a stop before a target?” “What is the expected drawdown on the way to my objective?”
– Pricing and risk : Useful for path-dependent options, Value-at-Risk (VaR), expected shortfall (CVaR), stress paths, and scenario analysis when closed-form formulas are unrealistic.
– Planning under uncertainty : Portfolio construction and rebalancing rules can be tested against a cloud of plausible futures rather than a single guess.
• Why it fits trading workflows . It turns gut feel like “seasonality is supportive here” into quantitative ranges: “median path suggests +X% with a 68% band of ±Y%; stop at Z has only ~16% odds of being tagged in N days.”
How this indicator builds its probability cone
1) Seasonal pattern discovery
The script builds two day-of-year maps as new data arrives:
• A return map where each calendar day stores an exponentially smoothed average of that day’s log return (yesterday→today). The smoothing (90% old, 10% new) behaves like an EWMA, letting older seasons matter while adapting to new information.
• A volatility map that tracks the typical absolute return for the same calendar day.
It calculates the day-of-year carefully (with leap-year adjustment) and indexes into a 365-slot seasonal array so “March 18” is compared with past March 18ths. This becomes the seasonal bias that gently nudges simulations up or down on each forecast day.
2) Choice of randomness engine
You can pick how the future shocks are generated:
• Daily mode uses a Gaussian draw with the seasonal bias as the mean and a volatility that comes from realized returns, scaled down to avoid over-fitting. It relies on the Box–Muller transform internally to turn two uniform random numbers into one normal shock.
• Weekly mode uses bootstrap sampling from the seasonal return history (resampling actual historical daily drifts and then blending in a fraction of the seasonal bias). Bootstrapping is robust when the empirical distribution has asymmetry or fatter tails than a normal distribution.
Both modes seed their random draws deterministically per path and day, which makes plots reproducible bar-to-bar and avoids flickering bands.
3) Volatility scaling to current conditions
Markets do not always live in average volatility. The engine computes a simple volatility factor from ATR(20)/price and scales the simulated shocks up or down within sensible bounds (clamped between 0.5× and 2.0×). When the current regime is quiet, the cone narrows; when ranges expand, the cone widens. This prevents the classic mistake of projecting calm markets into a storm or vice versa.
4) Many futures, summarized by percentiles
The model generates a matrix of price paths (capped at 100 runs for performance inside PulseWire), each path stepping forward for your selected horizon. For each forecast day it sorts the simulated prices and pulls key percentiles:
• 5th and 95th → approximate 95% band (outer cone).
• 16th and 84th → approximate 68% band (inner cone).
• 50th → the median or “expected path.”
These are drawn as polylines so you can immediately see central tendency and dispersion.
5) A historical overlay (optional)
Turn on the overlay to sketch a dotted path of what a purely seasonal projection would look like for the next ~30 days using only the return map, no randomness. This is not a forecast; it is a visual reminder of the seasonal drift you are biasing toward.
Inputs you control and how to think about them
Monte Carlo Simulation
• Price Series for Calculation . The source series, typically close.
• Enable Probability Forecasts . Master switch for simulation and drawing.
• Simulation Iterations . Requested number of paths to run. Internally capped at 100 to protect performance, which is generally enough to estimate the percentiles for a trading chart. If you need ultra-smooth bands, shorten the horizon.
• Forecast Days Ahead . The length of the cone. Longer horizons dilute seasonal signal and widen uncertainty.
• Probability Bands . Draw all bands, just 95%, just 68%, or a custom level (display logic remains 68/95 internally; the custom number is for labeling and color choice).
• Pattern Resolution . Daily leans on day-of-year effects like “turn-of-month” or holiday patterns. Weekly biases toward day-of-week tendencies and bootstraps from history.
• Volatility Scaling . On by default so the cone respects today’s range context.
Plotting & UI
• Probability Cone . Plots the outer and inner percentile envelopes.
• Expected Path . Plots the median line through the cone.
• Historical Overlay . Dotted seasonal-only projection for context.
• Band Transparency/Colors . Customize primary (outer) and secondary (inner) band colors and the mean path color. Use higher transparency for cleaner charts.
What appears on your chart
• A cone starting at the most recent bar, fanning outward. The outer lines are the ~95% band; the inner lines are the ~68% band.
• A median path (default blue) running through the center of the cone.
• An info panel on the final historical bar that summarizes simulation count, forecast days, number of seasonal patterns learned, the current day-of-year, expected percentage return to the median, and the approximate 95% half-range in percent.
• Optional historical seasonal path drawn as dotted segments for the next 30 bars.
How to use it in trading
1) Position sizing and stop logic
The cone translates “volatility plus seasonality” into distances.
• Put stops outside the inner band if you want only ~16% odds of a stop-out due to noise before your thesis can play.
• Size positions so that a test of the inner band is survivable and a test of the outer band is rare but acceptable.
• If your target sits inside the 68% band at your horizon, the payoff is likely modest; outside the 68% but inside the 95% can justify “one-good-push” trades; beyond the 95% band is a low-probability flyer—consider scaling plans or optionality.
2) Entry timing with seasonal bias
When the median path slopes up from this calendar date and the cone is relatively narrow, a pullback toward the lower inner band can be a high-quality entry with a tight invalidation. If the median slopes down, fade rallies toward the upper band or step aside if it clashes with your system.
3) Target selection
Project your time horizon to N bars ahead, then pick targets around the median or the opposite inner band depending on your style. You can also anchor dynamic take-profits to the moving median as new bars arrive.
4) Scenario planning & “what-ifs”
Before events, glance at the cone: if the 95% band already spans a huge range, trade smaller, expect whips, and avoid placing stops at obvious band edges. If the cone is unusually tight, consider breakout tactics and be ready to add if volatility expands beyond the inner band with follow-through.
5) Options and vol tactics
• When the cone is tight : Prefer long gamma structures (debit spreads) only if you expect a regime shift; otherwise premium selling may dominate.
• When the cone is wide : Debit structures benefit from range; credit spreads need wider wings or smaller size. Align with your separate IV metrics.
Reading the probability cone like a pro
• Cone slope = seasonal drift. Upward slope means the calendar has historically favored positive drift from this date, downward slope the opposite.
• Cone width = regime volatility. A widening fan tells you that uncertainty grows fast; a narrow cone says the market typically stays contained.
• Mean vs. price gap . If spot trades well above the median path and the upper band, mean-reversion risk is high. If spot presses the lower inner band in an up-sloping cone, you are in the “buy fear” zone.
• Touches and pierces . Touching the inner band is common noise; piercing it with momentum signals potential regime change; the outer band should be rare and often brings snap-backs unless there is a structural catalyst.
Methodological notes (what the code actually does)
• Log returns are used for additivity and better statistical behavior: sim_ret is applied via exp(sim_ret) to evolve price.
• Seasonal arrays are updated online with EWMA (90/10) so the model keeps learning as each bar arrives.
• Leap years are handled; indexing still normalizes into a 365-slot map so the seasonal pattern remains stable.
• Gaussian engine (Daily mode) centers shocks on the seasonal bias with a conservative standard deviation.
• Bootstrap engine (Weekly mode) resamples from observed seasonal returns and adds a fraction of the bias, which captures skew and fat tails better.
• Volatility adjustment multiplies each daily shock by a factor derived from ATR(20)/price, clamped between 0.5 and 2.0 to avoid extreme cones.
• Performance guardrails : simulations are capped at 100 paths; the probability cone uses polylines (no heavy fills) and only draws on the last confirmed bar to keep charts responsive.
• Prerequisite data : at least ~30 seasonal entries are required before the model will draw a cone; otherwise it waits for more history.
Strengths and limitations
• Strengths :
– Probabilistic thinking replaces single-point guessing.
– Seasonality adds a small but meaningful directional bias that many markets exhibit.
– Volatility scaling adapts to the current regime so the cone stays realistic.
• Limitations :
– Seasonality can break around structural changes, policy shifts, or one-off events.
– The number of paths is performance-limited; percentile estimates are good for trading, not for academic precision.
– The model assumes tomorrow’s randomness resembles recent randomness; if regime shifts violently, the cone will lag until the EWMA adapts.
– Holidays and missing sessions can thin the seasonal sample for some assets; be cautious with very short histories.
Tuning guide
• Horizon : 10–20 bars for tactical trades; 30+ for swing planning when you care more about broad ranges than precise targets.
• Iterations : The default 100 is enough for stable 5/16/50/84/95 percentiles. If you crave smoother lines, shorten the horizon or run on higher timeframes.
• Daily vs. Weekly : Daily for equities and crypto where month-end and turn-of-month effects matter; Weekly for futures and FX where day-of-week behavior is strong.
• Volatility scaling : Keep it on. Turn off only when you intentionally want a “pure seasonality” cone unaffected by current turbulence.
Workflow examples
• Swing continuation : Cone slopes up, price pulls into the lower inner band, your system fires. Enter near the band, stop just outside the outer line for the next 3–5 bars, target near the median or the opposite inner band.
• Fade extremes : Cone is flat or down, price gaps to the upper outer band on news, then stalls. Favor mean-reversion toward the median, size small if volatility scaling is elevated.
• Event play : Before CPI or earnings on a proxy index, check cone width. If the inner band is already wide, cut size or prefer options structures that benefit from range.
Good habits
• Pair the cone with your entry engine (breakout, pullback, order flow). Let Monte Carlo do range math; let your system do signal quality.
• Do not anchor blindly to the median; recalc after each bar. When the cone’s slope flips or width jumps, the plan should adapt.
• Validate seasonality for your symbol and timeframe; not every market has strong calendar effects.
Summary
The Seasonality Monte Carlo Forecaster wraps institutional risk planning into a single overlay: a data-driven seasonal drift, realistic volatility scaling, and a probabilistic cone that answers “where could we be, with what odds?” within your trading horizon. Use it to place stops where randomness is less likely to take you out, to set targets aligned with realistic travel, and to size positions with confidence born from distributions rather than hunches. It will not predict the future, but it will keep your decisions anchored to probabilities—the language markets actually speak. Indicator

FunctionSMCMCLibrary "FunctionSMCMC"
Methods to implement Markov Chain Monte Carlo Simulation (MCMC)
markov_chain(weights, actions, target_path, position, last_value) a basic implementation of the markov chain algorithm
Parameters:
weights : float array, weights of the Markov Chain.
actions : float array, actions of the Markov Chain.
target_path : float array, target path array.
position : int, index of the path.
last_value : float, base value to increment.
Returns: void, updates target array
mcmc(weights, actions, start_value, n_iterations) uses a monte carlo algorithm to simulate a markov chain at each step.
Parameters:
weights : float array, weights of the Markov Chain.
actions : float array, actions of the Markov Chain.
start_value : float, base value to start simulation.
n_iterations : integer, number of iterations to run.
Returns: float array with path. Library

MathSearchDijkstraLibrary "MathSearchDijkstra"
Shortest Path Tree Search Methods using Dijkstra Algorithm.
min_distance(distances, flagged_vertices) Find the lowest cost/distance.
Parameters:
distances : float array, data set with distance costs to start index.
flagged_vertices : bool array, data set with visited vertices flags.
Returns: int, lowest cost/distance index.
dijkstra(matrix_graph, dim_x, dim_y, start) Dijkstra Algorithm, perform a greedy tree search to calculate the cost/distance to selected start node at each vertex.
Parameters:
matrix_graph : int array, matrix holding the graph adjacency list and costs/distances.
dim_x : int, x dimension of matrix_graph.
dim_y : int, y dimension of matrix_graph.
start : int, the vertex index to start search.
Returns: int array, set with costs/distances to each vertex from start vertexs.
shortest_path(start, end, matrix_graph, dim_x, dim_y) Retrieves the shortest path between 2 vertices in a graph using Dijkstra Algorithm.
Parameters:
start : int, the vertex index to start search.
end : int, the vertex index to end search.
matrix_graph : int array, matrix holding the graph adjacency list and costs/distances.
dim_x : int, x dimension of matrix_graph.
dim_y : int, y dimension of matrix_graph.
Returns: int array, set with vertex indices to the shortest path. Library

Indicator
