Indicatore

Market Structure Break BOS Classifier Market Structure Break — BOS Classifier
A clean, no-noise market structure indicator that goes beyond simply marking a BOS. Every break is classified by context so you immediately know whether to act on it or skip it.
🔵 What Makes This Different
Most BOS indicators fire the same label regardless of market context. This one answers the question that actually matters — was that break meaningful, or was it just noise inside a range?
Every Break of Structure is classified into one of three types:
📊 Signal Types
✔ Valid BOS (Green/Red — solid line)
Price closes above the previous swing high (bullish) or below the previous swing low (bearish) while outside a consolidation zone. This is a clean, high-confidence structural break. Fires on the exact candle of the break — no lag.
⚠ Range BOS (Yellow — dashed line)
Same close-cross condition, but price was inside a consolidation zone when it happened. These breaks are more likely to be fakeouts. Treat with caution — wait for a retest or additional confirmation before entry.
〰 iBOS — Internal BOS (Lime/Red — dashed line)
The short-term zigzag trend flips direction but the higher-level market structure has not changed. This is a minor internal move within the prevailing trend. Useful for spotting early reversals, but not a tradeable structure break on its own.
🟠 Consolidation / Range Detection
The indicator automatically detects when price is forming a lower high AND higher low relative to the prior swing — the classic compression signature. When active:
Background is highlighted in orange
A dashed boundary box shows the exact range with top and bottom levels
Any BOS fired during this phase is automatically tagged as a Range BOS
⚙️ How It Works Internally
Zigzag engine builds swing highs (h0, h1) and swing lows (l0, l1)
Valid/Range BOS → fires when close crosses h1 or l1 on the break candle (leading — no confirmation lag)
iBOS → fires when trend variable flips but market variable does not
Consolidation → h0 < h1 AND l0 > l1 simultaneously
🛠 Settings
SettingDescriptionZigZag LengthControls swing sensitivity. Higher = fewer, larger swingsFib FactorMinimum move required to confirm a structural break (0–1)Show Consolidation ZoneToggle the range box and background highlightShow Valid BOSToggle clean outside-range BOS signalsShow Range BOSToggle inside-range BOS signalsShow iBOSToggle internal minor structure flipsText SizeTiny / Small / Normal / Large / Huge
🔔 Alerts Available
✔ Valid BOS Bullish — clean break above swing high outside range
✔ Valid BOS Bearish — clean break below swing low outside range
⚠ Range BOS Bullish — break above swing high from inside consolidation
⚠ Range BOS Bearish — break below swing low from inside consolidation
iBOS Bullish — internal flip inside bearish structure
iBOS Bearish — internal flip inside bullish structure
Consolidation Start — market entered a range zone
📌 Recommended Usage
Use on your HTF bias timeframe (1H, 4H) to identify the market state
A Valid BOS in the direction of your bias = structure is with you
A Range BOS = wait for the retest of the broken level before committing
An iBOS inside a trending market = potential early entry signal in the direction of the trend, not against it
When the Consolidation zone is active, reduce position size or wait for a clean Valid BOS breakout before trading
⚠️ Disclaimer
This indicator is for educational and analytical purposes only. It does not constitute financial advice. Past performance of any signal is not indicative of future results. Always use proper risk management.
Based on original MSB-OB structure by © EmreKb. Extended with consolidation detection, BOS classification, and leading signal logic. Indicatore

ontagion & Shock System (CSS) - Systemic Risk TrackerThe Contagion & Shock System (CSS) is an advanced quantitative indicator designed to measure systemic risk and sector contagion in real-time. Instead of looking at a single asset in isolation, this system tracks how sudden price shocks ripple across a configurable basket of proxy assets, helping traders identify true macro risk-on or risk-off environments.
1. Shock Detection
The system continuously monitors the base asset for sudden volatility spikes. It triggers an active "Shock" if a single bar exceeds a specific percentage threshold, or if a cumulative multi-bar move indicates sustained, aggressive buying or selling pressure.
2. Dynamic Correlation Engine (Wave Assignment)
The indicator runs a live Pearson Correlation (using log returns) between your base chart and 10 configurable proxy assets (e.g., SPY, QQQ, VIX, XLF). It automatically buckets these assets into three contagion waves:
Wave 1 (Immediate Impact): Correlation >= 0.70
Wave 2 (Lagging Impact): Correlation >= 0.40
Wave 3 (Distant/Isolated): Correlation < 0.40
3. Contagion Pressure Index (CPI)
Displayed as a central histogram, the CPI aggregates the correlation strength and directional movement of all 10 proxies. A positive score indicates risk-on contagion (assets are rising together), while a negative score indicates risk-off contagion (assets are falling together).
4. Systemic Risk Score (0-100)
Located in the dashboard, this gauge blends the magnitude of the CPI, the number of assets currently caught in Wave 1, and the recency of the last price shock. A score above 80 indicates severe market-wide stress.
Users can fully customize the shock thresholds, cumulative lookback windows, correlation lengths, and all 10 proxy tickers via the indicator settings to tailor the system to specific sectors or asset classes. Indicatore

Indicatore

Indicatore

Indicatore

Indicatore

Candle Fingerprint [TradingIQ]Hello Traders!
🔹 Candle Fingerprint
Candle Fingerprint is a pattern-based analysis tool designed to study how price has typically behaved after specific candle structures.
Instead of treating candles as isolated events, this tool compares current candles to historical ones and shows what has usually happened next in similar situations .
Think of it as a way to find historical matches and outcomes for the current candle , not as a fixed prediction engine.
finds candles with similar structure in the past
compares body size, wicks, volatility, and close position
tracks whether price typically continued or reversed
shows continuation vs reversal rates
displays typical move after similar candles
optional streak-based behavior analysis
🔹 What the tool shows
🔸 Candle similarity matching
The script analyzes the current candle and searches historical data for candles with similar structure.
It compares multiple components such as body size, wick proportions, volatility, and where the candle closed within its range.
This helps reveal:
which past candles looked similar to the current one
how those candles behaved afterward
whether similar setups tended to continue or reverse
Instead of assuming what a candle means, you get a historical reference for how similar structures have behaved before .
🔸 Continuation vs reversal behavior
Once similar candles are found, the script tracks what happened next.
It calculates how often price continued in the same direction versus reversing.
This allows you to see:
whether continuation or reversal has been more common
the relative strength of that tendency
how consistent the behavior has been across samples
This provides context around the current candle, rather than a guaranteed outcome.
🔸 Typical move after the candle
In addition to direction, the script measures how far price typically moved after similar candles.
It calculates median moves for both continuation and reversal scenarios.
This helps show:
the typical size of follow-through moves
the difference between continuation and reversal magnitude
how strong or weak reactions have been historically
This is not about predicting an exact move, but about understanding what has commonly happened in the past .
🔸 Visual similarity mapping
The script highlights the most similar historical candles directly on the chart.
This gives a visual reference for how past setups formed and evolved.
This helps you:
see real examples of similar price behavior
compare structure side by side
understand how the current setup fits into historical context
🔸 Candle streak model
In addition to similarity, the script includes a streak-based model that tracks sequences of consecutive up or down closes.
This allows you to analyze:
what has typically happened after multiple up closes
what has typically happened after multiple down closes
how continuation vs reversal tendencies shift with streak length
This provides a different lens focused on momentum sequences rather than structure .
🔸 Confidence context
The tool evaluates how reliable the observed behavior is based on sample size and consistency.
This helps you understand:
whether the data is meaningful or limited
how much weight to give the observation
when patterns appear more or less stable
🔹 How to read it
Each component gives a different layer of insight:
Candle structure → what the current candle looks like
Similarity matches → where this pattern appeared before
Continuation rate → how often price continued
Reversal rate → how often price reversed
Typical move → how far price typically moved afterward
Streak context → how sequences of candles have behaved
🔹 Why this tool is useful
It gives you:
a structured way to compare current candles to historical ones
context for whether a setup has tended to continue or reverse
typical move expectations based on past behavior
a data-driven alternative to subjective candle interpretation
multiple perspectives using both structure and streak behavior
🔹 Best use cases
analyzing individual candle behavior
comparing current setups to historical patterns
studying continuation vs reversal tendencies
understanding momentum through candle streaks
adding contextual data to price action analysis
🔹 Important note
This tool is based entirely on historical observations and pattern matching.
That means:
it reflects past behavior, not guaranteed outcomes
it should not be treated as a predictive or deterministic model
similar candles can still produce different results
outputs are best used as context, not certainty
🔹 Inputs you can customize
The script includes flexible controls such as:
model selection (similarity or streak)
candle selection method
table display and positioning
similarity weighting (body, wicks, volatility, close)
history table settings
visual offset and layout
Closing Notes
Candle Fingerprint is built to shift the focus from what a candle looks like to how similar candles have behaved historically .
It does not attempt to predict the future, but instead provides a structured view of what has typically happened in comparable situations , allowing you to make more informed, contextual decisions.
Thank you for checking it out! Indicatore

Settlement Cycle VWAP Ladder [TechnicalZen]Must have in a technical trader's toolkit! Four volume-weighted anchors stacked across derivatives-expiry horizons for all major markets.
What This Is
A multi-horizon VWAP reference stack, anchored to the settlement calendar of your chosen market (options and futures expiry dates). Four volume-weighted levels — monthly, weekly, week-to-date, and session — rendered on the price pane with a 20-bar historical table showing how each has evolved.
The indicator does NOT guess or lag. It computes hard reference levels from actual volume and price, snaps them to real expiry dates (last Thursday for NSE, third Friday for Europe, etc.), and prints them as step-lines and accumulating curves on your chart.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
What It Does — The Four Ladders
Monthly Anchor — N-day VWMA (default 20-day) whose value is snapped on the monthly expiry day and held flat until the next monthly expiry. This is your longest-horizon volume-weighted reference, updating once a month.
Weekly Anchor — N-day VWMA (default 5-day) snapped every weekly expiry day. Updates once a week. Between expiries it's a flat step-line — deliberately so, because that's what makes it useful as a reference level.
Week-to-Date VWAP — true cumulative VWAP accumulating bar-by-bar through the trading week. Resets the day AFTER weekly expiry (Friday for US / Europe, Monday for NSE Thursday-expiry, Wednesday for BSE Tuesday-expiry). Shows where volume-weighted consensus is building during the current cycle.
Session VWAP — classic daily VWAP, resets at each session open. Tightest anchor, your intraday fair-value line.
Stacked, these four tell you where price sits relative to volume-weighted consensus at every horizon: intraday → this week → this month → longer term. When price respects all four from one side, you have a strong directional bias. When price oscillates around the tight ones while respecting the wider ones, you have a range.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Market Presets — Derivatives Expiry Conventions Built In
Expiry days differ by market. Pick a preset and everything calibrates:
US Standard (3rd Friday) — SPX, NDX, S&P options, most index futures
US EOM (Last Friday) — SPX / SPY end-of-month options
Europe (3rd Friday) — DAX, FTSE 100, EURO STOXX 50, CAC 40, SMI, IBEX 35, AEX
India NSE (Last Thursday) — NIFTY, Bank NIFTY, stock futures, stock options
India BSE (Last Tuesday) — SENSEX, BANKEX
Custom — pick any weekday + "Third" or "Last" rule manually
Selecting the right preset sets the weekly snap day, the monthly snap rule (third vs last occurrence in the month), AND the week-start day for the Week-to-Date accumulator — so your "week" aligns with the actual options cycle.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
How to Use It
Load with defaults. Pick the market preset that matches your instrument.
Read price relative to the four ladders:
Above all four = strong volume-weighted uptrend across all horizons
Below all four = strong downtrend
Mixed (above some, below others) = transitional
Oscillating around tight (Session, WTD) while respecting wide (Weekly, Monthly) = range within bigger trend
Use the Monthly and Weekly anchors as support / resistance levels — they're where institutions mark to market at expiry.
Use the Week-to-Date VWAP as an intra-cycle fair value — price far above it = stretched bullish, far below = stretched bearish.
Use the Session VWAP as intraday mean — a classic reversion magnet.
Consult the history table for quick reference to recent values of all four, with date headers showing exactly which bar each column represents.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Main Features
Six market presets plus Custom mode for any derivatives expiry convention worldwide
Four stacked VWAP horizons — monthly, weekly, WTD, session — each independently togglable
Session-aware for futures — NQ, ES, CL, GC and other overnight-session instruments correctly identify their trading date via time_close("D"), so Friday's expiry snap lands on Friday even when the session starts Thursday evening
Date-headered history table — 20 columns of recent values, auto-formatted (HH:mm on intraday, dd MMM on daily+)
Adjustable text sizes — Tiny / Small / Normal / Large / Huge for both data cells and headers
Direction-aware colors — each cell and plot line shows bar-over-bar direction at a glance
Step-line plots with diamonds for the snapshot-held anchors (Monthly, Weekly); circles for WTD; continuous line for Session
Same-timeframe bug resolved — on D charts, VWMAs compute locally to avoid the 1-bar lookahead-off delay that `request.security` introduces; on sub-daily charts, `request.security` uses `lookahead_on` so intraday bars see today's evolving daily VWMA
NA guards — anchors never get clobbered by na on the first snap if chart history is short; they simply stay blank until a valid snap fires
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Key Settings
Market Preset — dropdown of expiry conventions (see above)
Monthly VWMA length (days) — default 20
Weekly VWMA length (days) — default 5
Source — price used for VWMA and cumulative calcs (default close)
Show Monthly / Weekly / WTD / Session — four independent plot toggles
Show History Table + position + column count
Data Cell Text Size / Header/Label Text Size — both adjustable
Custom: Monthly Rule — Third or Last (used only when Market Preset = Custom)
Custom: Expiry Weekday — Mon / Tue / Wed / Thu / Fri (used only when Market Preset = Custom)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Session-Aware Design
Cash equities (TSLA, AAPL, SPY) have a daily bar that sits squarely on the trading date. Futures (NQ, ES, CL) have an overnight session that starts the previous calendar evening. Most VWAP indicators that use `dayofweek(time)` get NQ wrong — they read Friday's session as Thursday because that's when it started.
This indicator uses `time_close("D")`, which always resolves to the trading date's session close — correct for both cash equities and overnight-session futures. No manual configuration needed; it just works on whatever symbol you load.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Disclaimer
This is a visualization and analytical tool, not financial advice or a signal service. VWAP levels are reference points — they do not guarantee reversals, breakouts, or any specific market behavior. Past price reactions at these levels do not guarantee future ones. Trade with your own risk management. Every trade can lose.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Four volume-weighted anchors. One chart.
— TechnicalZen
Indicatore

Regime Transition Intelligence [AGPro Series]Regime Transition Intelligence
Most regime scripts answer a single question: "what regime are we in right now?". Regime Transition Intelligence is designed to answer a different, more actionable set of questions: how long does this regime usually last, how close to its typical end is it, how likely is it to flip within the next N bars, and where does it historically go when it does flip. Instead of treating the current regime as a standalone snapshot, it builds a living, self-calibrating statistical profile of the symbol's own regime behavior and presents it in a compact on-chart dashboard.
The engine runs on three independent axes — Trend Strength (Kaufman Efficiency Ratio + ADX), Chop Risk (Choppiness Index + inverse trend), and Volatility (ATR% normalized over a user-defined lookback). Each axis is classified as LOW / MID / HIGH, either with fixed 33/67 thresholds or with an adaptive percentile rank engine that learns the symbol's own statistical envelope over a rolling window. The three axes are then combined into a discrete regime state: TREND, MIXED, or RANGE / CHOP.
🟦 Overview / What it does
Regime Transition Intelligence is a single-pane overlay indicator that continuously classifies the market into one of three regimes and then layers a full transition intelligence stack on top of that classification:
- A per-regime dwell-time distribution learned from the chart's own completed regime blocks
- A Bayesian-style flip probability that answers "how likely is a regime change within the next N bars, given the current age"
- A 3x3 transition matrix that ranks the most likely next regime with a secondary fallback
- A fatigue score comparing the current regime's age to its historical mean (FRESH / MATURE / EXTENDED)
- A confidence decay tracker that shows whether conviction is BUILDING, STABLE, or FADING within the current regime block
- A compact history ribbon showing the last completed regime blocks with their durations
- Higher-timeframe alignment with a SYNC / DIV indicator and a live beacon at the right edge of the chart
All of this is delivered inside a single configurable dashboard, a directional transition marker layer on the chart, optional regime tint and candle coloring, and a right-edge beacon summarizing the current state.
🟣 Unique Edge / Why it is not a basic mashup
Standard regime indicators report the current state and stop there. Regime Transition Intelligence adds six distinct statistical layers that together form a transition-aware view:
1. Dwell Time Statistics — the script stores every completed regime block in a rolling array (configurable depth) and continuously updates running mean, running variance, running max, and running count per regime code. Statistics are only shown after a minimum number of blocks per regime have been collected, so the user always knows when the sample size is still too small.
2. Exponential Hazard Flip Probability — the baseline flip probability uses P(flip within H bars) = 1 - exp(-H / mean), a standard survival-analysis construction assuming constant hazard. The result is then fatigue-adjusted: if the current age is far above the historical mean, the probability is boosted; if the regime has just started, the probability is damped. The final value is capped at 95% to avoid certainty claims.
3. Transition Matrix — a 3x3 counter records every observed regime transition and is read as a conditional distribution: "given the current regime ends, which regime is it most likely to move to, and what is the runner-up". Both the top candidate and the secondary candidate are displayed with their percentages.
4. Fatigue Score — the ratio of the current age to the historical mean is bucketed into three zones (FRESH, MATURE, EXTENDED) using user-configurable thresholds. It tells the user whether the current regime is still in its early lifecycle or already past its typical end.
5. Confidence Decay Tracker — conviction in the current regime is sampled at the start of each new block and compared to the current conviction. The delta is classified as BUILDING, STABLE, or FADING, which gives an early read on whether the regime is strengthening or losing its grip.
6. History Ribbon — the last N completed regime blocks are compressed into a single compact line such as "C2·M4·C8·M1·M7*", where letters are regime codes and numbers are bar counts, with the current block marked by an asterisk. It gives immediate context on recent regime rhythm at a single glance.
None of these layers is a repackaged classic indicator. They are built on top of a trend / chop / volatility engine but deliver information that is categorically different from a simple "regime yes / no" readout.
🟢 Methodology / Conceptual data flow
1. Feature extraction. Kaufman Efficiency Ratio (net move over lookback divided by summed absolute moves) and normalized ADX are combined into a trend score. The Choppiness Index is normalized against its operating range and blended with inverse trend to produce a chop score. ATR as a percentage of price is normalized against its own lookback min/max to produce a volatility score.
2. Classification. Each score is mapped to LOW / MID / HIGH using either fixed thresholds (Static mode) or percentile rank over an adaptive lookback (Adaptive mode). The three bands are combined into a discrete regime state: TREND when trend is HIGH and chop is LOW, RANGE / CHOP when chop is HIGH, and MIXED otherwise.
3. Block tracking. Every time the regime state changes on a confirmed bar, the previous block is closed: its duration is pushed to a rolling history array and added to the running sum / sum-of-squares / count / max for its regime code. When the history array exceeds its configured depth, the oldest block is popped and its contribution is subtracted from the running totals, which keeps the statistics adaptive and non-expanding.
4. Transition matrix update. When a block closes into a new regime, the 3x3 counter is incremented at the corresponding cell, and the row total is incremented. The conditional distribution for the current regime is read from its row at display time.
5. Statistical outputs. Mean dwell, fatigue ratio, exponential-hazard flip probability, fatigue-adjusted flip probability, top and secondary next regimes, and confidence delta are all derived from the running state and rendered into the dashboard.
6. Higher-timeframe alignment. The same three-axis engine is run on a user-selected higher timeframe via request.security and compared against the current-timeframe regime; the result appears as SYNC or DIV in the header and as an optional HTF row in the dashboard.
🔔 Signals & Alerts / Interpretation
Regime Transition Intelligence is a state-mapping and statistical context tool rather than a directional buy / sell engine. The main on-chart events are:
- Regime Shift — fires when the regime state changes on a confirmed bar
- High Flip Probability — fires when the fatigue-adjusted flip probability crosses a high threshold
- Regime Fatigue Extended — fires on the transition into the EXTENDED fatigue zone
- Confidence Fading — fires on the transition into the FADING confidence zone
How to read the panel:
- Summary + Age tells the user which regime is active and how long it has been active.
- Dwell Context compares the current age to the historical mean in the form "age / mean · % of typical lifespan".
- Fatigue summarizes that comparison as FRESH, MATURE, or EXTENDED.
- Flip Probability reports the statistical odds of a regime change within the user-defined horizon.
- Next Likely names the most probable next regime with its percentage and a secondary fallback.
- Confidence and Conf Decay together tell the user whether the current read is reliable and whether conviction is rising or fading.
- History gives quick situational awareness of recent regime rhythm.
None of these rows should be interpreted as a trade instruction. They are a context layer meant to be combined with the user's own structure and entry framework.
🎛️ Key Inputs
Regime Engine Core — Trend Persistence Length, DMI/ADX Length, Chop Length, ATR Length, Volatility Normalize Lookback.
Adaptive Boundaries — Band Classification Mode (Adaptive / Static), Adaptive Lookback, Adaptive Low / High Percentile.
Transition Intelligence — Regime History Depth, Flip Probability Horizon, Min Blocks Before Stats Activate, Fatigue Fresh / Extended thresholds.
HUD — Display Mode (PRO / MINIMAL), HUD Position, Text Size, transparency controls, individual row toggles, history ribbon length.
Add-ons — Chart Regime Tint, Regime Candle Coloring (Soft / Strong), HTF Peek Timeframe, Transition Markers (location, cooldown, stagger, size, ATR offset), Live Regime Beacon (position, size, stats toggle).
🧭 How to use
1. Add the script to any chart and timeframe. The engine is tuned to work from 15m up to Daily; very low timeframes on illiquid instruments can produce unstable regime blocks and are not the intended use case.
2. Give the script time to collect blocks. Statistics stay in N/A until the configured minimum number of completed blocks per regime has accumulated. On a fresh chart or an illiquid instrument this is expected behavior, not a bug.
3. Read the dashboard top-down. Start with the three axis rows to understand the current market shape, then move to Summary and Age to see what is active and for how long, then use Dwell / Fatigue / Flip / Next Likely to place the current regime inside its historical distribution, and finally use Conf Decay and HTF to sanity-check reliability and alignment.
4. Treat EXTENDED fatigue and high flip probability as context, not as a reversal signal. Regimes can remain in the EXTENDED zone for a while before actually flipping; the statistical profile is descriptive, not deterministic.
5. Combine with structural context. The script does not know about support / resistance, order blocks, or news. It only knows about the symbol's own regime rhythm. Use it as a regime-aware filter on top of the user's existing framework.
⚠️ Limitations & Transparency
This is not a strategy and not a complete trading system. It does not predict price direction and does not generate buy or sell signals. All statistics are estimated from a rolling history of the chart's own regime blocks, so they are sensitive to the chosen engine parameters, the timeframe, and the symbol; different timeframes and different instruments will produce different statistical profiles, and that is by design.
The exponential-hazard flip probability assumes a constant hazard within the current regime, which is a simplification. Real-world regime durations are not perfectly memoryless and the fatigue multiplier is a heuristic correction, not a formal model. The probability is capped at 95% on purpose, because even a heavily aged regime cannot be considered a certainty and the script deliberately avoids certainty language.
The transition matrix is read as a conditional frequency over completed blocks; it is informative about the symbol's own past behavior and should not be interpreted as a forward-looking forecast. Very small samples produce unstable conditional probabilities, which is why stats stay in N/A until a minimum number of blocks is collected.
Regime classification itself reacts to confirmed bars and can change as new data arrives, which is expected for any regime filter. Users who prefer fully non-repainting alerts should rely on the barstate.isconfirmed-gated alert conditions provided.
📜 Risk Disclosure
Trading involves substantial risk of loss and is not suitable for every investor. Past performance is not indicative of future results. This indicator is provided for educational and analytical purposes only and should not be interpreted as financial advice, an investment recommendation or a solicitation to trade. Always combine multiple forms of analysis, manage position size responsibly, and never risk capital you cannot afford to lose. Indicatore

Swap Engine - Pair Rotation (Z-Score) [AGPro Series]Swap Engine - Pair Rotation (Z-Score)
🔷 OVERVIEW
Swap Engine - Pair Rotation (Z-Score) transforms the log-ratio between two correlated crypto assets into a disciplined tier ladder decision framework. Rather than signalling single-asset direction, the engine measures how stretched one pair has become relative to its rolling mean and proposes rotation between the two assets when the spread reaches statistically meaningful extremes. Every decision is evaluated on confirmed Engine TF bar close, keeping suggestions non-repainting under the configured execution model.
🟣 UNIQUE EDGE
Unlike single-symbol mean-reversion or trend indicators, this engine treats the ratio itself as the tradable variable and pairs it with a full operational stack: a tiered exposure ladder (T0 to T3), an Integrity Gate that blocks entries when the pair relationship deteriorates, a Trend Regime filter that respects persistent one-sided moves, and a confirm-first execution model that converts raw signals into auditable decisions. A dedicated Signal Quality score (Q 0-100) and Integrity Score (IN 0-100) make every suggestion inspectable, not a black box.
🟢 METHODOLOGY
The engine fetches the closing price of Pair A and Pair B on the chosen Engine TF, computes the log-ratio L = ln(A / B), then derives a rolling z-score using user-defined lookback length. Entry thresholds (Z1, Z2, Z3) define the three tiers of exposure; exit thresholds (hysteresis) define when each tier is scaled back. A cost filter requires the expected mean-reversion edge to exceed a configurable multiple of estimated roundtrip cost before any entry is allowed. The Integrity Gate continuously validates rolling return correlation, ratio drift, and spread-volatility expansion, halting new entries when the pair relationship degrades.
🟡 SIGNALS & ALERTS
Each signal renders as a clearly tagged label on chart showing the action type (ENTRY / EXIT), source tier, target tier, direction (A->B or B->A), z-score snapshot, delta %, and Reason Code. Alerts are provided for: entry and exit events per direction, pending lifecycle (created, confirmed, skipped, expired), trend regime activation edges, duplicate suppression, and configuration warnings. All alerts fire on Engine TF bar close to remain consistent with the visible suggestions.
⚙️ KEY INPUTS
Pair A / Pair B: the two assets to rotate between (same quote currency recommended).
Engine TF: timeframe used for all ratio, z-score, and decision logic (240 / 4H default).
Lookback: bars used for rolling mean and standard deviation.
Entry Z1/Z2/Z3, Exit Z1/Z2/Z3: tiered thresholds for scaling in and out.
Tier Sizing (T1 / T2 / T3 %): rotation size per tier as a percentage of the active pool.
Trade Profile: preset gate behavior (Conservative, Balanced, Aggressive, Volatile Alt, High-Cost, Custom).
Integrity Gate: correlation, drift, and volatility expansion filter with configurable minimum score.
Execution Model: ASSUME (auto-advance), CONFIRM (pending + manual commit), or SIGNAL_ONLY (display only).
🔵 HOW TO USE
Start on the default BTCUSDT vs ETHUSDT pair on 4H Engine TF with the Balanced profile. Keep the chart timeframe equal to or lower than the Engine TF (the script warns otherwise). Watch the status panel for the current tier, direction, confidence strip (Q / IN / PH), and next action preview. In CONFIRM mode, a PENDING card appears when a signal fires; increase CONFIRM +1 to commit the rotation state, or SKIP +1 to discard. Use the Trade Profile dropdown to tighten or loosen effective gates without changing your base inputs.
🟠 LIMITATIONS & TRANSPARENCY
This is an indicator, not a strategy; no orders are placed and no backtest statistics are produced. Signals reflect statistical extremes in the pair's log-ratio and do not guarantee mean reversion. Performance depends heavily on pair selection - assets with persistent trends, broken correlation, or structural regime changes can cause extended adverse periods. The Integrity Gate mitigates but does not eliminate this risk. Costs, slippage, tax, and execution details are the user's responsibility; the Min Edge x filter is an estimate, not a realized-cost guarantee. Always validate on your own pair, timeframe, and account conditions before relying on any suggestion.
🔴 RISK DISCLOSURE
Trading and rotating between crypto assets involves substantial risk, including loss of capital. Past or simulated behavior of the ratio does not guarantee future results. This tool is shared for educational and analytical purposes only and does not constitute financial, investment, or trading advice. Users are solely responsible for their own decisions and should consult a qualified professional before committing capital. Indicatore

Follow-Through Day (FTD) Detector📈 Follow-Through Day (FTD) Detector
Marks Follow-Through Days on any chart using the classic William O'Neil / IBD methodology — a signal that a correction may be turning into a new uptrend attempt.
🔍 How it works
The script tracks rally attempts bar-by-bar. A rally begins when price is at or near a recent low (default 15-bar lookback) and closes up — that's Day 1. From there, the counter advances each bar. An FTD fires when, on day 4 or later of the attempt, the instrument closes up by at least the gain threshold (default 1.5%) on volume greater than the prior bar. If the rally's starting low is undercut before an FTD prints, the attempt resets.
🎨 On the chart
Green triangle below the bar on the FTD
Orange dot marking Day 1 of each rally attempt
Light blue background across the duration of an active attempt
Built-in alert condition
⚙️ Inputs
Minimum gain % (default 1.5 — IBD historically used 1.7%)
Earliest and latest day of the rally count (default 4 to 25)
Toggle for the higher-volume requirement
Lookback window for the recent-low check
Toggles for each visual element
✅ Pros
Faithful to the original rules, but fully parameterized
Works on any symbol and timeframe
Rally shading makes the setup visible in real time, not only after the signal fires
Clean state machine — no lookahead, no repainting
⚠️ Cons and caveats
FTDs are a probabilistic signal. Historically a meaningful share fail, and the script does not attempt to filter good vs bad ones
On cash indices like SPX, TradingView's volume is aggregated and can be noisy — disable the volume requirement or apply the indicator to SPY / ES futures
The rally-low reset uses the low of the first two bars of the attempt; a deeper correction low further back in the sell-off isn't tracked
Purely mechanical — doesn't incorporate market breadth, leadership, or distribution days, which IBD treats as essential companions
Defaults are a starting point, not a tuned edge. Backtest before trading off it
Feedback and suggestions welcome. Indicatore

Indicatore

Solstice Fibonacci Engine [JOAT]Solstice Fibonacci Engine
Introduction
The Solstice Fibonacci Engine is a fully automatic Fibonacci retracement and extension tool built for traders who want institutional-grade price levels drawn on their chart without the tedium of manually dragging anchor points. It detects the dominant swing high and swing low within your currently visible chart range, recalculates every time you scroll or zoom, and renders the complete Fibonacci suite — retracements from 0% to 100% and extensions to -100% — in a single, clean overlay.
The engine is purpose-built around two price zones that institutional order flow traders treat as highest-probability areas: the OTE (Optimal Trade Entry) zone from 61.8% to 78.6% retracement, and the Target Zone from -50% to -61.8% extension. These zones are shaded and labeled automatically, with TP1 through TP4 labels placed at the key confluence levels that align with those areas, giving you a ready-made trade management framework the moment any new swing is established.
Core Concepts
Visible Range Swing Detection
Unlike most Fibonacci tools that require manual anchoring or use fixed lookback lengths, Solstice tracks the swing high and swing low within the portion of the chart you are actually looking at:
int visLeft = int(chart.left_visible_bar_time)
int visRight = int(chart.right_visible_bar_time)
bool isVis = time >= visLeft and time <= visRight
if isVis
if na(swHi) or high > swHi
swHi := high
swHiBar := bar_index
if na(swLo) or low < swLo
swLo := low
swLoBar := bar_index
When you scroll left or right the swing resets instantly to reflect your new visible window. This makes the tool behave like a dynamic Fibonacci that always measures the most contextually relevant move — the one you are actually analyzing.
Trend Direction from Swing Sequence
The engine determines whether price is in an uptrend or downtrend by comparing the bar index of the swing high against the bar index of the swing low:
bool trendUp = nz(swLoBar, 0) < nz(swHiBar, 0)
If the swing low came first (left) and the swing high came after (right), price moved up — so retracement levels are drawn from the top down. If the swing high came first, price moved down and levels are drawn from the bottom up. This single boolean drives whether TP1–TP4 labels are placed above or below current price.
OTE Zone — 61.8% to 78.6%
The Optimal Trade Entry zone marks the golden pocket of Fibonacci retracement theory. Price returning into this band after a clean impulsive move often finds the institutional order flow that originally created the swing:
if showOTE
fibZone(color.new(oteClr, 90), 61.8, 78.6, trendUp,
bar_index - 2, lx, swHi, swLo, "OTE ZONE")
The zone is rendered as a shaded box extending to the right of the last visible bar, keeping it visible as new bars form. An alert fires on bar close the first time price enters this zone after it was outside it.
Target Zone — -50% to -61.8% Extension
The Target Zone marks the take-profit extension area beyond the 0% level:
if showTgt
fibZone(color.new(tgtClr, 90), -50.0, -61.8, trendUp,
bar_index - 2, lx, swHi, swLo, "TARGET ZONE")
When price has retraced into the OTE and reversed, the -50% to -61.8% extension zone becomes the natural profit target objective — where the move typically exhausts before the next consolidation.
TP1–TP4 Trade Management Labels
Four take-profit labels are placed at the levels that define a complete trade management plan from entry to full profit-taking:
| Label | Level | Meaning |
|-------|-------|---------|
| TP1 | 38.2% | First objective — scalp or partial close |
| TP2 | 0% | Full return to the original swing point |
| TP3 | -27.2% | First extension beyond the swing |
| TP4 | -61.8% | Deep extension — full target zone |
Features
Auto swing detection from visible chart range — no manual anchoring required
Dynamic recalculation on every chart scroll or zoom
Full Fibonacci suite: 0%, 23.6%, 38.2%, 50%, 61.8%, 70.6%, 78.6%, 100%, -27.2%, -50%, -61.8%, -100%, 150%, 200%
Per-level toggle switches — show only the levels you want
OTE Zone (61.8%–78.6%) shaded box with right-extension
Target Zone (-50% to -61.8%) shaded box with right-extension
TP1–TP4 labels with optional percentage labels on every level
Optional swing diagonal line from anchor to anchor
Dashboard showing swing trend, zone touch status, swing high/low, and range
Auto dark/light theme detection
Alerts fire on confirmed bar close when price enters OTE or Target Zone
Webhook JSON alert format for automation
Watermark
Input Parameters
Main Settings
Show All Elements — master toggle for all drawing objects
Show Swing Diagonal Line — draws a line connecting the two swing anchor points
Line Width — 1 to 5 pixels
Line Style — Solid, Dashed, or Dotted
Label Offset (bars) — how far to the right labels are placed beyond the last bar
Fibonacci Levels
Individual toggles for each level: 0%, 23.6%, 38.2%, 50%, 61.8%, 70.6%, 78.6%, 100%, -27.2%, -50%, -61.8%, -100%, 150%, 200%
Zones and Targets
Show OTE Zone — toggles the 61.8%–78.6% shaded box
Show Target Zone — toggles the -50% to -61.8% shaded box
Show Zone Labels — text inside zone boxes
Show TP1–TP4 Labels — take-profit label markers
Show Level % Labels — percentage text on every drawn level line
Visual Settings
Theme — Auto (reads chart background), Dark, or Light
Show Dashboard — compact panel showing current swing readings
Dashboard Position — Top Left, Top Right, Bottom Left, Bottom Right
Show Watermark
Webhook JSON — switches alerts to machine-readable JSON format
Colors
Fib Lines — color for all retracement/extension level lines
OTE Zone — fill color for the OTE box
Target Zone — fill color for the Target Zone box
How to Use
Add the indicator to any chart on any timeframe — it automatically maps to your current visible range.
Zoom or scroll your chart to frame the impulsive swing you want to analyze. The Fibonacci grid recalculates to match.
Look for price to retrace into the OTE Zone (gold band between 61.8% and 78.6%). This is the institutional entry area.
When price reverses out of the OTE zone, monitor the TP1 label at 38.2% for partial profits, TP2 at 0% for full return to the swing origin, and TP3/TP4 in the Target Zone for extended runners.
Set the OTE Zone and Target Zone alerts to receive notifications when price enters either area on bar close.
Enable percentage labels if you need to confirm exact level values for manual entries.
Indicator Limitations
The swing is determined by the highest high and lowest low within the visible range only — it does not use a structural pivot detection algorithm. On heavily zoomed-out charts, the swing might span an unusually long period.
Fibonacci levels are mathematical retracements of the detected swing range. They are areas of interest, not guaranteed reversal zones. Always combine with your own confluence analysis.
The OTE and Target Zone alerts trigger only on the first bar close when price enters the zone from outside. If price exits and re-enters, a new alert fires.
Retracement drawing regenerates on every bar close at the last bar. On very high-resolution timeframes with large numbers of active objects, this can approach TradingView drawing limits.
Originality Statement
The Solstice Fibonacci Engine is an original Pine Script v6 implementation. Its use of chart.left_visible_bar_time and chart.right_visible_bar_time for dynamic visible-range swing detection is a novel approach that produces a self-adjusting Fibonacci tool with no manual intervention. The OTE and Target Zone framework, TP1–TP4 label system, and scroll-responsive recalculation are original design decisions made specifically for this publication.
Disclaimer
This indicator is for educational and informational purposes only. It does not constitute financial advice. Fibonacci levels are areas of potential price reaction, not certainties. Past Fibonacci confluence does not guarantee future performance. Always use proper risk management and consult a licensed financial professional before trading.
-Made with passion by jackofalltrades
Indicatore

Indicatore

Aaryan EPS/ SalesAaryan EPS/ Sales
A comprehensive earnings and sales overlay that puts fundamental data directly on your price chart — quarterly results at a glance without leaving the chart window.
What it shows
The indicator displays two data tables and result-day labels on the chart:
Yearly Table shows EPS, year-over-year EPS growth, Sales (in Cr), year-over-year Sales growth, OPM%, PE, ROE, and EV/EBITDA for up to N years. Market cap is displayed in the header.
Quarterly Table shows EPS with QoQ growth and Sales with QoQ growth for up to N quarters. Stripped down to essentials — no price clutter.
Result Day Labels an arrow label is placed on the candle where quarterly results were declared. You choose what the label displays by ticking any combination of: EPS absolute value, EPS YoY growth %, and Sales YoY growth %. Multiple selections appear together separated by a pipe (e.g. "Mar-25: EPS:12.3 | E:+25% | S:+18%").
Customizable Settings
Everything is configurable from the settings panel:
- Toggle yearly table, quarterly table, and labels independently on or off
- Choose positive/negative growth colors (not locked to green/red)
- Set number of years and quarters to display
- Position each table anywhere on the chart (top/middle/bottom, left/center/right)
- Pick label size, color, and placement (above or below bar)
- Select which data points appear on result labels (multi-select checkboxes)
- Dark/light theme support
Data Source
All financial data is pulled from TradingView's built-in financial functions using FactSet earnings timestamps for accurate result-day detection. Sales figures are displayed in crores.
--- Indicatore

Delta Volume Structure [CLEVER]📌 Overview
Concept and Objective
Delta Volume Structure (DVS) is an analytical overlay tool developed to model directional volume pressure using standard OHLCV candle data. The core concept of the script is to estimate how trading volume may be distributed relative to price movement inside each bar and across broader session structures.
Traditional volume indicators typically display total traded volume per candle without distinguishing directional participation. DVS approaches this limitation by applying structured estimation logic that attempts to approximate buying and selling pressure based on measurable candle characteristics such as range, body position, and wick structure. The goal is not to replicate true bid/ask transaction data, but to provide a consistent, rule-based framework for interpreting volume behavior within the constraints of standard chart data.
The primary objective of the script is to enhance contextual analysis of price action. Instead of producing automatic trade entries or predictive signals, DVS is designed to help users evaluate:
Relative strength of directional participation
Imbalance between estimated buying and selling pressure
Momentum shifts reflected in cumulative delta flow
Structural pressure development during a session
Potential absorption or exhaustion characteristics
All calculations are derived exclusively from historical OHLCV data available on the active chart. The script does not access external order flow feeds, bid/ask transaction streams, or broker-specific execution data. As a result, delta values represent modeled approximations rather than confirmed executed trade-side data.
The tool is structured to support analytical decision-making rather than replace it. Its objective is to provide additional volume-based context alongside price structure, allowing users to assess how participation dynamics may align or diverge from visible price movement.
DVS is intended for educational and analytical use. It does not provide financial advice, guaranteed outcomes, or performance claims. Users are encouraged to apply independent judgment and appropriate risk management when interpreting its outputs.
📐 Delta Estimation Framework
The Delta Estimation Framework forms the computational foundation of the script. Its purpose is to approximate directional volume pressure using only standard OHLCV (Open, High, Low, Close, Volume) candle data available on the chart.
Since true bid/ask transaction data is not accessible within standard chart feeds, the framework does not attempt to replicate actual executed buy and sell orders. Instead, it applies rule-based mathematical modeling to estimate how total candle volume may be proportionally distributed between upward and downward price movement.
1️⃣ Directional Volume Modeling Approach
The framework provides multiple configurable estimation methods. Each method applies a different interpretation of candle structure to assign directional bias to volume.
• OHLC Proportional Distribution
In this model, volume allocation is influenced by the candle’s internal range positioning. The relationship between open, high, low, and close is used to estimate how much of the range reflects upward displacement versus downward displacement. Volume is then proportionally distributed based on this relative movement within the candle’s total range.
This approach attempts to reflect intrabar structural balance rather than relying solely on net bar direction.
• Close vs Open Allocation
This simplified model assigns directional bias based on whether the closing price is above or below the opening price. If the candle closes higher than it opens, volume is estimated as predominantly positive delta. If it closes lower, volume is estimated as predominantly negative delta.
This method prioritizes net directional outcome rather than internal range structure.
• Wick-Weighted Estimation
The wick-weighted model considers the relationship between candle body and upper/lower wicks. Larger lower wicks may indicate rejection of lower prices, while larger upper wicks may indicate rejection of higher prices. Volume distribution is adjusted proportionally according to body-to-wick structure.
This model attempts to incorporate intrabar rejection characteristics into directional estimation.
2️⃣ Delta Calculation
For each candle, estimated buy volume and sell volume are derived using the selected allocation model.
Delta is calculated as:
Estimated Buy Volume − Estimated Sell Volume
The result represents a modeled directional imbalance for that bar.
It is important to note that delta values generated by this framework are estimations derived from price structure and total volume. They do not represent confirmed trade-side execution.
3️⃣ Optional Smoothing and Noise Control
To reduce short-term volatility in delta readings, optional smoothing can be applied using configurable moving average logic. This allows users to balance responsiveness against stability depending on timeframe and instrument behavior.
Smoothing does not introduce forward-looking data and operates strictly on historical bars.
4️⃣ Cumulative Delta Integration
Individual bar delta values can be aggregated into cumulative delta (CVD). The framework supports configurable reset conditions such as:
Continuous accumulation
Daily reset
Weekly reset
This enables users to evaluate directional pressure across different structural horizons.
Cumulative calculations are derived solely from previously calculated delta values and do not incorporate future data.
5️⃣ Framework Limitations
Because the estimation logic is based entirely on OHLCV candle structure:
It does not use bid/ask execution data.
It does not access order book information.
It does not represent confirmed institutional order flow.
It reflects modeled approximations rather than transaction-level precision.
The framework is designed to provide structured analytical context within the constraints of available chart data.
Summary
The Delta Estimation Framework offers a configurable, rule-based system for approximating directional volume pressure using measurable candle characteristics. Its objective is to enhance contextual interpretation of participation dynamics while remaining fully dependent on standard historical data.
It is intended for analytical and educational use and should be interpreted alongside independent market structure analysis and risk management practices.
📊 Cumulative Delta and Session Structure
Conceptual Foundation
Cumulative Delta (CVD) within this script is designed as a structured aggregation of the previously calculated per-bar delta values. Rather than analyzing directional imbalance on a single candle basis, cumulative delta provides a running total of modeled buy–sell pressure over a defined period.
The objective is to observe how directional participation evolves across time, not to predict future price movement or replicate institutional order flow. All calculations rely strictly on historical OHLCV data available on the chart.
1️⃣ What Cumulative Delta Represents
Each bar produces an estimated delta value derived from the selected delta estimation framework.
Cumulative Delta is calculated as:
Previous CVD + Current Bar Delta
This produces a continuous directional pressure curve that reflects how modeled imbalance builds or unwinds over time.
It is important to clarify:
CVD is a derived analytical metric.
It does not represent confirmed executed buy/sell volume.
It does not access bid/ask trade-level data.
It reflects structured modeling within data limitations.
2️⃣ Session-Based Structure
To improve contextual clarity, the script allows cumulative delta to operate within defined structural boundaries. Instead of accumulating indefinitely, CVD can reset based on session logic.
Supported structural modes may include:
• Continuous Mode
CVD accumulates across all visible historical bars without reset.
Useful for observing long-term directional participation trends.
• Daily Reset
CVD resets at the beginning of each trading day.
This isolates intraday pressure dynamics.
• Weekly Reset
CVD resets at the beginning of each trading week.
This allows mid-term directional evaluation without long-term carryover distortion.
Reset logic is time-based and relies strictly on chart session boundaries. No forward-looking data is used.
3️⃣ Why Session Segmentation Matters
Without structural segmentation, cumulative data may become skewed by distant historical activity. Session-based resets allow users to:
Compare relative strength between trading sessions
Evaluate intraday participation shifts
Identify whether directional pressure is sustained or fading
Contextualize price movement within a defined structural window
This segmentation enhances analytical clarity but does not alter the underlying delta estimation method.
4️⃣ Divergence Observation
When price forms higher highs while cumulative delta fails to confirm, or when price forms lower lows while delta stabilizes, users may observe structural divergence patterns.
However:
The script does not label signals as predictive.
Divergence should be interpreted as contextual information.
No guarantee of reversal or continuation is implied.
All interpretations remain discretionary.
5️⃣ Internal Data Handling
The cumulative calculation process:
Uses only previously calculated delta values
Avoids repainting logic
Does not reference future bars
Updates strictly at bar close (unless user enables real-time intrabar updates within platform limits)
This ensures transparency and compliance with platform standards.
6️⃣ Structural Limitations
Because cumulative delta is derived from modeled directional allocation:
It does not represent actual order flow imbalance.
It does not replace exchange-level footprint data.
It may behave differently across assets with varying liquidity profiles.
Users should consider timeframe, instrument volatility, and volume characteristics when interpreting results.
Summary
Cumulative Delta and Session Structure within this script provide a rule-based framework for tracking modeled directional participation across defined structural windows. By combining delta aggregation with session segmentation, the tool aims to enhance contextual analysis of market pressure while remaining fully dependent on historical chart data.
It is intended for analytical and educational use and should be combined with independent risk management and broader market structure evaluation.
🎯 Advanced Pressure and Imbalance Metrics
Conceptual Objective
Advanced Pressure and Imbalance Metrics are designed to extend basic delta analysis into a more structured interpretation of participation dynamics. Instead of observing raw delta values alone, this framework evaluates how directional imbalance behaves relative to price structure, volatility, and session boundaries.
The purpose is not to generate guaranteed signals or predictive outcomes, but to provide layered analytical context derived strictly from historical OHLCV data.
All metrics remain model-based estimations and do not represent confirmed transaction-side execution.
1️⃣ Relative Delta Strength
Raw delta values can vary significantly across assets and timeframes. To improve interpretability, the script may normalize or scale delta readings relative to:
Average session volume
Recent rolling delta averages
Candle range expansion
This produces a contextual pressure measurement rather than an absolute number.
For example:
A moderate delta reading during low volume conditions may represent stronger relative pressure.
A large absolute delta during extreme volatility may represent balanced participation when scaled proportionally.
Normalization helps reduce distortion without introducing forward-looking logic.
2️⃣ Imbalance Intensity Mapping
Imbalance intensity refers to the magnitude of directional pressure relative to structural price movement.
The script may evaluate:
Delta relative to candle range
Delta relative to recent volatility
Acceleration or deceleration of cumulative delta slope
This allows identification of:
Sustained directional participation
Exhaustion behavior
Gradual absorption
Pressure compression zones
These observations are descriptive, not predictive.
3️⃣ Price–Delta Structural Relationship
Rather than treating delta in isolation, the framework evaluates how imbalance interacts with price behavior.
Common structural observations may include:
• Expansion with Participation
Price moves directionally while delta confirms consistent imbalance.
• Expansion with Weak Participation
Price continues higher or lower while delta flattens or contracts.
• Compression Before Break
Price consolidates while delta gradually builds in one direction.
These conditions are analytical interpretations and should not be treated as automatic trade signals.
4️⃣ Delta Acceleration & Deceleration
Beyond absolute values, the framework may assess the rate of change of delta.
This includes:
Increasing slope of cumulative delta
Sudden spike in single-bar imbalance
Progressive reduction in directional intensity
Acceleration metrics attempt to capture changes in participation tempo rather than static pressure.
All calculations are derived from previously computed delta values and do not reference future data.
5️⃣ Session-Weighted Pressure Context
When session segmentation is enabled, imbalance metrics are evaluated within the boundaries of the active session.
This allows users to observe:
Early session dominance
Mid-session absorption
Late-session exhaustion patterns
Session weighting ensures that pressure analysis reflects local structural conditions rather than distant historical accumulation.
6️⃣ Visual Representation Logic
Advanced pressure metrics may be displayed using:
Gradient-based histogram intensity
Heatmap-style background zones
Delta slope curves
Threshold-based markers
Visual elements are representations of calculated data and do not modify underlying calculations.
All visual updates occur using historical bar information only.
7️⃣ Limitations and Data Constraints
These metrics operate within the following constraints:
No bid/ask level trade data
No order book depth
No access to tick-level execution classification
Dependent on candle-based modeling
As such, the imbalance framework reflects structured estimation rather than exchange-confirmed order flow.
Behavior may vary across instruments with differing liquidity profiles.
Analytical Intent
The Advanced Pressure and Imbalance Metrics are designed to:
Provide layered context to delta behavior
Highlight participation shifts
Enhance structural observation within sessions
Support discretionary analysis
They are not designed to guarantee profitability, predict reversals, or replace independent risk management practices.
Summary
The Advanced Pressure and Imbalance Metrics expand basic delta modeling into a structured evaluation of participation strength, acceleration, and structural interaction with price. All calculations remain fully derived from historical OHLCV data and operate within clearly defined modeling limitations.
The framework is intended for analytical and educational use and should be interpreted alongside broader market structure analysis.
📉 Divergence and Structural Detection
Conceptual Foundation
Divergence and Structural Detection within this framework is designed to evaluate the relationship between modeled directional pressure (delta / cumulative delta) and visible price structure.
The objective is not to predict reversals or confirm future price movement, but to identify conditions where price expansion and participation pressure are no longer aligned. These structural differences may provide analytical context for discretionary decision-making.
All divergence calculations rely strictly on previously computed delta values and historical OHLCV data.
1️⃣ What Structural Divergence Represents
Divergence occurs when:
Price forms a new structural high while cumulative delta fails to form a corresponding high
Price forms a new structural low while cumulative delta fails to form a corresponding low
This indicates a potential imbalance between visible price movement and modeled participation pressure.
It is important to clarify:
Divergence is an observational condition, not a predictive signal
It does not guarantee reversal
It does not confirm exhaustion
It reflects structural mismatch within historical data
2️⃣ Types of Divergence Observed
• Bearish Structural Divergence
Price prints higher highs while cumulative delta forms lower highs or flattens.
Interpretation context:
Participation intensity may be weakening relative to price expansion.
This does not imply immediate downside movement.
• Bullish Structural Divergence
Price prints lower lows while cumulative delta forms higher lows or stabilizes.
Interpretation context:
Directional selling pressure may be reducing relative to price decline.
This does not imply guaranteed upside reversal.
• Hidden Structural Divergence
In some configurations, continuation-type divergence may also be observed:
Price forms higher low while delta forms lower low
Price forms lower high while delta forms higher high
These observations reflect structural shifts in participation relative to pullbacks.
All divergence types are derived from swing comparisons within defined lookback windows.
3️⃣ Swing Detection Methodology
Structural comparisons require identification of local swing points in price and cumulative delta.
Swing detection may use:
Configurable lookback periods
Fractal-based high/low recognition
Pivot confirmation logic
Range-based filtering
All pivot detection operates using confirmed historical bars only. No future data or repainting logic is used beyond normal pivot confirmation delay.
4️⃣ Structural Strength Filtering
To reduce noise, divergence logic may incorporate filtering conditions such as:
Minimum delta magnitude threshold
Minimum price swing distance
Session-bound comparison
Volatility-adjusted swing qualification
This ensures divergence is evaluated within meaningful structural movement rather than minor fluctuations.
Filtering enhances clarity but does not eliminate false positives.
5️⃣ Multi-Session Context
When session segmentation is enabled, divergence may be evaluated:
Within the active session
Across session boundaries
Relative to prior session cumulative extremes
This allows contextual interpretation of whether divergence reflects intraday imbalance or broader structural shift.
6️⃣ Visualization Logic
Divergence detection may be displayed through:
Connecting swing lines
Highlighted pivot markers
Structural labeling
Subtle background indication
Visual representation does not alter the underlying delta computation.
All signals are plotted using confirmed bar data to maintain transparency.
7️⃣ Practical Interpretation Considerations
Divergence should be evaluated alongside:
Market structure (trend vs range)
Volatility regime
Volume expansion or contraction
Higher timeframe context
Divergence in isolation does not provide sufficient confirmation for trade execution.
8️⃣ Limitations
Because delta itself is modeled from OHLCV data:
Divergence reflects modeled imbalance, not confirmed order flow
It does not access tick-level trade classification
Results may vary across assets with different liquidity structures
Short timeframes may produce higher noise frequency
Users should adjust structural sensitivity according to timeframe and instrument behavior.
Summary
The Divergence and Structural Detection module evaluates the relationship between price swings and modeled cumulative delta behavior. By identifying structural mismatches between price movement and directional pressure, the framework provides contextual insight into participation dynamics.
All calculations are historical, rule-based, and non-predictive in nature. The feature is intended for analytical and educational use and should be combined with independent market structure analysis and disciplined risk management.
🧩 Dashboard Architecture
Conceptual Overview
The Dashboard Architecture in this script is designed as a structured information layer that consolidates multiple analytical outputs into a single, readable interface. Instead of displaying isolated indicators separately, the dashboard organizes delta, volume, cumulative metrics, and structural signals into a unified layout.
The objective is to improve readability and decision context by presenting computed values in a compact format. It does not introduce new predictive logic; it only visualizes already calculated data in a structured form.
All displayed values are derived from historical OHLCV-based calculations within the script.
1️⃣ Core Design Philosophy
The dashboard follows a multi-row, multi-column structured grid system. Each cell represents a specific analytical metric, grouped by functional categories such as:
Delta and volume behavior
Cumulative delta structure
Imbalance and participation metrics
Trend and momentum context
Session-based statistics
This modular layout ensures that each category remains visually separated while still contributing to an integrated market view.
2️⃣ Multi-Layer Information Structure
The dashboard is organized into layered rows, where each row represents a different level of analytical depth:
• Primary Layer (Core Metrics)
This layer focuses on immediate market pressure representation, such as:
Delta values
Buy/sell proportion
Imbalance ratio
Aggregated pressure score
These values reflect short-term participation structure.
• Secondary Layer (Behavioral Context)
This layer expands interpretation by including:
Cumulative delta status
Trend classification
Momentum state
Strength scaling of participation
It provides context to raw pressure readings without altering their computation.
• Structural Layer (Session & Flow Context)
This layer focuses on broader structural behavior:
Session cumulative delta
Flip counts and directional shifts
Institutional footprint flags
Absorption and climax counts
It helps in understanding how market behavior evolves over time within a session boundary.
• Diagnostic Layer (Pressure Visualization)
This layer translates numeric relationships into readable classifications such as:
Strong / weak participation
Balanced / imbalanced flow
High / low volatility pressure states
Streak-based directional behavior
These classifications are derived from thresholds and ratios, not external data.
3️⃣ Data Aggregation Logic
The dashboard does not compute raw indicators independently. Instead, it aggregates already calculated internal variables, such as:
Delta (bar-level directional estimation)
Cumulative delta (session-based accumulation)
Volume averages (rolling statistical baseline)
Price structure metrics (range, position, body size)
This ensures that the dashboard remains a visualization layer rather than a computation engine.
4️⃣ Dynamic Update Mechanism
All dashboard values update in real-time based on completed bar data. The update process follows these principles:
No forward-looking calculations
No repainting beyond standard bar confirmation behavior
Updates occur only when new bar data is confirmed
Session resets apply when configured time boundaries are reached
This maintains consistency between plotted data and displayed values.
5️⃣ Visual Hierarchy System
The dashboard uses a structured visual hierarchy to improve readability:
Color coding distinguishes bullish, bearish, and neutral conditions
Font emphasis highlights key metrics
Section separators visually isolate analytical groups
Grid alignment ensures consistent comparison across metrics
The visual design supports interpretation but does not influence calculations.
6️⃣ Session Integration Layer
Session-based logic plays a key role in dashboard behavior. Metrics are optionally reset or segmented based on:
Daily session boundaries
Weekly session boundaries
Continuous accumulation mode
This allows the dashboard to reflect either intraday behavior or extended structural flow depending on configuration.
7️⃣ Performance and Optimization Considerations
To maintain efficiency:
Computations are reused rather than recalculated where possible
Rolling functions are applied with fixed lookback windows
Table updates are optimized through structured cell updates
No unnecessary external data calls are used
This ensures stable performance even with high-frequency updates.
8️⃣ Interpretation Boundaries
The dashboard is a visualization framework only. It does not:
Predict future price movement
Guarantee trade outcomes
Replace market structure analysis
Access real order book data
All displayed insights are derived strictly from historical OHLCV-based calculations.
Summary
The Dashboard Architecture provides a structured visualization layer that organizes multiple delta-based and volume-based metrics into a unified analytical interface. It enhances readability by grouping related market behavior indicators into a clean, hierarchical grid system while maintaining strict reliance on historical data inputs.
The system is designed for analytical clarity and observational context rather than predictive functionality, ensuring compliance with platform standards and maintaining transparency in data representation.
📌 How It Works
⚙️ Core Concept
The core idea is that the market is not interpreted through single candle values or simplified price points, but as a continuous intrabar auction process where buyers and sellers actively compete at every price level. Instead of treating Open, High, Low, and Close as summary values, each candle is analyzed as a full internal price journey.
📊 Intrabar Price Path Logic
Every candle is assumed to contain a complete price path rather than a single directional move. This means price is considered to have traveled through multiple levels within the candle, creating micro-interactions of buying and selling. These internal movements are used to reconstruct how activity was distributed across price levels.
🔥 Volume Distribution Mechanism
Instead of assigning volume to only one price point, volume is distributed across the entire path of the candle. Each segment of price movement receives a proportional share of volume based on how the market behaved during that movement. This creates a more accurate representation of real participation in the market.
🎯 Market Behavior Interpretation
This structure helps identify hidden market behavior that traditional candle analysis cannot show. It reveals where liquidity was actively consumed, where acceptance occurred, and where rejection started. Essentially, it exposes the underlying order flow behavior behind each candle.
🧠 Final Understanding
Overall, the system is designed to combine price action with intrabar volume distribution, allowing the market to be read as an auction-based structure rather than a simple sequence of candles. This makes it possible to understand institutional-level activity more clearly and accurately.
⚙️ Core Concept
📌 Market as an Auction System
The market is best understood as a continuous auction where buyers and sellers constantly compete to agree on price. Every candle represents a mini-auction session rather than a simple directional move. Price is not random; it is the outcome of repeated negotiations between aggressive buyers and aggressive sellers at different levels.
📊 Price Discovery Process
In this auction system, price continuously moves to find areas of acceptance and rejection. When buyers dominate, price is pushed upward until sellers step in. When sellers dominate, price is pushed downward until buyers absorb the supply. This ongoing interaction forms the structure of price discovery within every candle.
🔥 Liquidity Interaction Model
Each price level inside a candle represents a point where liquidity is tested. The market does not move in a straight line; it moves by consuming available liquidity step by step. Strong participation at certain levels indicates acceptance, while weak participation indicates rejection zones.
🎯 Imbalance Between Buyers and Sellers
The core driver of movement is imbalance. When buying pressure outweighs selling pressure, the auction shifts upward. When selling pressure dominates, the auction shifts downward. This imbalance is what creates trends, reversals, and consolidations in the market.
🧠 Final Understanding
Ultimately, viewing the market as an auction system means understanding that every price movement is the result of real-time competition between buyers and sellers. Price only changes when one side becomes stronger than the other, making market structure a direct reflection of underlying order flow behavior.
📌 How It Is Used
⚙️ Core Usage Idea
This system is used to read the market as a liquidity-driven auction, where the main focus is not prediction based on patterns, but interpretation of who is in control (buyers or sellers) at specific price zones. Traders use it to understand where real participation is happening and where the market is likely to react due to imbalance.
📊 Identifying High-Probability Zones
One of the primary uses is to detect important price zones such as high-volume areas, value areas, and low-volume gaps. These zones act as decision points where price either continues its trend or reverses. Traders use these areas to plan entries and exits based on acceptance or rejection of price.
🔥 Understanding Market Pressure
The system is used to measure buying and selling pressure through volume distribution and delta behavior. When buying pressure consistently dominates at higher levels, it signals bullish strength. When selling pressure dominates at lower levels, it signals bearish control. This helps in reading real market intent rather than guessing direction.
🎯 Entry and Exit Timing
Traders use this structure to refine timing. Entries are typically planned at points where the market shows imbalance shift or rejection from low-volume zones. Exits are often planned near high-volume nodes or value boundaries where price is likely to slow down or consolidate.
📐 Trend Continuation and Reversal Detection
This approach is also used to identify whether a trend is strong or weak. If volume supports the direction consistently, the trend is considered strong. If volume starts shifting against the direction, it signals potential exhaustion and reversal.
🧠 Final Practical Understanding
In practical use, this system is not just an indicator but a decision-making framework. It helps traders read real-time market behavior, understand institutional activity, and align trades with actual liquidity flow instead of relying on simple chart patterns or lagging signals.
📌 How the Concepts Work Together
⚙️ Unified Market Structure
The real strength of this system appears when all components are combined into a single framework. The market is not analyzed as isolated indicators, but as a unified structure where price action, volume distribution, session behavior, and order flow pressure all interact simultaneously to define market intent.
📊 Price and Volume Integration
First, the full candle movement (Open, High, Low, Close) is combined with volume distribution. Instead of assigning volume to a single price point, it is spread across the entire intrabar price path. This reveals where actual trading activity occurred and which price levels attracted real participation.
🔥 Auction and Liquidity Behavior
The market is treated as a continuous auction where liquidity is constantly being tested and consumed. High-volume zones represent areas of acceptance where the market is comfortable trading, while low-volume zones represent inefficiency where price tends to move quickly due to lack of participation.
🎯 Delta and Pressure Confirmation
After volume distribution, delta analysis is used to confirm whether buyers or sellers are in control. When price movement aligns with strong delta, it confirms trend strength. When price moves against delta, it signals weakening momentum and potential reversal conditions.
📐 Session-Based Context Filtering
Each movement is evaluated within its specific trading session (Asia, London, New York). This helps filter noise and highlights periods of strong institutional activity. It also shows when the market is likely to trend versus when it is likely to consolidate.
🔗 Step-by-Step Combined Workflow
The full intrabar price path is analyzed
Volume is distributed across price levels
Key zones such as POC, VAH, VAL, HVN, and LVN are formed
Delta confirms buying or selling pressure
Session context validates market strength
Final interpretation (trend, reversal, breakout) is derived
🧠 Final Combined Understanding
When all components work together, the market is no longer viewed as random price movement. It becomes a structured auction map where every move has a clear reason—showing where liquidity exists, who is in control, and how institutional participation is shaping price behavior.
📌 Key Features
📊 Path-Based Volume Distribution
One of the core features is the ability to distribute volume across the entire intrabar price path instead of assigning it to a single candle close. This allows the system to show where actual trading activity happened inside each candle, giving a more realistic view of market participation and liquidity flow.
🔥 Session-Based Market Segmentation
The system divides the market into separate trading sessions such as Asia, London, and New York. Each session behaves differently in terms of volatility and liquidity. By isolating sessions, the indicator highlights institutional participation periods and removes mixed noise from different market phases.
🎯 Value Area and Control Zones
It automatically identifies key structural zones such as Point of Control (POC), Value Area High (VAH), and Value Area Low (VAL). These zones represent areas where the market has accepted price or rejected it, helping traders understand balance and imbalance in market structure.
📐 High and Low Volume Nodes (HVN / LVN)
The system highlights areas of concentrated and thin volume. High Volume Nodes indicate strong acceptance zones where price tends to consolidate, while Low Volume Nodes represent inefficiency zones where price can move rapidly due to lack of liquidity.
🔥 Delta and Pressure Analysis
A key feature is the calculation of buying and selling pressure through delta. This shows whether buyers or sellers are dominating at specific price levels. It helps identify strength behind moves rather than just direction.
⚡ Dynamic Real-Time Updating
The structure updates in real-time as new candles form. Each new price movement adjusts volume distribution, zones, and pressure metrics. This makes the system adaptive and responsive to changing market conditions.
🎯 Institutional Footprint Detection
By combining volume, price path, and delta, the system reveals hidden institutional behavior. It helps identify where large participants are entering or exiting the market, which is often invisible in traditional indicators.
🧠 Final Understanding
Overall, the key features work together to transform raw price action into a structured market map. This map shows liquidity distribution, control zones, pressure imbalance, and real-time institutional activity, making the market behavior easier to interpret and analyze.
⚙️ Settings & Customization
📌 Core Customization Philosophy
The main purpose of customization is to allow the system to adapt to different trading styles, strategies, and risk preferences. The default configuration only provides a baseline structure, while real effectiveness comes when the user fine-tunes the tool according to how they read and trade the market.
🕒 Session Settings Control
Session customization allows traders to select which trading sessions to analyze, such as Asia, London, or New York. Each session has different liquidity and volatility characteristics. By enabling or disabling specific sessions, traders can remove unnecessary noise and focus only on high-impact market periods.
📊 Volume Sensitivity Adjustment
This setting controls how detailed the volume distribution will be. Higher sensitivity reveals finer intrabar activity and micro-level participation, while lower sensitivity highlights only major liquidity zones. This allows traders to switch between precision-based analysis and simplified structure reading depending on their strategy.
🔥 Profile Resolution Control
Profile resolution determines how finely the price path is divided. A higher resolution creates a more detailed and complex market structure, while a lower resolution produces a cleaner and more readable chart. Scalpers and intraday traders often prefer higher resolution, while swing traders prefer lower resolution for clarity.
🎯 Zone Display Options
This customization allows users to enable or disable specific structural zones such as:
Point of Control (POC)
Value Area High (VAH) and Value Area Low (VAL)
High Volume Nodes (HVN) and Low Volume Nodes (LVN)
Turning off unnecessary zones helps maintain a clean chart and improves decision clarity.
📐 Delta & Pressure Filters
These settings control how buying and selling pressure is calculated and displayed. Strong filtering reduces noise and produces more stable signals, while weaker filtering increases sensitivity and produces earlier but more volatile signals. This directly impacts trend confirmation and reversal detection accuracy.
⚡ Real-Time Update Speed
This setting defines how quickly the indicator updates with new price data. Faster updates are useful for scalping and fast execution strategies, while slower updates provide smoother and more stable analysis for swing or positional trading.
🧠 Final Customization Insight
Overall, customization transforms the system from a fixed indicator into a flexible market analysis framework. By adjusting sessions, volume sensitivity, resolution, zones, and update speed, each trader can build a personalized structure that matches their trading style and improves decision-making accuracy.
🧠 Final Note
⚙️ Complete Market Understanding
This entire system is designed to change the way the market is viewed. Instead of treating price as a simple line moving up and down, it reveals the market as a liquidity-driven auction environment where every movement is the result of real interaction between buyers and sellers.
📊 From Noise to Structure
What looks like random candles on a chart is actually structured behavior. When volume is distributed across the price path and combined with session context and pressure analysis, the market stops being noise and starts forming a clear structure of acceptance, rejection, and imbalance.
🔥 Real Intent vs Visual Movement
The key transformation is the ability to separate visual price movement from real market intent. A candle may look strong or weak visually, but true strength is confirmed only when volume, delta, and liquidity zones support that move. This is where hidden institutional activity becomes visible.
🎯 Decision-Making Clarity
This framework does not predict the market; it helps interpret it. It gives clarity on where participation is strong, where liquidity is trapped, and where the market is likely to react. This reduces emotional trading and replaces it with structured decision-making based on data behavior.
🧠 Final Insight
Ultimately, the final purpose of this system is to shift thinking from “guessing direction” to “reading behavior.” Once a trader understands how price, volume, and liquidity interact together, the market becomes less unpredictable and more logical. The real edge comes from understanding this hidden auction structure, not from any single indicator or signal.
⚠️ Disclaimer
📌 Educational Purpose Only
This system, explanation, and all related concepts are provided strictly for educational and informational purposes. It is designed to help understand market structure, volume behavior, and auction-based price action, not to provide guaranteed trading results or financial advice.
📊 No Financial Advice
Nothing in this content should be considered financial, investment, or trading advice. The interpretation of markets is highly subjective and depends on individual skill, experience, and risk management. Users are fully responsible for their own trading decisions.
🔥 Market Risk Warning
Trading in financial markets involves high risk of loss, and it is possible to lose all invested capital. Past behavior, volume analysis, or indicators do not guarantee future performance. Market conditions can change rapidly and unpredictably.
🎯 No Guarantee of Accuracy
Although the system is designed to improve market understanding, no method, indicator, or framework can predict the market with 100% accuracy. All signals, zones, and interpretations should be treated as analytical tools, not absolute outcomes.
🧠 User Responsibility
Every trading decision made using this information is the sole responsibility of the user. Proper risk management, discipline, and independent verification are essential before entering any trade.
⚡ Final Note
This content is meant to enhance market understanding and analytical thinking. It should be used as a supportive tool within a broader trading strategy, not as a standalone system for guaranteed profits.
⚠️ Repainting / Misleading Behavior (Important Note)
Pivot-based signals in this script are based on confirmed swing points using ta.pivothigh and ta.pivotlow, which naturally appear only after a defined confirmation length (divergence period). To prevent misleading behavior, proper offset handling is applied so signals are plotted on validated structure rather than future or unconfirmed data. The script does not use any lookahead logic, does not access future data, and avoids security() misuse, ensuring that all signals are generated strictly from historical confirmed price action.
⚠️ Potential Risk Areas (Minor – Terminology Clarity)
The variable is Institutional should be described carefully to avoid implying direct detection of real institutional orders, as this can be considered a misleading claim under publishing guidelines. Instead of stating that it “detects real institutional activity,” it is safer and more accurate to define it as identifying high-volume, compressed-range price behavior that may represent areas of increased participation or strong market activity. This ensures the description remains compliant, realistic, and focused on observable market data rather than unverified institutional inference. Indicatore

Indicatore

Libreria

Indicatore

Machine Learning: seMLP Q-Wavelet RL Engine [Jamallo]Author Note: I always get asked: "How can I build a Machine Learning or Artificial Intelligence trading system?" I created the study "Machine Learning: seMLP Q-Wavelet RL Engine" to showcase exactly how it can be done in a beginner-friendly manner. We will break down exactly how this AI thinks in plain English, and then show you exactly how the Pine Script code executes it step-by-step.
Introduction: The Institutional Approach to Algorithmic Trading
Most retail and algorithmic traders spend years searching for the "holy grail" by combining static indicators and hard-coded `IF/THEN` rule sets. They are often unaware that institutional quant desks abandoned those basic, curve-fitted patterns decades ago. Standard algorithmic analysis fails because financial markets are inherently chaotic—a hardcoded strategy that works perfectly in a backtest will systematically break down during a live regime shift.
To acquire a true institutional edge, algorithmic strategies cannot rely on rigid, backwards-looking formulas; they require a system that adapts dynamically in real-time. This script brings that quantitative firepower directly to your chart by constructing a live Self-Teaching AI .
Dynamic Filtering : It uses advanced frequency mathematics (Wavelets) to separate random market noise from true institutional momentum footprints with near-zero lag.
Artificial Brain : It feeds that data into a neural network—a living matrix of artificial "neurons" that continuously analyze and execute decisions.
Self-Correction : Most importantly, it executes Reinforcement Learning. If a trade fails, the AI actively calculates the error and mathematically rewires its own brain, ensuring it constantly evolves to survive changing market conditions.
Ultimately, this serves as a foundational study showing you exactly how to break away from basic scripting and get started in true Quantitative Algorithmic Trading.
1. The Core Architecture Loop
Here is the high-level flow of how the AI thinks on every single candle:
The Invisible "Burn-In" Phase
Because the AI starts with a completely randomized, "empty" brain, it will make terrible decisions on the very first few candles. To prevent it from acting prematurely on live data, the script executes an aggressive Burn-In Phase (e.g., the first 300 bars of the chart). During this period, the indicator is completely invisible. It aggressively executes hundreds of "mock trades" in the background, tracking virtual PnL, taking massive risks, and rapidly rewiring its brain without showing a single signal on your screen. Once the 300 bars are up, the burn-in phase ends. The AI stops acting recklessly and officially enters "Live Trading" mode with a fully trained, highly-intelligent brain.
SECTIONS 2 & 3: Setting Up the Brain
Conceptual Overview
Imagine the brain as a massive team of financial analysts.
We have 16 junior analysts looking at chart data.
They report their findings up to 12 senior analysts.
The seniors report to 6 directors.
The 6 directors send their final opinions to 3 executives representing the 3 possible actions: `BUY, SELL, HOLD`. This is called a 16 → 12 → 6 → 3 network structure.
Before we hand the price data to the junior analysts, we Normalize it (Z-Score). This just means "leveling the playing field" so a massive $500 candle wick doesn't break the analysts' math compared to a tiny $1 movement.
The Code Breakdown
// Section 2: Brain Size Constants
int NI = 16 // 16 Inputs (Junior analysts)
int NH1 = 12 // 12 Hidden layer 1 nodes
int NH2 = 6 // 6 Hidden layer 2 nodes
int NO = 3 // 3 Outputs
// Section 3: Normalization Helper
norm(series float x, simple int win) =>
float mu = ta.sma(x, win)
float sg = ta.stdev(x, win)
float sf = nz(sg) < 1e-10 ? 1.0 : sg
float res = (x - nz(mu, x)) / sf // Levels out the price data
na(res) ? 0.0 : res
SECTIONS 4 & 5: Giving the AI "Memory"
Conceptual Overview
By default, TradingView indicators suffer from permanent amnesia! Every time a new candle paints, TradingView completely deletes its short-term memory and forgets what happened on the last candle. If we are building an AI for trading that needs to "learn", it must be able to remember its past mathematical mistakes.
To force TradingView to remember, we use special variables called `var` to create "Persistent Memory Matrices" where the AI for trading stores its brain's wiring throughout the entire chart history.
The Code Breakdown
// Using 'var' locks the memory so it never resets when a new candle paints
var matrix W1 = matrix.new(NI, NH1, 0.0) // The connections between neurons
var matrix W2 = matrix.new(NH1, NH2, 0.0)
...
var int pos = 0 // The AI remembers its current position: Long (1), Short (-1), or Flat (0)
SECTION 6: Seeing the Market (Wavelets)
Conceptual Overview
If you use a Moving Average, it always "lags" behind the real price. By the time the Moving Average crosses to tell you to buy, the massive breakout has already happened.
To fix this, we teach the AI for trading to see using Haar Wavelets . A Wavelet is a piece of advanced math that splits the price candle with minimal lag into two things:
The Detail (D) : The immediate, rapid volatility chop.
The Smooth (V) : The true underlying smooth momentum. By looking at the detail and momentum completely separately, the AI for trading can react to shifts with minimal lag.
The Code Breakdown
// We take standard features like Open, Close, and Volume:
float f0 = open
float f1 = close...
// We break them into Wavelets using simple math combinations:
float v1_0 = (f0 + nz(f0 , f0)) / 2.0 // Smooth momentum
float d1_0 = (f0 - nz(f0 , f0)) / 2.0 // Instant volatility detail
...
// We pack all 16 traits into the 'feat' array to feed the AI for trading's Brain
feat.set(0, norm(d1_0, i_normWin))
feat.set(14, float(pos)) // Tells the brain its current trade position
feat.set(15, norm(portRet, i_normWin)) // Tells the brain its current open trade return
SECTION 7: How the Brain Thinks (seMLP)
Conceptual Overview
An "MLP" is just a standard Neural Network (a massive web of variables that pass data to each other). The problem is that if you give TradingView an insanely massive web of math equations, it will crash and throw a compiler timeout error.
So, we use a Self-evolving MLP (seMLP) . The AI pushes the Wavelet data through its network dynamically. To prevent "dead zones" where a neuron just stops firing in a flat market, it uses a formula called LeakyReLU . It basically acts as a gatekeeper that tells the neuron: "If this signal is incredibly weak, shrink it down to 1%, but don't explicitly delete it."
The Code Breakdown
// The data enters Hidden Layer 1 (h1)
array h1 = array.new(NH1, 0.0)
for j = 0 to NH1 - 1
float s = B1.get(j)
// The inner brain loops through all 16 incoming inputs
for i = 0 to NI - 1
s += feat.get(i) * W1.get(i, j)
// LeakyReLU Formula: f(x) = x if x > 0 else 0.01 * x
// If the signal 's' is positive, keep it. If 's' is negative, shrink to 1%
h1.set(j, s > 0 ? s : 0.01 * s)
SECTION 8: Taking Action (Exploration vs Exploitation)
Conceptual Overview
How does the AI actually press the BUY or SELL button? It calculates a "Confidence Score" (called a Q-Value) for all three options— Buy, Sell, and Hold. The highest score wins and executes the trade.
However, during its invisible "Burn-In Period", the AI uses a variable called Epsilon . Think of Epsilon as a dice roll. Sometimes, instead of making the smartest, highest-scoring choice, the AI will randomly pick a completely stupid trade just to "experiment" and see if a hidden market pattern exists! This is conceptually how AI for trading discovers new, out-of-the-box strategies. As training goes on, Epsilon gets smaller, and the AI stops experimenting.
The Code Breakdown
// Calculate Epsilon: Start at a high 50% and slowly decay to 5% over time
float epsilon = bar_index <= i_burnIn ? math.max(0.05, i_epsStart_val * ...)
// Roll the dice. If the random number is less than epsilon, we experiment randomly!
bool explore = math.random(0.0, 1.0) < epsilon
// Find the AI for trading's highest confidence choice: Q(0) = Buy, Q(1) = Sell, Q(2) = Hold
if Q.get(1) > bestQ // If Sell confidence is higher than current best (Buy)...
bestQ := Q.get(1)
bestAct := 1
if Q.get(2) > bestQ // If Hold is even higher...
bestQ := Q.get(2)
bestAct := 2
// Execute the final action
int act = explore ? math.min(int(math.floor(math.random(0.0, 2.999))), 2) : qArg
SECTION 9: Training with Rewards (Reinforcement Learning)
Conceptual Overview
This is the heart of Machine Learning. It functions exactly like training a pet. If the AI makes a winning trade that generates cash, we give it a mathematical "treat" (a positive reward). If the AI loses money, we hit it with a brutal negative reward. Over time, the AI autonomously refines its neural weights exclusively to collect the maximum amount of "treats".
The Code Breakdown
// Calculate how much money the candle moved
float cRet = nz((close - close ) / close , 0.0)
// The Reward (R) is a combination of three factors:
// 1. PnL (rPn) - Did we make raw cash profit?
// 2. Trail (rTn) - Did we efficiently track the trend?
// 3. Lee (rLee) - A shaping bonus for correct directional positioning.
float R = i_alphaT * rTn + i_alphaP * rPn + 0.1 * rLee
SECTION 10: Learning from Mistakes (Backpropagation)
Conceptual Overview
If the AI's trade failed, how does it adjust its internal logic? It uses a process called Backpropagation . It looks at the Reward it just received, realizes it was horribly wrong, and calculates the "Error Margin" (How far off my prediction was I?). It then mathematically rewrites all of the internal connections `(W1, W2, W3)` in reverse, editing them to be slightly smarter for the next candle!
Because updating a massive brain on every single micro-tick causes chaotic glitches, we "Accumulate" the errors in a batch over several candles, and then update the brain smoothly with the batch average.
The Code Breakdown
// Compare the Target Reward vs what the Brain actually Predicted (Temporal Difference Error)
float tgt = R + i_gamma * max_qt
float td = tgt - pOut.get(prevAct)
// Accumulate the backwards gradients over multiple bars so we don't glitch
for j = 0 to NO - 1
gB3_acc.set(j, gB3_acc.get(j) + g3.get(j))
accumCount += 1
// Once 'i_accumSteps' bars have passed, we apply the compiled batch update to 'Rewire' the Brain weights!
if accumCount >= i_accumSteps
for i = 0 to NH2 - 1
for j = 0 to NO - 1
float dw = gW3_acc.get(i, j) * sc
W3.set(i, j, W3.get(i, j) + clr * dw - clr * i_l2 * W3.get(i, j))
SECTION 11: Link Pruning (Making the Brain Faster)
Conceptual Overview
Stage 1: The Initial Brain (Complex & Slow)
Stage 2: The Pruning Decision
Stage 3: The Optimized AI for trading (Sleek & Fast)
As the brain learns, some of the mathematical connections become totally useless. Having a giant Tradingview indicator calculate hundreds of useless math connections will trigger a calculation timeout. At a specific point in training length (defaulting to the end of the 300-bar burn-in period), the script literally pauses and deletes (zeroes out) the weakest neural links. TradingView skips over calculations containing plain zeroes, making your indicator insanely fast and completely lag-proof.
The Code Breakdown
if bar_index == i_pruneBar and not pruned
// Evaluate every single connection weight...
// Find the bottom weakest percentage (i_prunePct)
float thr = absW.get(pidx)
// Explicitly set the weakest weights to Zero!
for i = 0 to NI - 1
for j = 0 to NH1 - 1
if math.abs(W1.get(i, j)) <= thr
W1.set(i, j, 0.0) // Permanent pruning: weak link removed
Important Disclaimer
This indicator is published strictly for educational and research purposes. It is a conceptual showcase proving that advanced Deep Reinforcement Learning architectures generally reserved for Python/TensorFlow can be natively executed within the TradingView Pine Script environment. Due to Pine Script's structural time-series limitations—specifically the lack of a random-access historical buffer required for true experience replay—this is NOT intended for practical live trading. For production-grade deployment, it is highly recommended to port this mathematical framework to Python.
References
This indicator's mathematical engine was directly modeled and bridged from the following quantitative research papers:
Lee et al. (2021) — " Learning to trade in financial time series using high-frequency through wavelet transformation and deep reinforcement learning " (Used for the MODWT Wavelet integration & State architecture).
Tsantekidis et al. (2021) — " Price Trailing for Financial Trading using Deep Reinforcement Learning " (Used for the dynamic margin-trailing reward system).
Seow et al. (2021) — " seMLP: Self-evolving Multi-layer Perceptron " (Used for the 16 → 12 → 6 → 3 sparse Neural Network structure and the automatic Link Pruning logic).
Indicatore

Indicatore

Indicatore
