Smarter Money Concepts - Wyckoff Springs & Upthrusts [PhenLabs]📊Smarter Money Concepts - Wyckoff Springs & Upthrusts
Version: PineScript™v6
📌Description
Discover institutional manipulation in real-time with this advanced Wyckoff indicator that detects Springs (accumulation phases) and Upthrusts (distribution phases). It identifies when price tests support or resistance on high volume, followed by a strong recovery, signaling potential reversals where smart money accumulates or distributes positions. This tool solves the common problem of missing these subtle phase transitions, helping traders anticipate trend changes and avoid traps in volatile markets.
By combining volume spike detection, ATR-normalized recovery strength, and a sigmoid probability model, it filters out weak signals and highlights only high-confidence setups. Whether you’re swing trading or day trading, this indicator provides clear visual cues to align with institutional flows, improving entry timing and risk management.
🚀Points of Innovation
Sigmoid-based probability threshold for signal filtering, ensuring only statistically significant Wyckoff patterns trigger alerts
ATR-normalized recovery measurement that adapts to market volatility, unlike static recovery checks in traditional indicators
Customizable volume spike multiplier to distinguish institutional volume from retail noise
Integrated dashboard legend with position and size options for personalized chart visualization
Hidden probability plots for advanced users to analyze underlying math without chart clutter
🔧Core Components
Support/Resistance Calculator: Scans a user-defined lookback period to establish dynamic levels for Spring and Upthrust detection
Volume Spike Detector: Compares current volume to a 10-period SMA, multiplied by a configurable factor to identify significant surges
Recovery Strength Analyzer: Uses ATR to measure price recovery after breaks, normalizing for different market conditions
Probability Model: Applies sigmoid function to combine volume and recovery data, generating a confidence score for each potential signal
🔥Key Features
Spring Detection: Spots accumulation when price dips below support but recovers strongly, helping traders enter longs at potential bottoms
Upthrust Detection: Identifies distribution when price spikes above resistance but falls back, alerting to possible short opportunities at tops
Customizable Inputs: Adjust lookback, volume multiplier, ATR period, and probability threshold to match your trading style and market
Visual Signals: Clear + (green) and - (red) labels on charts for instant recognition of accumulation and distribution phases
Alert System: Triggers notifications for signals and probability thresholds, keeping you informed without constant monitoring
🎨Visualization
Spring Signal: Green upward label (+) below the bar, indicating strong recovery after support break for accumulation
Upthrust Signal: Red downward label (-) above the bar, showing failed breakout above resistance for distribution
Dashboard Legend: Customizable table explaining signals, positioned anywhere on the chart for quick reference
📖Usage Guidelines
Core Settings
Support/Resistance Lookback
Default: 20
Range: 5-50
Description: Sets bars back for S/R levels; lower for recent sensitivity, higher for stable long-term zones – ideal for spotting Wyckoff phases
Volume Spike Multiplier
Default: 1.5
Range: 1.0-3.0
Description: Multiplies 10-period volume SMA; higher values filter to significant spikes, confirming institutional involvement in patterns
ATR for Recovery Measurement
Default: 5
Range: 2-20
Description: ATR period for recovery strength; shorter for volatile markets, longer for smoother analysis of post-break recoveries
Phase Transition Probability Threshold
Default: 0.9
Range: 0.5-0.99
Description: Minimum sigmoid probability for signals; higher for strict filtering, ensuring only high-confidence Wyckoff setups
Display Settings
Dashboard Position
Default: Top Right
Range: Various positions
Description: Places legend table on chart; choose based on layout to avoid overlapping price action
Dashboard Text Size
Default: Normal
Range: Auto to Huge
Description: Adjusts legend text; larger for visibility, smaller for minimal space use
✅Best Use Cases
Swing Trading: Identify Springs for long entries in downtrends turning to accumulation
Day Trading: Catch Upthrusts for short scalps during intraday distribution at resistance
Trend Reversal Confirmation: Use in conjunction with other indicators to validate phase shifts in ranging markets
Volatility Plays: Spot signals in high-volume environments like news events for quick reversals
⚠️Limitations
May produce false signals in low-volume or sideways markets where volume spikes are unreliable
Depends on historical data, so performance varies in unprecedented market conditions or gaps
Probability model is statistical, not predictive, and cannot account for external factors like news
💡What Makes This Unique
Probability-Driven Filtering: Sigmoid model combines multiple factors for superior signal quality over basic Wyckoff detectors
Adaptive Recovery: ATR normalization ensures reliability across assets and timeframes, unlike fixed-threshold tools
User-Centric Design: Tooltips, customizable dashboard, and alerts make it accessible yet powerful for all trader levels
🔬How It Works
Calculate S/R Levels:
Uses the highest high and the lowest low over the lookback period to set dynamic zones
Establishes baseline for detecting breaks in Wyckoff patterns
Detect Breaks and Recovery:
Checks for price breaking support/resistance, then recovering on volume
Measures recovery strength via ATR for volatility adjustment
Apply Probability Model:
Combines volume spike and recovery into a sigmoid function for confidence score
Triggers signal only if above threshold, plotting visuals and alerts
💡Note:
For optimal results, combine with price action analysis and test settings on historical charts. Remember, Wyckoff patterns are most effective in trending markets – use lower probability thresholds for practice, then increase for live trading to focus on high-quality setups.
Analisis Trend
Live Trading Metrics DashboardReal-Time Trading Data Table for Chart Analysis
This clean and professional dashboard displays essential trading metrics directly on your chart in an easy-to-read table format. Perfect for traders who need quick access to key volatility and momentum data without cluttering their chart with multiple indicators.
Key Metrics Displayed:
IBD Relative Strength (RS):
Professional Formula: Uses Investor's Business Daily methodology
Multi-Timeframe Analysis: Weighted calculation across 3, 6, 9, and 12-month periods
Performance Indicator: Shows how the instrument performs relative to its historical price action
Real-Time Updates: Values update with each bar for current market conditions
1.5 ATR (Average True Range):
Volatility Measurement: 14-period ATR multiplied by 1.5 for extended range analysis
Stop-Loss Placement: Ideal for setting dynamic stop-loss levels
Risk Management: Helps determine appropriate position sizing based on volatility
Breakout Targets: Useful for setting profit targets on breakout trades
1.5 ATR Percentage:
Relative Volatility: Shows 1.5 ATR as a percentage of current price
Cross-Asset Comparison: Enables volatility comparison across different instruments
Position Sizing: Helps calculate risk per trade as percentage of price
Market Context: Understand volatility relative to instrument value
How to Interpret:
Positive IBD RS: Instrument showing strength relative to historical performance
Negative IBD RS: Instrument showing weakness relative to historical performance
Higher ATR Values: Increased volatility, wider stops needed
Higher ATR %: Greater relative volatility for the instrument's price level
Perfect For:
Day traders needing quick volatility reference
Swing traders using IBD methodology
Position traders managing risk with ATR-based stops
Any trader wanting clean, organized data display
Average True Ranges with IBD RSAdvanced ATR Analysis with IBD Relative Strength
This comprehensive indicator combines Average True Range (ATR) analysis with IBD (Investor's Business Daily) Relative Strength calculation, providing both volatility measurement and momentum analysis in one powerful tool.
Key Features:
ATR Analysis:
Standard ATR: Customizable period (default 14) with multiple smoothing options
1.5x ATR: Extended range for wider stop-loss and target calculations
Smoothing Options: Choose between RMA, SMA, EMA, or WMA for ATR calculation
Customizable Colors: Distinct colors for easy visual identification
IBD Relative Strength:
Professional RS Formula: Uses the same calculation method as Investor's Business Daily
Multi-Timeframe Analysis: Compares current price to 3, 6, 9, and 12-month performance
Weighted Calculation: 40% weight on 3-month, 20% each on 6, 9, and 12-month performance
Zero-Based Scale: Values above 0 indicate outperformance, below 0 indicate underperformance
Trading Applications:
Volatility-Based Stops: Use ATR and 1.5x ATR for dynamic stop-loss placement
Position Sizing: ATR helps determine appropriate position size based on volatility
Relative Strength Analysis: IBD RS identifies stocks with superior momentum
Market Timing: High RS values often precede strong price moves
Risk Management: Combine volatility (ATR) with momentum (RS) for comprehensive analysis
Technical Details:
ATR Calculation: True Range smoothed over selected period with chosen method
IBD RS Formula: (40% × 3M) + (20% × 6M) + (20% × 9M) + (20% × 12M) - 100
Display: Separate pane indicator with customizable colors for each component
How to Interpret:
High ATR: Increased volatility, wider stops needed
Low ATR: Reduced volatility, tighter stops possible
Positive IBD RS: Stock outperforming market over measured periods
Negative IBD RS: Stock underperforming market over measured periods
Customizable Parameters:
ATR calculation length
Smoothing method for ATR
Individual colors for ATR, 1.5x ATR, and IBD RS lines
Perfect for swing traders and position traders who want to combine volatility analysis with relative strength momentum in their decision-making process. Particularly useful for stock selection and risk management.
Market Structure: HH/HL/LH/LL (v6, simple)What it does
Labels swing High/Low and classifies structure as HH / HL / LH / LL after confirmation.
Uses confirmed fractals (pivothigh/pivotlow) → no repaint after confirmation (there is a right-bar confirmation delay).
Optional swing connectors (lines), optional plain H/L when structure label is not applicable.
Plots last confirmed High/Low levels as reference.
Alerts when a new HH/HL/LH/LL is formed.
How it works
Swings are detected with ta.pivothigh() / ta.pivotlow() using user-defined left and right.
A pivot is confirmed only after right bars on the right—this is the only delay. Once confirmed, the label does not repaint.
Inputs
Left bars & Right bars – fractal sensitivity.
Connect swings with lines – draw lines between consecutive swings.
Show bullish (HH/HL) / Show bearish (LH/LL) – filter what to display.
Show plain H/L – draw H/L when classification is not HH/HL/LH/LL yet.
Recommended settings
1H–4H: left=2, right=2 (responsive).
1D+: left=3, right=3 (cleaner swing map).
Alerts provided
HH formed – new Higher High confirmed.
HL formed – new Higher Low confirmed.
LH formed – new Lower High confirmed.
LL formed – new Lower Low confirmed.
Use them to automate structure tracking or feed your strategy rules.
Tips
Trend up: a sequence of HH + HL; Trend down: LH + LL.
Combine with VWAP/EMA, liquidity zones, or volume/CVD to avoid chasing late signals.
The script is intentionally simple and lightweight; BOS/CHoCH can be added in a future update.
Limitations / Notes
Because the tool relies on confirmed pivots, signals are delayed by right bars.
This is not financial advice and not a buy/sell system on its own.
Changelog
v1.0 – Initial public release (Pine v6). Structure labels, swing connectors, last levels, and alert set.
Keywords
market structure, hh hl lh ll, swing, fractal, pivothigh, pivotlow, trend, structure labels, price action
🏛️ INSTITUTIONAL TRENDLINE v8 • Open Source🏛️ INSTITUTIONAL TRENDLINE v8 • Open Source
Adaptive S/R discovery with ML scoring, MTF confluence, and event-driven alerts
What it does (in one breath):
This indicator auto-discovers institutional-grade trendlines / dynamic support & resistance, scores them for quality using a dual-regime ML model (trend vs. range), validates them with multiple techniques (Theil–Sen, Huber, ATR/RSI/MACD/EMA, MTF confluence), then tracks breakouts, retests, failed breaks, proximity/touch events, and learns from outcomes to adapt over time. A visual panel summarizes stats, and optional heatmap/zones show where price is most “supported” or “capped”.
🚀 Quick Start (2 minutes)
Add to chart and leave defaults.
At the top of Inputs:
🎛️ Preset → choose your style: Scalper, Swing, Investor (or Custom).
🧬 Market Profile → pick Crypto/FX/Stocks + style or “Auto by Timeframe”.
Keep 🎯 Accuracy Mode = Quantum AI and ⚡ Performance = Maximum Quality if your device handles it.
Turn on 💥 Breakout Signals and 🚨 Alerts if you want notifications.
Read the right-side panel: Active Lines, Avg Q, Best Line, Market State, Nearest S/R, Top-3 lines, Pattern, Touch counts.
That’s it. You’ll see thinner, professional trendlines, small labels, optional zones, and tasteful break/retest markers.
🧠 How it works (plain English)
Discovery: It samples price pairs (with a swing-pivot bias) and fits many candidate lines.
Inlier-only R²: Instead of punishing outliers, it measures how tight touching bars are to a line.
ML Quality (0–100): Six signals (Touches, Volume @ touches, RSI, MACD, Volatility, Duration) are weighted differently for Trend vs Range regimes.
Validation: Rejects lines that disagree across Theil–Sen and Huber regressions (>15% slope deviation), fail slope/ATR filters, or lack MTF confluence.
Live tracking: Once a line is on the chart, the script watches for Breakouts → Retests → Failed breaks, and logs outcomes to continually re-weight the ML model (if enabled).
🎛️ Inputs (top section first)
1) Presets & Profiles (at the top)
🎛️ Preset
Scalper – lower lookbacks, faster, more signals.
Swing – balanced lookbacks, 2–4 lines per window.
Investor – longer lookbacks, fewer but stronger lines.
Custom – you control everything below.
🧬 Market Profile
Tailors thresholds for Crypto / FX / Stocks and your style (Scalper / Swing / Investor). Choose Auto by Timeframe to adapt from your chart resolution.
These two choices set “effective” requirements under the hood (min quality, R², proximity windows, cleanup cadence, etc.) so you don’t have to micromanage.
2) 🤖 Machine Learning Engine
Enable ML Enhancement – turns the adaptive scoring on/off.
ML Sensitivity – caps the maximum achievable score (lower = stricter).
Adaptive Learning – updates weights after each confirmed outcome.
Outcome Window (bars) & Target (ATR) – define when a breakout is counted as success or fail for learning.
Dual-Regime Models – separate weight sets for Trend and Range.
Tip: If results look “too picky,” raise ML Sensitivity slightly (e.g., 0.85→0.95).
3) 🎯 Accuracy & Filters
Minimum Touch Points / Quality / R² – base requirements for new lines.
Multi-Algorithm Validation – confirms slope across three regressions.
Volume / RSI / MACD / EMA / ATR filters – optional evidence checks.
No-Repaint Strict (HTF closed only) – for purists; fewer but cleaner MTF confirmations.
4) 🧠 Pro Logic / MTF
Swing-Anchored Sampling Bias – increases hits on meaningful swings.
HTF 1 / HTF 2 – reference frames for confluence (e.g., 4H & 1D).
HTF Bars to Scan / Touches Needed – how much agreement to demand.
Geometric Midline Agreement – proximity to HTF midlines (20-SMA).
Midline Distance Threshold (×ATR) – how strict that midline check is.
5) 💎 Visual System
Display Trendlines / Zones / Smart Labels / Breakout Signals / Heatmap – toggle pieces on/off.
Visual Theme & Color Intensity – pick a palette; v8 lines are thinner with subtle gradients.
Highlight Top-3 Lines – faint halo on the three highest-quality lines.
Limit Signal Markers / Bar – prevents clutter in fast moves.
Tip: For the cleanest chart: show Trendlines + Breakouts, keep Zones semi-transparent, and enable Heatmap only when you want confluence context.
6) 🚨 Alerts
Enable Smart Alerts – master switch.
Alert Quality Threshold – only alert for lines ≥ this Q%.
Base Proximity (ATR) & Slope-Adaptive Proximity – how close is “near”.
Retest / Failed-Break Windows – how long after a break to track.
Per-Line Cool-Off (bars) – spacing to avoid spam.
Consolidated JSON Alert/Bar – single JSON payload with all events per bar (great for bots).
Fire Inline Alerts (verbose) – pop real-time alerts the moment events occur.
Alert names (mapped to alertconditions):
🆕 New S/R Created
📍 Approaching Trendline
🎯 Touching Trendline
🟢 Bullish Breakout / 🔴 Bearish Breakdown
♻️ Bullish Retest / ♻️ Bearish Retest
⛔ Failed Break
7) ⚡ Performance
Performance Mode – quality vs speed.
Max New Lines per Lookback/Bar – caps how many fresh lines a bar can add.
Cleanup Interval (bars) & Max Lines to Keep – automatic memory & clutter control.
Theil–Sen Sampled Pairs – fewer = faster; more = robust.
📈 How to read the chart
Lines:
Color = Support (green) or Resistance (red) at current price.
Thickness/Style = relates to Quality and Touches (higher Q = slightly bolder).
Labels show a badge (💎 🏆 ⭐ ✅ 📊) with Q%. Tooltip lists touches, R², price@line, lookback, and which evidences are ON.
Zones: Soft confidence corridors around lines (ATR-scaled).
Heatmap: A faint background tint—dominant support, resistance, or neutral/confluence.
Break markers: tiny ▲ / ▼ (or 🚀/💀 when very strong). Retests and failed breaks are tagged separately.
Top-3 glow: subtle halo on the three best lines right now.
🧭 Trading workflow (example)
Scenario A – Trend continuation
Market panel shows TREND; Top-3 lines include two rising supports ≥90% Q.
Price approaches one of them → Touch → Bullish breakout above a local resistance line.
Wait for ♻️ Retest of that broken line from above; if RSI>50 & MACD>0 (shown in panel), open a long with stop just under the line or zone.
Exit partials at next resistance line; trail under the line.
Scenario B – Range fade
Panel says RANGE; heatmap is neutral/confluence.
Price tags a high-Q red line and prints Touch without breakout, while RSI>60 cools off.
Enter a mean-revert short with stop above the line; target midrange or next green line.
If a Bullish breakout fires during the trade → respect the Failed Break logic; exit quickly.
Scenario C – Breakout trader
Filter only lines with Q ≥ 90% and alerts ON.
When Breakout triggers with strength ≥ 4/7 (see panel), take a starter.
Add on Retest if it prints within your retest window and confluence still looks good.
Manage risk with ATR or zone width.
This is a levels & event indicator. It doesn’t replace your system; it gives objective lines and objective events around those lines.
✅ Best-practice setup
Presets/Profiles: Start with Swing + your Market Profile.
ML Sensitivity: 0.90–0.95 for most markets.
Alerts: Set Alert Quality ≥ 85–90, Cool-Off = 4–6 bars.
MTF: Use 4H + 1D on intraday; 1D + 1W on daily charts.
Clutter control: Max Lines ~200, Cleanup ~50 bars, Signal cap 6/bar (defaults are sensible).
No-repaint strict: Turn on for signal review; turn off if you want more frequent MTF confirmations in real time.
🔬 Research Mode (optional)
Enable 🧪 Research Mode to track win-rates by quality buckets. The panel shows Win% so you can calibrate your thresholds per market.
⚠️ Notes & limitations
This is open-source research software. Past performance ≠ future results.
Learning requires time: the ML engine adapts after outcomes; don’t expect instant magic.
Very low-liquidity symbols may produce fewer reliable lines; increase lookbacks or tighten filters.
MTF data uses request.security with no lookahead; turning No-Repaint Strict on can further reduce signals.
🧩 Troubleshooting
“Too many lines.” Raise Min Quality / R², lower Max Lines, or reduce cap per lookback.
“Too few lines.” Lower Min Quality a bit, raise ML Sensitivity, or choose an easier Preset/Market Profile.
“Alerts are spammy.” Raise Alert Quality, increase Cool-Off, increase Proximity threshold.
“Performance is slow.” Use Balanced / Fast, reduce Theil–Sen pairs, or extend Cleanup Interval.
📦 Included alertconditions (for one-click alert rules)
New S/R Created
Approaching Trendline
Touching Trendline
Bullish Breakout / Bearish Breakdown
Bullish Retest / Bearish Retest
Failed Break
Enjoy, share feedback, and feel free to fork.
If you publish ideas using it, please credit “INSTITUTIONAL TRENDLINE v8 • OS” so other traders can find the open-source original. Happy trading! 🫶
Auto-Fit Growth Trendline# **Theoretical Algorithmic Principles of the Auto-Fit Growth Trendline (AFGT)**
## **🎯 What Does This Algorithm Do?**
The Auto-Fit Growth Trendline is an advanced technical analysis system that **automates the identification of long-term growth trends** and **projects future price levels** based on historical cyclical patterns.
### **Primary Functionality:**
- **Automatically detects** the most significant lows in regular periods (monthly, quarterly, semi-annually, annually)
- **Constructs a dynamic trendline** that connects these historical lows
- **Projects the trend into the future** with high mathematical precision
- **Generates Fibonacci bands** that act as dynamic support and resistance levels
- **Automatically adapts** to different timeframes and market conditions
### **Strategic Purpose:**
The algorithm is designed to identify **fundamental value zones** where price has historically found support, enabling traders to:
- Identify optimal entry points for long positions
- Establish realistic price targets based on mathematical projections
- Recognize dynamic support and resistance levels
- Anticipate long-term price movements
---
## **🧮 Core Mathematical Foundations**
### **Adaptive Temporal Segmentation Theory**
The algorithm is based on **dynamic temporal partition theory**, where time is divided into mathematically coherent uniform intervals. It uses modular transformations to create bijective mappings between continuous timestamps and discrete periods, ensuring each temporal point belongs uniquely to a specific period.
**What does this achieve?** It allows the algorithm to automatically identify natural market cycles (annual, quarterly, etc.) without manual intervention, adapting to the inherent periodicity of each asset.
The temporal mapping function implements a **discrete affine transformation** that normalizes different frequencies (monthly, quarterly, semi-annual, annual) to a space of unique identifiers, enabling consistent cross-temporal comparative analysis.
---
## **📊 Local Extrema Detection Theory**
### **Multi-Point Retrospective Validation Principle**
Local minima detection is founded on **relative extrema theory with sliding window**. Instead of using a simple minimum finder, it implements a cross-validation system that examines the persistence of the extremum across multiple historical periods.
**What problem does this solve?** It eliminates false minima caused by temporal volatility, identifying only those points that represent true historical support levels with statistical significance.
This approach is based on the **statistical confirmation principle**, where a minimum is only considered valid if it maintains its extremum condition during a defined observation period, significantly reducing false positives caused by transitory volatility.
---
## **🔬 Robust Interpolation Theory with Outlier Control**
### **Contextual Adaptive Interpolation Model**
The mathematical core uses **piecewise linear interpolation with adaptive outlier correction**. The key innovation lies in implementing a **contextual anomaly detector** that identifies not only absolute extreme values, but relative deviations to the local context.
**Why is this important?** Financial markets contain extreme events (crashes, bubbles) that can distort projections. This system identifies and appropriately weights them without completely eliminating them, preserving directional information while attenuating distortions.
### **Implicit Bayesian Smoothing Algorithm**
When an outlier is detected (deviation >300% of local average), the system applies a **simplified Kalman filter** that combines the current observation with a local trend estimation, using a weight factor that preserves directional information while attenuating extreme fluctuations.
---
## **📈 Stabilized Extrapolation Theory**
### **Exponential Growth Model with Dampening**
Extrapolation is based on a **modified exponential growth model with progressive dampening**. It uses multiple historical points to calculate local growth ratios, implements statistical filtering to eliminate outliers, and applies a dampening factor that increases with extrapolation distance.
**What advantage does this offer?** Long-term projections in finance tend to be exponentially unrealistic. This system maintains short-to-medium term accuracy while converging toward realistic long-term projections, avoiding the typical "exponential explosions" of other methods.
### **Asymptotic Convergence Principle**
For long-term projections, the algorithm implements **controlled asymptotic convergence**, where growth ratios gradually converge toward pre-established limits, avoiding unrealistic exponential projections while preserving short-to-medium term accuracy.
---
## **🌟 Dynamic Fibonacci Projection Theory**
### **Continuous Proportional Scaling Model**
Fibonacci bands are constructed through **uniform proportional scaling** of the base curve, where each level represents a linear transformation of the main curve by a constant factor derived from the Fibonacci sequence.
**What is its practical utility?** It provides dynamic resistance and support levels that move with the trend, offering price targets and profit-taking points that automatically adapt to market evolution.
### **Topological Preservation Principle**
The system maintains the **topological properties** of the base curve in all Fibonacci projections, ensuring that spatial and temporal relationships are consistently preserved across all resistance/support levels.
---
## **⚡ Adaptive Computational Optimization**
### **Multi-Scale Resolution Theory**
It implements **automatic multi-resolution analysis** where data granularity is dynamically adjusted according to the analysis timeframe. It uses the **adaptive Nyquist principle** to optimize the signal-to-noise ratio according to the temporal observation scale.
**Why is this necessary?** Different timeframes require different levels of detail. A 1-minute chart needs more granularity than a monthly one. This system automatically optimizes resolution for each case.
### **Adaptive Density Algorithm**
Calculation point density is optimized through **adaptive sampling theory**, where calculation frequency is adjusted according to local trend curvature and analysis timeframe, balancing visual precision with computational efficiency.
---
## **🛡️ Robustness and Fault Tolerance**
### **Graceful Degradation Theory**
The system implements **multi-level graceful degradation**, where under error conditions or insufficient data, the algorithm progressively falls back to simpler but reliable methods, maintaining basic functionality under any condition.
**What does this guarantee?** That the indicator functions consistently even with incomplete data, new symbols with limited history, or extreme market conditions.
### **State Consistency Principle**
It uses **mathematical invariants** to guarantee that the algorithm's internal state remains consistent between executions, implementing consistency checks that validate data structure integrity in each iteration.
---
## **🔍 Key Theoretical Innovations**
### **A. Contextual vs. Absolute Outlier Detection**
It revolutionizes traditional outlier detection by considering not only the absolute magnitude of deviations, but their relative significance within the local context of the time series.
**Practical impact:** It distinguishes between legitimate market movements and technical anomalies, preserving important events like breakouts while filtering noise.
### **B. Extrapolation with Weighted Historical Memory**
It implements a memory system that weights different historical periods according to their relevance for current prediction, creating projections more adaptable to market regime changes.
**Competitive advantage:** It automatically adapts to fundamental changes in asset dynamics without requiring manual recalibration.
### **C. Automatic Multi-Timeframe Adaptation**
It develops an automatic temporal resolution selection system that optimizes signal extraction according to the intrinsic characteristics of the analysis timeframe.
**Result:** A single indicator that functions optimally from 1-minute to monthly charts without manual adjustments.
### **D. Intelligent Asymptotic Convergence**
It introduces the concept of controlled asymptotic convergence in financial extrapolations, where long-term projections converge toward realistic limits based on historical fundamentals.
**Added value:** Mathematically sound long-term projections that avoid the unrealistic extremes typical of other extrapolation methods.
---
## **📊 Complexity and Scalability Theory**
### **Optimized Linear Complexity Model**
The algorithm maintains **linear computational complexity** O(n) in the number of historical data points, guaranteeing scalability for extensive time series analysis without performance degradation.
### **Temporal Locality Principle**
It implements **temporal locality**, where the most expensive operations are concentrated in the most relevant temporal regions (recent periods and near projections), optimizing computational resource usage.
---
## **🎯 Convergence and Stability**
### **Probabilistic Convergence Theory**
The system guarantees **probabilistic convergence** toward the real underlying trend, where projection accuracy increases with the amount of available historical data, following **law of large numbers** principles.
**Practical implication:** The more history an asset has, the more accurate the algorithm's projections will be.
### **Guaranteed Numerical Stability**
It implements **intrinsic numerical stability** through the use of robust floating-point arithmetic and validations that prevent overflow, underflow, and numerical error propagation.
**Result:** Reliable operation even with extreme-priced assets (from satoshis to thousand-dollar stocks).
---
## **💼 Comprehensive Practical Application**
**The algorithm functions as a "financial GPS"** that:
1. **Identifies where we've been** (significant historical lows)
2. **Determines where we are** (current position relative to the trend)
3. **Projects where we're going** (future trend with specific price levels)
4. **Provides alternative routes** (Fibonacci bands as alternative targets)
This theoretical framework represents an innovative synthesis of time series analysis, approximation theory, and computational optimization, specifically designed for long-term financial trend analysis with robust and mathematically grounded projections.
Market Outlook Score (MOS)Overview
The "Market Outlook Score (MOS)" is a custom technical indicator designed for TradingView, written in Pine Script version 6. It provides a quantitative assessment of market conditions by aggregating multiple factors, including trend strength across different timeframes, directional movement (via ADX), momentum (via RSI changes), volume dynamics, and volatility stability (via ATR). The MOS is calculated as a weighted score that ranges typically between -1 and +1 (though it can exceed these bounds in extreme conditions), where positive values suggest bullish (long) opportunities, negative values indicate bearish (short) setups, and values near zero imply neutral or indecisive markets.
This indicator is particularly useful for traders seeking a holistic "outlook" score to gauge potential entry points or market bias. It overlays on a separate pane (non-overlay mode) and visualizes the score through horizontal threshold lines and dynamic labels showing the numeric MOS value along with a simple trading decision ("Long", "Short", or "Neutral"). The script avoids using the plot function for compatibility reasons (e.g., potential TradingView bugs) and instead relies on hline for static lines and label.new for per-bar annotations.
Key features:
Multi-Timeframe Analysis: Incorporates slope data from 5-minute, 15-minute, and 30-minute charts to capture short-term trends.
Trend and Strength Integration: Uses ADX to weight trend bias, ensuring stronger signals in trending markets.
Momentum and Volume: Includes RSI momentum impulses and volume deviations for added confirmation.
Volatility Adjustment: Factors in ATR changes to assess market stability.
Customizable Inputs: Allows users to tweak periods for lookback, ADX, and ATR.
Decision Labels: Automatically classifies the MOS into actionable categories with visual labels.
This indicator is best suited for intraday or swing trading on volatile assets like stocks, forex, or cryptocurrencies. It does not generate buy/sell signals directly but can be combined with other tools (e.g., moving averages or oscillators) for comprehensive strategies.
Inputs
The script provides three user-configurable inputs via TradingView's input panel:
Lookback Period (lookback):
Type: Integer
Default: 20
Range: Minimum 10, Maximum 50
Purpose: Defines the number of bars used in slope calculations for trend analysis. A shorter lookback makes the indicator more sensitive to recent price action, while a longer one smooths out noise for longer-term trends.
ADX Period (adxPeriod):
Type: Integer
Default: 14
Range: Minimum 5, Maximum 30
Purpose: Sets the smoothing period for the Average Directional Index (ADX) and its components (DI+ and DI-). Standard value is 14, but shorter periods increase responsiveness, and longer ones reduce false signals.
ATR Period (atrPeriod):
Type: Integer
Default: 14
Range: Minimum 5, Maximum 30
Purpose: Determines the period for the Average True Range (ATR) calculation, which measures volatility. Adjust this to match your trading timeframe—shorter for scalping, longer for positional trading.
These inputs allow customization without editing the code, making the indicator adaptable to different market conditions or user preferences.
Core Calculations
The MOS is computed through a series of steps, blending trend, momentum, volume, and volatility metrics. Here's a breakdown:
Multi-Timeframe Slopes:
The script fetches data from higher timeframes (5m, 15m, 30m) using request.security.
Slope calculation: For each timeframe, it computes the linear regression slope of price over the lookback period using the formula:
textslope = correlation(close, bar_index, lookback) * stdev(close, lookback) / stdev(bar_index, lookback)
This measures the rate of price change, where positive slopes indicate uptrends and negative slopes indicate downtrends.
Variables: slope5m, slope15m, slope30m.
ATR (Average True Range):
Calculated using ta.atr(atrPeriod).
Represents average volatility over the specified period. Used later to derive volatility stability.
ADX (Average Directional Index):
A detailed, manual implementation (not using built-in ta.adx for customization):
Computes upward movement (upMove = high - high ) and downward movement (downMove = low - low).
Derives +DM (Plus Directional Movement) and -DM (Minus Directional Movement) by filtering non-relevant moves.
Smooths true range (trur = ta.rma(ta.tr(true), adxPeriod)).
Calculates +DI and -DI: plusDI = 100 * ta.rma(plusDM, adxPeriod) / trur, similarly for minusDI.
DX: dx = 100 * abs(plusDI - minusDI) / max(plusDI + minusDI, 0.0001).
ADX: adx = ta.rma(dx, adxPeriod).
ADX values above 25 typically indicate strong trends; here, it's normalized (divided by 50) to influence the trend bias.
Volume Delta (5m Timeframe):
Fetches 5m volume: volume_5m = request.security(syminfo.tickerid, "5", volume, lookahead=barmerge.lookahead_on).
Computes a 12-period SMA of volume: avgVolume = ta.sma(volume_5m, 12).
Delta: (volume_5m - avgVolume) / avgVolume (or 0 if avgVolume is zero).
This measures relative volume spikes, where positive deltas suggest increased interest (bullish) and negative suggest waning activity (bearish).
MOS Components and Final Calculation:
Trend Bias: Average of the three slopes, normalized by close price and scaled by 100, then weighted by ADX influence: (slope5m + slope15m + slope30m) / 3 / close * 100 * (adx / 50).
Emphasizes trends in strong ADX conditions.
Momentum Impulse: Change in 5m RSI(14) over 1 bar, divided by 50: ta.change(request.security(syminfo.tickerid, "5", ta.rsi(close, 14), lookahead=barmerge.lookahead_on), 1) / 50.
Captures short-term momentum shifts.
Volatility Clarity: 1 - ta.change(atr, 1) / max(atr, 0.0001).
Measures ATR stability; values near 1 indicate low volatility changes (clearer trends), while lower values suggest erratic markets.
MOS Formula: Weighted average:
textmos = (0.35 * trendBias + 0.25 * momentumImpulse + 0.2 * volumeDelta + 0.2 * volatilityClarity)
Weights prioritize trend (35%) and momentum (25%), with volume and volatility at 20% each. These can be adjusted in code for experimentation.
Trading Decision:
A variable mosDecision starts as "Neutral".
If mos > 0.15, set to "Long".
If mos < -0.15, set to "Short".
Thresholds (0.15 and -0.15) are hardcoded but can be modified.
Visualization and Outputs
Threshold Lines (using hline):
Long Threshold: Horizontal dashed green line at +0.15.
Short Threshold: Horizontal dashed red line at -0.15.
Neutral Line: Horizontal dashed gray line at 0.
These provide visual reference points for MOS interpretation.
Dynamic Labels (using label.new):
Placed at each bar's index and MOS value.
Text: Formatted MOS value (e.g., "0.2345") followed by a newline and the decision (e.g., "Long").
Style: Downward-pointing label with gray background and white text for readability.
This replaces a traditional plot line, showing exact values and decisions per bar without cluttering the chart.
The indicator appears in a separate pane below the main price chart, making it easy to monitor alongside price action.
Usage Instructions
Adding to TradingView:
Copy the script into TradingView's Pine Script editor.
Save and add to your chart via the "Indicators" menu.
Select a symbol and timeframe (e.g., 1-minute for intraday).
Interpretation:
Long Signal: MOS > 0.15 – Consider bullish positions if supported by other indicators.
Short Signal: MOS < -0.15 – Potential bearish setups.
Neutral: Between -0.15 and 0.15 – Avoid trades or wait for confirmation.
Watch for MOS crossings of thresholds for momentum shifts.
Combine with price patterns, support/resistance, or volume for better accuracy.
Limitations and Considerations:
Lookahead Bias: Uses barmerge.lookahead_on for multi-timeframe data, which may introduce minor forward-looking bias in backtesting (use with caution).
No Alerts Built-In: Add custom alerts via TradingView's alert system based on MOS conditions.
Performance: Tested for compatibility; may require adjustments for illiquid assets or extreme volatility.
Backtesting: Use TradingView's strategy tester to evaluate historical performance, but remember past results don't guarantee future outcomes.
Customization: Edit weights in the MOS formula or thresholds to fit your strategy.
This indicator distills complex market data into a single score, aiding decision-making while encouraging users to verify signals with additional analysis. If you need modifications, such as restoring plot functionality or adding features, provide details for further refinement.
VWAP For Loop [BackQuant]VWAP For Loop
What this tool does—in one sentence
A volume-weighted trend gauge that anchors VWAP to a calendar period (day/week/month/quarter/year) and then scores the persistence of that VWAP trend with a simple for-loop “breadth” count; the result is a clean, threshold-driven oscillator plus an optional VWAP overlay and alerts.
Plain-English overview
Instead of judging raw price alone, this indicator focuses on anchored VWAP —the market’s average price paid during your chosen institutional period. It then asks a simple question across a configurable set of lookback steps: “Is the current anchored VWAP higher than it was i bars ago—or lower?” Each “yes” adds +1, each “no” adds −1. Summing those answers creates a score that reflects how consistently the volume-weighted trend has been rising or falling. Extreme positive scores imply persistent, broad strength; deeply negative scores imply persistent weakness. Crossing predefined thresholds produces objective long/short events and color-coded context.
Under the hood
• Anchoring — VWAP using hlc3 × volume resets exactly when the selected period rolls:
Day → session change, Week → new week, Month → new month, Quarter/Year → calendar quarter/year.
• For-loop scoring — For lag steps i = , compare today’s VWAP to VWAP .
– If VWAP > VWAP , add +1.
– Else, add −1.
The final score ∈ , where N = (end − start + 1). With defaults (1→45), N = 45.
• Signal logic (stateful)
– Long when score > upper (e.g., > 40 with N = 45 → VWAP higher than ~89% of checked lags).
– Short on crossunder of lower (e.g., dropping below −10).
– A compact state variable ( out ) holds the current regime: +1 (long), −1 (short), otherwise unchanged. This “stickiness” avoids constant flipping between bars without sufficient evidence.
Why VWAP + a breadth score?
• VWAP aggregates both price and volume—where participants actually traded.
• The breadth-style count rewards consistency of the anchored trend, not one-off spikes.
• Thresholds give you binary structure when you need it (alerts, automation), without complex math.
What you’ll see on the chart
• Sub-pane oscillator — The for-loop score line, colored by regime (long/short/neutral).
• Main-pane VWAP (optional) — Even though the indicator runs off-chart, the anchored VWAP can be overlaid on price (toggle visibility and whether it inherits trend colors).
• Threshold guides — Horizontal lines for the long/short bands (toggle).
• Cosmetics — Optional candle painting and background shading by regime; adjustable line width and colors.
Input map (quick reference)
• VWAP Anchor Period — Day, Week, Month, Quarter, Year.
• Calculation Start/End — The for-loop lag window . With 1→45, you evaluate 45 comparisons.
• Long/Short Thresholds — Default upper=40, lower=−10 (asymmetric by design; see below).
• UI/Style — Show thresholds, paint candles, background color, line width, VWAP visibility and coloring, custom long/short colors.
Interpreting the score
• Near +N — Current anchored VWAP is above most historical VWAP checkpoints in the window → entrenched strength.
• Near −N — Current anchored VWAP is below most checkpoints → entrenched weakness.
• Between — Mixed, choppy, or transitioning regimes; use thresholds to avoid reacting to noise.
Why the asymmetric default thresholds?
• Long = score > upper (40) — Demands unusually broad upside persistence before declaring “long regime.”
• Short = crossunder lower (−10) — Triggers only on downward momentum events (a fresh breach), not merely being below −10. This combination tends to:
– Capture sustained uptrends only when they’re very strong.
– Flag downside turns as they occur, rather than waiting for an extreme negative breadth.
Tuning guide
Choose an anchor that matches your horizon
– Intraday scalps : Day anchor on intraday charts.
– Swing/position : Month or Quarter anchor on 1h/4h/D charts to capture institutional cycles.
Pick the for-loop window
– Larger N (bigger end) = stronger evidence requirement, smoother oscillator.
– Smaller N = faster, more reactive score.
Set achievable thresholds
– Ensure upper ≤ N and lower ≥ −N ; if N=30, an upper of 40 can never trigger.
– Symmetric setups (e.g., +20/−20) are fine if you want balanced behavior.
Match visuals to intent
– Enabling VWAP coloring lets you see regime directly on price.
– Background shading is useful for discretionary reading; turn it off for cleaner automation displays.
Playbook examples
• Trend confirmation with disciplined entries — On Month anchor, N=45, upper=38–42: when the long regime engages, use pullbacks toward anchored VWAP on the main pane for entries, with stops just beyond VWAP or a recent swing.
• Downside transition detection — Keep lower around −8…−12 and watch for crossunders; combine with price losing anchored VWAP to validate risk-off.
• Intraday bias filter — Day anchor on a 5–15m chart, N=20–30, upper ~ 16–20, lower ~ −6…−10. Only take longs while score is positive and above a midline you define (e.g., 0), and shorts only after a genuine crossunder.
Behavior around resets (important)
Anchored VWAP is hard-reset each period. Immediately after a reset, the series can be young and comparisons to pre-reset values may span two periods. If you prefer within-period evaluation only, choose end small enough not to bridge typical period length on your timeframe, or accept that the breadth test intentionally spans regimes.
Alerts included
• VWAP FL Long — Fires when the long condition is true (score > upper and not in short).
• VWAP FL Short — Fires on crossunder of the lower threshold (event-driven).
Messages include {{ticker}} and {{interval}} placeholders for routing.
Strengths
• Simple, transparent math — Easy to reason about and validate.
• Volume-aware by construction — Decisions reference VWAP, not just price.
• Robust to single-bar noise — Needs many lags to agree before flipping state (by design, via thresholds and the stateful output).
Limitations & cautions
• Threshold feasibility — If N < upper or |lower| > N, signals will never trigger; always cross-check N.
• Path dependence — The state variable persists until a new event; if you want frequent re-evaluation, lower thresholds or reduce N.
• Regime changes — Calendar resets can produce early ambiguity; expect a few bars for the breadth to mature.
• VWAP sensitivity to volume spikes — Large prints can tilt VWAP abruptly; that behavior is intentional in VWAP-based logic.
Suggested starting profiles
• Intraday trend bias : Anchor=Day, N=25 (1→25), upper=18–20, lower=−8, paint candles ON.
• Swing bias : Anchor=Month, N=45 (1→45), upper=38–42, lower=−10, VWAP coloring ON, background OFF.
• Balanced reactivity : Anchor=Week, N=30 (1→30), upper=20–22, lower=−10…−12, symmetric if desired.
Implementation notes
• The indicator runs in a separate pane (oscillator), but VWAP itself is drawn on price using forced overlay so you can see interactions (touches, reclaim/loss).
• HLC3 is used for VWAP price; that’s a common choice to dampen wick noise while still reflecting intrabar range.
• For-loop cap is kept modest (≤50) for performance and clarity.
How to use this responsibly
Treat the oscillator as a bias and persistence meter . Combine it with your entry framework (structure breaks, liquidity zones, higher-timeframe context) and risk controls. The design emphasizes clarity over complexity—its edge is in how strictly it demands agreement before declaring a regime, not in predicting specific turns.
Summary
VWAP For Loop distills the question “How broadly is the anchored, volume-weighted trend advancing or retreating?” into a single, thresholded score you can read at a glance, alert on, and color through your chart. With careful anchoring and thresholds sized to your window length, it becomes a pragmatic bias filter for both systematic and discretionary workflows.
Smart BOS & FVG Signal IndicatorDescription:
This script is designed to help traders identify high-probability trade setups using a combination of Break of Structure (BOS) detection, Fair Value Gaps (FVGs), and an EMA retest filter.
How It Works
Break of Structure (BOS): The indicator automatically detects BOS events when price takes out previous highs/lows. Users can choose between strict or equal-high/low comparisons with the Comparison Mode setting.
Fair Value Gaps (FVGs): Highlighted zones show areas of imbalance in price. You can choose whether signals require the FVG to still be open.
EMA Retest Filter: A dynamic EMA check confirms whether price retests a moving average after BOS, helping filter out weaker setups.
Trade Signals
Green Arrows (Buy Signals): Trigger when a bullish BOS aligns with FVG and EMA retest conditions.
Red Arrows (Sell Signals): Trigger when a bearish BOS aligns with FVG and EMA retest conditions.
Key Features
Toggle “Require FVG Still Open at Signal” for stricter setups.
Adjust BOS Comparison Mode between standard and allowEqual for different market structures.
Clean visualization: arrows and highlights mark where valid trade opportunities occur.
How to Use
Apply the indicator to your chart.
Use BOS + FVG confluence to spot continuation or reversal opportunities.
Filter signals with the EMA retest option to reduce noise.
Best paired with strong risk management and confirmation from your overall strategy.
Range Percent Histogram📌 Range Percent Histogram – Indicator Description
The Range Percent Histogram is a custom indicator that behaves like a traditional volume histogram, but instead of showing traded volume it displays the percentage range of each candle.
In other words, the height of each bar represents how much the price moved (in percentage terms) within that candle, from its low to its high.
🔧 What it shows
The indicator has two main components:
Component Description
Histogram Bars Columns plotted in red or green depending on the candle direction (green = bullish candle, red = bearish). The height of each bar = (high - low) / low * 100. That means a candle that moved, for example, 1 % from its lowest point to its highest point will show a bar with 1 % height.
Moving Average (optional) A 20-period Simple Moving Average applied directly to the bar values. It can be turned ON/OFF via a checkbox and helps you detect whether current range activity is above or below the average range of the past candles.
⚙️ How it works
Every time a new candle closes, the indicator calculates its range and converts it into a percentage.
This value is drawn as a column under the chart.
If the closing price is above the opening price → the bar is green (bullish range).
If the closing price is below the opening price → the bar is red (bearish range).
When the Show Moving Average option is enabled, a smooth line is plotted on top of the histogram representing the average percentage range of the last 20 candles.
📈 How to use it
This indicator is very helpful for detecting moments of range expansion or contraction.
One powerful way to use it is similar to a volume exhaustion / low-volume pattern:
Situation Interpretation
Consecutive bars with very low height Price is in a period of low volatility → possible accumulation or "pause" phase.
A sudden large bar after a series of small ones Indicates a strong pickup in volatility → often marks the start of a new impulse in the direction of the breakout.
ICT Killzones + HTF FVG [JewlsTagara]This indicator plots the high and low (h/l) of every kill
zone period included with HTF FVG's.
Best use;
- 15m, 30m, 1hr, 4h FVG
- Adjust lunch to end at 1:30pm EST and NYPM 17:00 EST
Strategy:
- When price sweeps kill zone h/l into/in a HTF FVG
- Enter a 1 - 3m iFVG.
- Target 1:1 or 1:2 RR
note: you make use whatever entry model you like.
9 Sequential for Stock Screener9 Sequential for Stock Screener. Use this to forecast the buy/sell signal for your stocks. It can be integrated into the stock screener to scan the stocks in the market. green arrow means buy signal, red arrow means sell signal.
ICT Killzones + HTF FVG [JewlsTagara]This indicator plots the hits and lows of every kill
zone period included with HTF FVG's.
Best use;
- 15m, 30m, 1hr, 4h FVG
- Adjust lunch to end at 1:30pm EST and NYPM 17:00 EST
Strategy:
- When price sweeps kill zone h/l into a HTF FVG
- Enter a 1 - 3m iFVG.
note: you make user whatever entry model you like.
Trading Macro Windows by BW v2
Trading Macros by BW: Integrating ICT Concepts for Session Analysis
This indicator combines two key Inner Circle Trader (ICT) concepts—Change in State of Delivery (CISD) or Inverted Fair Value Gap (IFVG) signals with Macro Time Windows—to provide a unified tool for analyzing intraday price action, particularly during Pacific Time (PT) sessions. Rather than simply merging existing scripts, this integration creates a cohesive visual framework that highlights how macro consolidation periods interact with potential reversal or continuation signals like CISD or IFVG. By overlaying macro candle styling and borders on the chart alongside selectable signal lines, traders can better contextualize setups within ICT's macro narrative, where price often manipulates liquidity during these windows before displacing toward higher-timeframe objectives.
Core Components and How They Work Together:
Macro Time Windows (Inspired by ICT's Macro Periods):
ICT emphasizes "macro" as 30-minute windows (e.g., 06:45–07:15 PT, 07:45–08:15 PT, up to 11:45–12:15 PT) where price tends to consolidate, sweep liquidity, or form key structures like Fair Value Gaps (FVGs). These periods set the stage for the session's directional bias.
The indicator styles candles within these windows using a user-defined color for wicks, borders, and bodies (translucent for visibility). This visual emphasis helps traders focus on activity inside macros, where reversals or continuations often originate.
Borders are drawn as vertical lines at the start and end of each window (with a +5 minute buffer to capture related activity), using a dotted style by default. This creates a "study zone" that encapsulates macro events, allowing traders to assess if price is respecting or violating these zones in alignment with broader ICT models like the Power of 3 (AMD cycle).
Toggle: "Macro Candles Enabled" (default: true) – Turn off to disable styling and borders if focusing solely on signals.
CISD or IFVG Signals (Selectable Mode):
Mode Selection: Choose between "Change in the State of Delivery" (CISD) or "IFVG" (default: IFVG). Both detect shifts in market delivery during specific 30-minute slices (15–45 or 17–45 minutes past the hour in PT sessions).
CISD Mode: Based on ICT's definition of a sudden directional shift, this identifies aggressive displacements after sweeping recent highs/lows. It uses a rolling reference high/low over 6 bars, checks for sweeps (penetrating by at least 2 ticks in the last 2-3 bars), reclamation (closing beyond the reference with at least 50% body), and displacement (50% of prior range or an immediate FVG of 6+ ticks). Signals plot a horizontal line from the close, extending 24 bars right, labeled "CISD."
IFVG Mode: Focuses on Inverted Fair Value Gaps, where a bullish FVG (low > high by 13+ ticks) forms but is inverted (closed below) in the same slice, signaling bearish intent (or vice versa). This targets violations against opposing liquidity, often leading to raids on external ranges. Signals plot similarly, labeled "IFVG."
Shared Logic: Both modes enforce a 55-bar cooldown to prevent clustering, operate only during PT sessions (06:30–13:00), and use tick-based thresholds for precision across instruments. The integration with macros allows traders to see if signals occur within or at the edges of macro windows, enhancing confirmation—for example, a CISD inside a macro might indicate a manipulated reversal toward the session's true objective.
Toggle: "Signals Enabled" (default: true) – Turn off to hide all signal lines and labels, isolating the macro visualization.
How Components Interact:
Macro windows provide the "narrative context" (consolidation/manipulation), while CISD/IFVG signals detect the "delivery shift" (displacement). Together, they form a mashup that justifies publication: isolated signals can be noisy, but when filtered by macro periods, they align with ICT's session model. For instance, an IFVG inversion during a macro might confirm a liquidity sweep before targeting PD arrays or order blocks.
No external dependencies; all calculations are self-contained using Pine's built-in functions like ta.highest/lowest for references and time-based sessions for windows.
Usage Guidelines:
Apply to intraday charts (e.g., 1-5 min) or stocks during PT hours.
Look for confluence: A bull IFVG signal post-macro low sweep might target the next macro high or daily bias.
Customize colors/styles for signals (solid/dashed/dotted lines) and macros to suit your chart.
Backtest in replay mode to observe how macros frame signals—e.g., price often respects macro borders as S/R.
Limitations: Timezone-fixed to PT (America/Los_Angeles); signals are directional hints, not trade entries. Combine with ICT tools like order blocks or liquidity pools for full setups.
This script draws from community ICT implementations but refines them into a single, purpose-built tool for macro-driven trading, reducing chart clutter while emphasizing interconnected concepts. Feedback welcome!
Tamil own - MTF RSI Scanner 🚥so, if all RSI is green then total is 31
if all are red, it will be -31 Show.
if 31 then show with green bg
if -31 then show with red background
others just show the value.
Daily Seasonality Strength + PredictionDaily Seasonality Strength + Prediction
Seasonality Strength:
This indicator measures seasonality strength by comparing predicted seasonal returns with actual returns, using the inverse of MSE (higher values mean stronger seasonality).
This script is for informational and educational purposes only. It does not constitute financial, investment, or trading advice. I am not a financial advisor. Any decisions you make based on this indicator are your own responsibility. Always do your own research and consult with a qualified financial professional before making any investment decisions.
Past performance is no guarantee of future results. The value of the instruments may fluctuate and is not guaranteed
Daily Seasonality Strength + Prediction TableDaily Seasonality Strength + Prediction Table
Return Estimates:
This indicator uses historical price data to calculate average returns for each day (of the week or month) and uses these to predict the next day’s return.
Seasonality Strength:
It measures seasonality strength by comparing predicted returns with actual returns, using the inverse of MSE (higher values mean stronger seasonality).
supports up to 10 assets
This script is for informational and educational purposes only. It does not constitute financial, investment, or trading advice. I am not a financial advisor. Any decisions you make based on this indicator are your own responsibility. Always do your own research and consult with a qualified financial professional before making any investment decisions.
Past performance is no guarantee of future results. The value of the instruments may fluctuate and is not guaranteed
HMA Trendlinie – + HTF & ATR Filter📌 HMA Trendline – User Guide
What it does
The indicator plots a Hull Moving Average (HMA) directly on the price chart.
It colors the line according to market conditions:
Green → Bullish trend (HMA rising)
Red → Bearish trend (HMA falling)
Yellow → Sideways (HMA slope too flat → no clear trend)
Inputs
Source (src): The data used to calculate the HMA (default = close).
HMA Length (hmaLen): Number of bars used to smooth the HMA.
Smaller values = more sensitive, reacts faster.
Larger values = smoother, better for long-term trend filtering.
Slope Lookback (slopeLookback): Number of bars used to measure slope.
Slope Threshold (slopeThreshold %): Minimum percentage change required for the trend to be considered bullish or bearish.
Example: 0.20% → if HMA changes less than ±0.2% over the lookback period, it is considered sideways.
How to read it
Line Color
Green = Uptrend → favor long positions.
Red = Downtrend → favor short/avoid longs.
Yellow = Range/Flat → trend-following signals are unreliable.
Trend Changes
A green triangle appears when the trend turns bullish.
A red triangle appears when the trend turns bearish.
(Optional: yellow dots for sideways start can be disabled in the code).
Trading Usage
Filter: Only trade in the direction of the line (long if green, short if red).
Pullbacks: Price pulling back to the HMA can provide entries in the direction of the trend.
Sideways (yellow): Better to avoid trend trades – market likely consolidating.
Example Settings
Crypto (high volatility): hmaLen = 55, slopeLookback = 10, slopeThreshold = 0.30 – 0.50%.
Stocks (lower volatility): hmaLen = 100–200, slopeLookback = 10–20, slopeThreshold = 0.10 – 0.20%.
👉 In short: This indicator is a trend filter.
Use it to quickly identify market direction and avoid trading when the market is flat.
Ultimate Webby RSI 2.0 for MNQ 3m
🔎 Introduction
This is a flexible version of Amphibiantrading’s Webby RSI concept, optimized for MNQ 3-minute trading.
It normalizes the distance of price from moving averages (EMA/SMA) using ATR, producing stretch histograms that highlight overextended moves.
I extended it with:
✅ Swing and Scalper presets (instantly switch via dropdown)
✅ Custom mode (type in your own parameters)
✅ Optional HTF (Higher Timeframe) bias filter — e.g., only show longs when 15m trend is up
✅ Alerts for bull/bear stretches and SMA extension
⚙️ Core Logic
Green histogram = low above EMA (normalized by ATR) → bullish stretch
Red histogram = EMA above high → bearish stretch
Orange line = high above SMA → extension (useful for exhaustion / fade plays)
Stretch Level line = threshold (default depends on Swing vs Scalper preset)
📊 Presets
Choose in the Mode dropdown:
Swing (MNQ 3m)
ATR Length = 100
EMA Length = 34
SMA Length = 14
Stretched Level = 3.8
👉 Fewer, cleaner signals (approx 3–6/day).
Scalper (MNQ 3m)
ATR Length = 34
EMA Length = 13
SMA Length = 8
Stretched Level = 2.4
👉 More signals (approx 15–25/day).
Custom
Enter your own ATR/EMA/SMA/Level values.
🧭 HTF Bias Filter (optional)
Enable the toggle to align entries with a higher-timeframe trend.
Example: HTF timeframe = 15m, EMA(34)
If close > EMA → bull bias (only green/orange plots show)
If close < EMA → bear bias (only red plots show)
Optional background tint shows bias (green = bull, red = bear).
This reduces false signals and keeps you trading with the bigger move.
🚀 How to Use
Add the indicator → In settings, choose Mode (Swing/Scalper/Custom).
Leave Computation timeframe = 3 and Override symbol = MNQ1! for MNQ micro futures.
Watch for histogram/extension values crossing your Stretched Level.
Bull stretch above threshold = price stretched to upside.
Bear stretch above threshold = price stretched to downside.
SMA extension = price extended above SMA, often exhaustion.
(Optional) Turn on HTF Bias to only take trades in the main trend direction.
🔔 Alerts Included
Bull Stretch > Level (positive histogram crosses above level)
Bear Stretch > Level (negative histogram crosses above level)
SMA Extension > Level (SMA line crosses above level)
All alerts automatically respect the HTF bias filter if enabled.
⚠️ Notes & Best Practices
Stretched Level is not RSI OB/OS — it’s distance normalized by ATR. Combine with market structure (VWAP, supply/demand, session levels).
If using higher-TF calculations (via HTF bias), remember values finalize at the close of that TF bar.
Swing preset is better for holding through moves; Scalper preset is better for fast in/out trading.
Always combine with risk management — normalized stretch can still extend further in strong trends.
✅ Credits
Original Webby RSI by Amphibiantrading.
Extended by for flexible MNQ swing/scalp use with HTF filters.
⚖️ Disclaimer
This script is provided for educational purposes only. It does not constitute financial advice or an offer to buy or sell any financial instrument.
Trading futures, stocks, forex, and cryptocurrencies involves substantial risk and may not be suitable for every investor.
Past performance is not indicative of future results.
Always do your own research and consult with a licensed financial advisor before making any trading decisions.
Use at your own risk.
Ultimate Webby RSI Pro [MNQ 3min]Ultimate Webby RSI Pro – User Guide
I made it to use it on NQ micro futures on a 3-minute time frame.
What it does
Plots the RSI as a colored histogram (green above 50, red below 50, gray near 50).
Adds adaptive ATR-scaled bands around RSI to measure volatility-adjusted momentum.
Optional multi-timeframe RSI filter (choose a higher resolution to confirm signals).
Optional volume filter (signals only when volume is above average).
Detects potential bullish and bearish divergences.
Generates buy/sell alerts when RSI crosses 30/70 with wave/volume confirmation.
How to use it
Apply to a chart (default: MNQ 3m).
Look for Buy signals (green triangles) when RSI crosses upward through 30 with trend/volume confirmation.
Look for Sell signals (red triangles) when RSI crosses downward through 70 with trend/volume confirmation.
Use the colored histogram for quick momentum reading:
Green = bullish pressure
Red = bearish pressure
Gray = neutral/transition
Watch ATR bands: when RSI approaches/exceeds them, momentum may be stretched.
Divergence labels (“Bull Div” / “Bear Div”) highlight possible reversal zones.
Enable TradingView alerts from the “Webby RSI Buy/Sell Signal” conditions.
⚠️ Disclaimer
This script is provided for educational purposes only.
It is not financial advice, and past performance does not guarantee future results.
Always do your own research and use proper risk management before trading or investing.
Machine Learning BBPct [BackQuant]Machine Learning BBPct
What this is (in one line)
A Bollinger Band %B oscillator enhanced with a simplified K-Nearest Neighbors (KNN) pattern matcher. The model compares today’s context (volatility, momentum, volume, and position inside the bands) to similar situations in recent history and blends that historical consensus back into the raw %B to reduce noise and improve context awareness. It is informational and diagnostic—designed to describe market state, not to sell a trading system.
Background: %B in plain terms
Bollinger %B measures where price sits inside its dynamic envelope: 0 at the lower band, 1 at the upper band, ~ 0.5 near the basis (the moving average). Readings toward 1 indicate pressure near the envelope’s upper edge (often strength or stretch), while readings toward 0 indicate pressure near the lower edge (often weakness or stretch). Because bands adapt to volatility, %B is naturally comparable across regimes.
Why add (simplified) KNN?
Classic %B is reactive and can be whippy in fast regimes. The simplified KNN layer builds a “nearest-neighbor memory” of recent market states and asks: “When the market looked like this before, where did %B tend to be next bar?” It then blends that estimate with the current %B. Key ideas:
• Feature vector . Each bar is summarized by up to five normalized features:
– %B itself (normalized)
– Band width (volatility proxy)
– Price momentum (ROC)
– Volume momentum (ROC of volume)
– Price position within the bands
• Distance metric . Euclidean distance ranks the most similar recent bars.
• Prediction . Average the neighbors’ prior %B (lagged to avoid lookahead), inverse-weighted by distance.
• Blend . Linearly combine raw %B and KNN-predicted %B with a configurable weight; optional filtering then adapts to confidence.
This remains “simplified” KNN: no training/validation split, no KD-trees, no scaling beyond windowed min-max, and no probabilistic calibration.
How the script is organized (by input groups)
1) BBPct Settings
• Price Source – Which price to evaluate (%B is computed from this).
• Calculation Period – Lookback for SMA basis and standard deviation.
• Multiplier – Standard deviation width (e.g., 2.0).
• Apply Smoothing / Type / Length – Optional smoothing of the %B stream before ML (EMA, RMA, DEMA, TEMA, LINREG, HMA, etc.). Turning this off gives you the raw %B.
2) Thresholds
• Overbought/Oversold – Default 0.8 / 0.2 (inside ).
• Extreme OB/OS – Stricter zones (e.g., 0.95 / 0.05) to flag stretch conditions.
3) KNN Machine Learning
• Enable KNN – Switch between pure %B and hybrid.
• K (neighbors) – How many historical analogs to blend (default 8).
• Historical Period – Size of the search window for neighbors.
• ML Weight – Blend between raw %B and KNN estimate.
• Number of Features – Use 2–5 features; higher counts add context but raise the risk of overfitting in short windows.
4) Filtering
• Method – None, Adaptive, Kalman-style (first-order),
or Hull smoothing.
• Strength – How aggressively to smooth. “Adaptive” uses model confidence to modulate its alpha: higher confidence → stronger reliance on the ML estimate.
5) Performance Tracking
• Win-rate Period – Simple running score of past signal outcomes based on target/stop/time-out logic (informational, not a robust backtest).
• Early Entry Lookback – Horizon for forecasting a potential threshold cross.
• Profit Target / Stop Loss – Used only by the internal win-rate heuristic.
6) Self-Optimization
• Enable Self-Optimization – Lightweight, rolling comparison of a few canned settings (K = 8/14/21 via simple rules on %B extremes).
• Optimization Window & Stability Threshold – Governs how quickly preferred K changes and how sensitive the overfitting alarm is.
• Adaptive Thresholds – Adjust the OB/OS lines with volatility regime (ATR ratio), widening in calm markets and tightening in turbulent ones (bounded 0.7–0.9 and 0.1–0.3).
7) UI Settings
• Show Table / Zones / ML Prediction / Early Signals – Toggle informational overlays.
• Signal Line Width, Candle Painting, Colors – Visual preferences.
Step-by-step logic
A) Compute %B
Basis = SMA(source, len); dev = stdev(source, len) × multiplier; Upper/Lower = Basis ± dev.
%B = (price − Lower) / (Upper − Lower). Optional smoothing yields standardBB .
B) Build the feature vector
All features are min-max normalized over the KNN window so distances are in comparable units. Features include normalized %B, normalized band width, normalized price ROC, normalized volume ROC, and normalized position within bands. You can limit to the first N features (2–5).
C) Find nearest neighbors
For each bar inside the lookback window, compute the Euclidean distance between current features and that bar’s features. Sort by distance, keep the top K .
D) Predict and blend
Use inverse-distance weights (with a strong cap for near-zero distances) to average neighbors’ prior %B (lagged by one bar). This becomes the KNN estimate. Blend it with raw %B via the ML weight. A variance of neighbor %B around the prediction becomes an uncertainty proxy ; combined with a stability score (how long parameters remain unchanged), it forms mlConfidence ∈ . The Adaptive filter optionally transforms that confidence into a smoothing coefficient.
E) Adaptive thresholds
Volatility regime (ATR(14) divided by its 50-bar SMA) nudges OB/OS thresholds wider or narrower within fixed bounds. The aim: comparable extremeness across regimes.
F) Early entry heuristic
A tiny two-step slope/acceleration probe extrapolates finalBB forward a few bars. If it is on track to cross OB/OS soon (and slope/acceleration agree), it flags an EARLY_BUY/SELL candidate with an internal confidence score. This is explicitly a heuristic—use as an attention cue, not a signal by itself.
G) Informational win-rate
The script keeps a rolling array of trade outcomes derived from signal transitions + rudimentary exits (target/stop/time). The percentage shown is a rough diagnostic , not a validated backtest.
Outputs and visual language
• ML Bollinger %B (finalBB) – The main line after KNN blending and optional filtering.
• Gradient fill – Greenish tones above 0.5, reddish below, with intensity following distance from the midline.
• Adaptive zones – Overbought/oversold and extreme bands; shaded backgrounds appear at extremes.
• ML Prediction (dots) – The KNN estimate plotted as faint circles; becomes bright white when confidence > 0.7.
• Early arrows – Optional small triangles for approaching OB/OS.
• Candle painting – Light green above the midline, light red below (optional).
• Info panel – Current value, signal classification, ML confidence, optimized K, stability, volatility regime, adaptive thresholds, overfitting flag, early-entry status, and total signals processed.
Signal classification (informational)
The indicator does not fire trade commands; it labels state:
• STRONG_BUY / STRONG_SELL – finalBB beyond extreme OS/OB thresholds.
• BUY / SELL – finalBB beyond adaptive OS/OB.
• EARLY_BUY / EARLY_SELL – forecast suggests a near-term cross with decent internal confidence.
• NEUTRAL – between adaptive bands.
Alerts (what you can automate)
• Entering adaptive OB/OS and extreme OB/OS.
• Midline cross (0.5).
• Overfitting detected (frequent parameter flipping).
• Early signals when early confidence > 0.7.
These are purely descriptive triggers around the indicator’s state.
Practical interpretation
• Mean-reversion context – In range markets, adaptive OS/OB with ML smoothing can reduce whipsaws relative to raw %B.
• Trend context – In persistent trends, the KNN blend can keep finalBB nearer the mid/upper region during healthy pullbacks if history supports similar contexts.
• Regime awareness – Watch the volatility regime and adaptive thresholds. If thresholds compress (high vol), “OB/OS” comes sooner; if thresholds widen (calm), it takes more stretch to flag.
• Confidence as a weight – High mlConfidence implies neighbors agree; you may rely more on the ML curve. Low confidence argues for de-emphasizing ML and leaning on raw %B or other tools.
• Stability score – Rising stability indicates consistent parameter selection and fewer flips; dropping stability hints at a shifting backdrop.
Methodological notes
• Normalization uses rolling min-max over the KNN window. This is simple and scale-agnostic but sensitive to outliers; the distance metric will reflect that.
• Distance is unweighted Euclidean. If you raise featureCount, you increase dimensionality; consider keeping K larger and lookback ample to avoid sparse-neighbor artifacts.
• Lag handling intentionally uses neighbors’ previous %B for prediction to avoid lookahead bias.
• Self-optimization is deliberately modest: it only compares a few canned K/threshold choices using simple “did an extreme anticipate movement?” scoring, then enforces a stability regime and an overfitting guard. It is not a grid search or GA.
• Kalman option is a first-order recursive filter (fixed gain), not a full state-space estimator.
• Hull option derives a dynamic length from 1/strength; it is a convenience smoothing alternative.
Limitations and cautions
• Non-stationarity – Nearest neighbors from the recent window may not represent the future under structural breaks (policy shifts, liquidity shocks).
• Curse of dimensionality – Adding features without sufficient lookback can make genuine neighbors rare.
• Overfitting risk – The script includes a crude overfitting detector (frequent parameter flips) and will fall back to defaults when triggered, but this is only a guardrail.
• Win-rate display – The internal score is illustrative; it does not constitute a tradable backtest.
• Latency vs. smoothness – Smoothing and ML blending reduce noise but add lag; tune to your timeframe and objectives.
Tuning guide
• Short-term scalping – Lower len (10–14), slightly lower multiplier (1.8–2.0), small K (5–8), featureCount 3–4, Adaptive filter ON, moderate strength.
• Swing trading – len (20–30), multiplier ~2.0, K (8–14), featureCount 4–5, Adaptive thresholds ON, filter modest.
• Strong trends – Consider higher adaptive_upper/lower bounds (or let volatility regime do it), keep ML weight moderate so raw %B still reflects surges.
• Chop – Higher ML weight and stronger Adaptive filtering; accept lag in exchange for fewer false extremes.
How to use it responsibly
Treat this as a state descriptor and context filter. Pair it with your execution signals (structure breaks, volume footprints, higher-timeframe bias) and risk management. If mlConfidence is low or stability is falling, lean less on the ML line and more on raw %B or external confirmation.
Summary
Machine Learning BBPct augments a familiar oscillator with a transparent, simplified KNN memory of recent conditions. By blending neighbors’ behavior into %B and adapting thresholds to volatility regime—while exposing confidence, stability, and a plain early-entry heuristic—it provides an informational, probability-minded view of stretch and reversion that you can interpret alongside your own process.