TX Ultra Zone Consolidation Detector## TX Ultra Zone Consolidation Detector ##
Overview TX Ultra Zone is an advanced market structure utility designed to automatically detect periods of consolidation, indecision, and sideways movement. By isolating ranging markets, it helps traders avoid "choppy" conditions and prepare for high-probability breakouts.
What It Does
Automatic Detection: Draws visual boxes around price action when volatility compresses.
Breakout Projection: Once price breaks the box, it projects a "Shadow Zone" forward. This shadow serves as a key reference for Support-becomes-Resistance (or vice versa) retests.
Noise Filtering: Helps you stay out of the market when no clear trend exists.
How It Works (Conceptual) The script uses a multi-layer detection engine:
Regime Detection: It analyzes market efficiency and volatility (using adaptive logic) to determine if the market is trending or ranging.
Geometry Confinement: When a range is detected, the script locks the High and Low boundaries.
Expansion & Breakout: The box dynamically expands if price pushes the boundary slightly without a true breakout. A valid breakout closes the box and triggers the Shadow Extension.
How to Use
Add to Chart: Works best on volatility-sensitive assets (Forex, Crypto, Indices).
Wait for the Box: When a Purple Box appears, the market is resting. Do not trade trends inside the box.
Trade the Breakout: Wait for a candle close outside the box.
Use the Shadow: The Grey Shadow Extension indicates where price might return to "retest" the breakout level. This is often a prime entry zone.
Settings & Tuning
Detection Engine: Switch between Adaptive Volatility (Standard) or Momentum Compression (Alternative).
Zone Threshold:
45-50: Sensitive (More boxes, catches micro-ranges).
55-60: Strict (Only catches very clear, tight consolidation).
Shadow Extension: Adjust how far into the future the support/resistance zone is projected.
Disclaimer This tool is for educational and analytical purposes only. Past performance does not guarantee future results. Always use proper risk management.
趨勢分析
LinhFX Breakout Detector Breakout is a price action–based indicator designed to detect valid breakouts from consolidation zones, support and resistance levels, helping traders capture early trend expansions.
The indicator focuses on:
Identifying price compression and range zones
Detecting bullish and bearish breakouts
Filtering false breakouts using momentum and price behavior
Suitable for intraday, scalping, and swing trading, and works across multiple timeframes and markets including Forex, Gold, Crypto, and Indices.
Best used in combination with market structure, momentum or volume analysis.
Sessions DRG FX & Indices This indicator highlights the major global trading sessions on the chart, helping traders identify periods of high liquidity and increased volatility in Forex and Indices markets.
Sri-VWAP CTF)📌 Sri-VWAP CTF (Custom Timeframe VWAP)
🔍 Overview
Sri-VWAP CTF is a custom-timeframe, rolling-window VWAP indicator designed to give traders higher-timeframe volume-weighted price context directly on any lower-timeframe chart.
Unlike standard VWAP implementations that are:
Session-anchored (daily/weekly only), or
Locked to the chart timeframe
this script allows the user to independently select the VWAP calculation timeframe and control how the VWAP behaves between higher-timeframe bars.
This makes the indicator especially useful for multi-timeframe analysis, intraday structure trading, and HTF bias confirmation.
⚙️ How It Works (Conceptual Explanation)
This indicator calculates VWAP using a rolling cumulative window instead of a session reset.
Typical Price Calculation
VWAP is derived using the typical price:
(High + Low + Close) / 3
Volume-Weighted Aggregation
The script multiplies the typical price by volume and applies a rolling cumulative sum over a user-defined number of bars.
Rolling VWAP (Non-Session Based)
VWAP is calculated over a fixed number of candles
It does not reset at session boundaries
This provides a smoother, trend-aware VWAP useful for swing and intraday bias
Custom Timeframe Engine
The VWAP calculation is executed on a user-selected higher timeframe using TradingView’s security mechanism and then projected onto the active chart timeframe.
⏱️ Custom Timeframe Logic
You can calculate VWAP on:
15-minute
30-minute
1-hour
Daily
Any supported timeframe
This allows traders to:
Trade on lower TF entries
While respecting higher TF volume-weighted structure
📈 Plot Behavior Modes
The script offers two distinct plotting behaviors:
1️⃣ Hold Between HTF Bars
VWAP value remains constant until the next HTF candle completes
Best for HTF bias, support/resistance, and trend holding
2️⃣ Show Only on HTF Bars
VWAP appears only when a new HTF candle closes
Ideal for precision reference levels and HTF validation
🧠 Why This Is Different / Useful
✔ Not session-anchored
✔ Rolling VWAP instead of reset-based VWAP
✔ Independent calculation timeframe
✔ Controlled projection behavior
✔ Clean, non-repainting logic
✔ Suitable for scalping, intraday, and swing trading
This design avoids the limitations of traditional VWAP tools and provides greater analytical flexibility without clutter.
🎯 How Traders Can Use It
Trend Bias
Price above HTF VWAP → bullish bias
Price below HTF VWAP → bearish bias
Dynamic Support & Resistance
VWAP acts as a volume-weighted equilibrium level
Entry Filtering
Combine with lower-TF price action, RSI, or EMA strategies
Multi-Timeframe Confirmation
Align LTF entries with HTF VWAP direction
⚠️ Notes
VWAP uses actual traded volume, so results depend on data quality
Best used alongside price structure or momentum tools
Indicator does not repaint
✅ Summary
Sri-VWAP CTF is a custom timeframe, rolling VWAP tool built for traders who want clear HTF volume context on any chart, without session limitations or visual noise.
Candle Born TrendlineThis indicator pinpoints the exact location where a candlestick formation begins. It allows for more accurate tracking of asset trends. It also helps monitor price trend reversals. Its purpose is to provide the user with a tool that allows for visual monitoring of price action. It was created especially for those who trade using scalping techniques.
AuraAura - Premium Adaptive Trend System
Aura is an advanced trend intelligence system engineering for precision market analysis. Unlike static indicators, Aura features a Smart Adaptive Engine that automatically calibrates its sensitivity based on your selected timeframe, ensuring optimal performance across different trading styles.
Key Innovations:
* Smart Adaptive Engine: Automatically detects your timeframe (Scalping, Day Trading, or Swing) and adjusts internal parameters to filter noise and capture true momentum.
* Gold-Optimized Logic: Specifically tuned for high-volatility assets like XAUUSD, utilizing a deviation multiplier of 2.5 to eliminate false signals and fakeouts.
* Dynamic Trend Ribbon: A visually immersive ribbon that expands and contracts with volatility, painting a clear picture of market dominance (Blue for Bullish, Red for Bearish).
* Institutional EMAs: Integrated institutional moving averages (50, 100, 200) provide immediate long-term context without cluttering the chart.
* Precision Signals: Reversal signals are generated only when confirmed by the smoothed baseline, reducing premature entries.
Operational Guide:
1. Select Timeframe: Simply switch between 5m, 1H, or Daily. Aura automatically optimizes itself.
2. Identify Trend: Trade in the direction of the Ribbon color.
3. Execute: Use the "UP" and "DOWN" signals as clear entry triggers.
Rolling Volume Boxes█ OVERVIEW
Rolling Volume Boxes is an indicator that visualizes high-volume zones on the chart in the form of dynamic volume “boxes.” Each box splits volume into bullish and bearish parts, allowing you to assess the dominance of buyers or sellers.
Thanks to the pseudo-volume option, the indicator can also be used on markets where real volume data is unavailable, although results may slightly differ.
The indicator is also suitable for trend analysis and identifying signs of trend weakening – everything depends on box parameters such as their size, moving average length, and multiplier.
█ CONCEPT
The indicator was created as a universal tool offering a non-standard market perspective. It combines volume analysis with trend structure and dynamic support and resistance levels.
Boxes are built using a rolling window of a fixed number of candles defined by the Bars per Box parameter. For each completed window, the indicator calculates the average volume of the entire group of candles and compares it to the volume moving average multiplied by the selected multiplier. A box is created only when this condition is met, meaning that zones appear exclusively in areas where aggregated volume for the whole box is significantly above average. The volume filter is therefore applied to the complete structure, not to individual candles.
Boxes do not overlap. A new box can be formed only after the previous one has fully ended, which keeps the market structure clean and prevents stacking or repainting. Each box always represents a separate and independent volume event.
Inside every box, candle volume is split into bullish and bearish parts. Green candles assign volume to buyers, while red candles assign volume to sellers. This method does not use classic candle delta, but instead builds a clear picture of dominance inside the zone.
Additionally, a Weighted Center is calculated for each box. It represents the true volume equilibrium level within the zone and often acts as a dynamic reaction point for price.
█ FEATURES
Data source
The indicator can use:
- candle volume
- pseudo volume (candle body size)
Calculations
- volume moving average (SMA)
- volume aggregation into boxes
- bullish / bearish volume split
- Weighted Center calculation
Visualization
- volume boxes (bullish / bearish)
- box boundary lines (high / low), extended to the right and removed after breakout
- dashed Weighted Center line, removed after breakout or after a defined number of bars
- labels showing bullish and bearish percentages
- graphical breakout signals
Alerts
- Box Breakout Up
- Box Breakout Down
- Weighted Center Up
- Weighted Center Down
█ HOW TO USE
Adding the indicator
Paste the code into Pine Editor or search for “Rolling Volume Boxes.”
Main settings
- Bars per Box – number of candles per box
- SMA Length – volume moving average length
- Multiplier – zone detection sensitivity
- Use Pseudo Volume – enable pseudo volume
- Show Labels – percentage labels
Key elements are box boundary lines and the Weighted Center line. They are extended to the right, disappear automatically after price breaks them, and act as dynamic market reaction levels.
█ APPLICATION
High-volume zones
Box levels often later become natural support and resistance levels.
Consolidations and ranges
With larger boxes, their boundaries often define the price range. If no breakout occurs for several candles after a box is formed, the probability of sideways movement increases – range trading may be considered.
Breakout trading
Breaking the upper or lower box boundary may signal:
- trend continuation
- the start of a new impulse
Trend analysis
In a strong trend, the internal structure of boxes helps detect decreasing dominance of one side and increasingly balanced proportions, which often acts as an early warning of trend weakening.
Combining with other tools
The indicator works best together with:
- trend indicators
- price levels (pivots, S/R)
- momentum oscillators
Example
- price approaches resistance + momentum weakens
→ in this situation, it is worth considering whether to open a position in line with the dominant trend or, alternatively, wait for a potential trend reversal
█ NOTES
- on markets without volume data, enable pseudo volume
- not a standalone trading indicator
- best results are achieved when used in market context
This indicator may not work properly on certain markets, especially on indices, synthetic instruments and all assets where volume and candle data are aggregated or artificially constructed (e.g. market cap indices, CFD, composite tickers).
In such cases, volume does not reflect real market activity and candles are not based on actual transactions, which makes the boxes lose their analytical value and potentially become misleading.
Price Risk AssessmentPrice Risk Assessment is a composite risk oscillator designed to gauge the probability of price exhaustion and reversal. Unlike standard oscillators that rely on a single data point, this indicator synthesizes five distinct market dimensions to create a holistic "Risk Score" ranging from 0 to 1.
This tool is designed to help traders identify when an asset is statistically overheated (High Risk) or undervalued (Low Risk) relative to its recent history.
🛠️ How It Works
The indicator calculates a raw risk score based on a weighted average of the following components:
Price Position: Measures where the current price sits relative to the High/Low range of the lookback period.
Momentum Risk: Analyzes the Rate of Change (ROC) to determine if velocity is reaching historical extremes.
Volatility Risk: Uses Average True Range (ATR) to assess if volatility is expanding to unsustainable levels.
Trend Strength: Utilizes a custom ADX calculation to factor in trend exhaustion.
Volume Intensity: Compares current volume against historical extremes to identify climax behavior.
🚀 Asset-Specific Algorithms Markets behave differently. This indicator includes a unique "Asset Type" input that dynamically adjusts the weight of the calculations above:
Crypto: Heavily weighted toward Volatility and Momentum.
Stocks: Balanced approach with higher emphasis on Trend Strength.
ETFs: Prioritizes Price Position and Trend stability.
🎯 How to Use
The indicator plots a line that changes color based on "Persistent Risk."
Buying Opportunities (Low Risk):
Purple (Very Low Risk < 0.20): Extreme oversold conditions. historically strong accumulation zones.
Lime (Low Risk < 0.35): Price is in a value area.
Signal: Look for the line to turn Lime or Purple. This suggests downside momentum is fading.
Selling/Hedging Opportunities (High Risk):
Red (Very High Risk > 0.80): Extreme overbought conditions. High probability of a correction.
Orange (High Risk > 0.65): Price is entering a danger zone.
Signal: Look for the line to turn Orange or Red. This suggests the move is overextended.
The "Persistence" Filter To avoid fake-outs during strong trends, this script uses a Persistence Period setting. The risk level must remain in a zone for a specific number of bars (default: 3) before the color changes. This filters out momentary spikes and focuses on sustained market stress.
⚙️ Settings
Asset Type: Choose between Crypto, Stock, or ETF to adjust the internal formula weights.
Lookback Period: The historical window for calculating relative extremes (Default: 100).
Smoothing: Applies an EMA to the final score to reduce noise.
Risk Thresholds: Manually adjust what constitutes "High" or "Low" risk.
Disclaimer: This tool is for information purposes only and does not constitute financial advice. Past performance is not indicative of future results.
QuantRX SuperTrendQuantRX SuperTrend Lite is a clean, non-repainting SuperTrend indicator that visualizes trend state using an ATR-based trailing band. It plots one active line on the chart: the finalized lower band during bullish trend state and the finalized upper band during bearish trend state, using classic SuperTrend band-finalization rules.
Inputs: Price Source, ATR Length, and ATR Multiplier.
Optional display: neutral “Trend Up / Trend Down” flip markers and an optional transparent magenta/purple background tint to reflect the current trend state.
Optional alerts: “Trend Up” and “Trend Down” can be enabled for trend flips only (neutral wording).
This script is intended as a simple trend-state visualization tool. It does not generate buy/sell signals, entries/exits, targets, or performance claims, and it does not include dashboards or automation logic. Use it as a chart overlay to help interpret directional context across any market and timeframe.
Nas Indicator It helps with finding directional bias based off of percentages and grounds me better in my execution.
Adaptive ZigZag Context v1 (Stable)Adaptive ZigZag Context v1 (Stable) is a versatile swing structure indicator that adaptively detects pivot highs and lows while providing higher timeframe context. It helps traders visualize market structure, trend bias, and potential reversal points with stable signals.
Key Features:
Detects swing highs and lows adaptively using a configurable pivot leg length.
Draws ZigZag lines connecting confirmed pivots for clear market structure visualization.
Highlights higher timeframe trend bias using EMA and background color (green for bullish, red for bearish).
Usage:
Analyze market swings and identify potential reversal zones.
Combine with other indicators for trend confirmation.
Useful for multi-timeframe analysis with higher timeframe EMA context.
Important Notes:
This indicator does not provide performance guarantees.
Past behavior does not imply future results.
Traders are encouraged to use this tool alongside other analysis techniques and risk management strategies.
TradeChillOut Stc icon ProfessionalHtf L 80 F 20 S50
Ribbon
1 L 180 F144 S3500
2 L10 F20 S50
3L160 F20 S50
4L96 F20 S50
5L 98 F20 S 50
...
TE_ARCH_PULSE🔷 TE_ARCH_PULSE (ARCH) – Smart Trend, Risk & Options Trading System
🔷TE_ARCH_PULSE is a non-repainting, multi-layer trading indicator designed for Index,
Stocks & Options traders, combining:
🔹 Adaptive ARCH trend logic
🔹 Precise Buy / Sell signals
🔹 Auto & Manual Stop-Loss
🔹 Up to 5 dynamic targets
🔹 Trailing Stop Loss (TSL)
🔹 ADX + BBP market strength analysis
🔹 Live Dynamic Option Strikes (ITM / ATM / OTM)
🔹 Manual Option Chain with Delta & Risk-Reward
🔹 Advanced Pivot Points (Camarilla / Traditional / Fibonacci etc.)
This is NOT a strategy, it is a decision-support trading system.
🔶 1️⃣ Core ARCH Logic (Heart of the System)
ARCH is a volatility-adaptive trend filter.
Buy Signal (B)
Triggered when:
Price is above ARCH filter
Price is rising
ARCH direction is upward
Sell Signal (S)
Triggered when:
Price is below ARCH filter
Price is falling
ARCH direction is downward
🔹 No repeated signals in same direction
🔹 No repainting after candle close
🔶 2️⃣ Visual Signals & Bar Coloring
Green Arrow (B) → Buy setup
Red Arrow (S) → Sell setup
Optional Bar Coloring:
🟢 Bullish
🔴 Bearish
Signal distance from candle can be adjusted to avoid clutter.
🔶 3️⃣ Entry, Stop-Loss & Target System (Professional Grade)
▶ Entry
Entry is calculated with buffer points to avoid fake breakouts
Entry confirmation is tracked candle-by-candle
▶ Stop-Loss (3 Types)
You can use any ONE or combination:
1. Auto SL
Based on recent swing high / low
Optional buffer to avoid SL hunting
2. Multiplier SL
Based on ARCH volatility
Automatically adapts to market speed
3. Manual SL
Fixed Points OR Percentage
🧠 System always considers the most logical SL for Risk-Reward.
🔶 4️⃣ Target System (Up to 5 Targets)
TGT1 – TGT3 (default)
Optional TGT4 & TGT5 (for trending days)
Targets are:
Volatility-based (ARCH)
Automatically marked HIT (✅) with date & time
Lines change color once target is achieved.
🔶 5️⃣ ARCH Trailing Stop Loss (TSL)
Swing-based trailing logic
Works only after signal confirmation
Helps:
Lock profits
Ride strong trends
Avoid emotional exits
🔶 6️⃣ Smart Signal Panel (Bottom-Right Table)
The table shows LIVE STATUS:
✔ Current Signal (BUY / SELL)
✔ Entry Price & Time
✔ Auto SL & Manual SL hit status
✔ Target hit timestamps
✔ Risk / Reward ratio
✔ BBP (Bull vs Bear Power)
✔ ADX Value, Zone & DI condition
This makes the indicator self-explanatory during live trading.
🔶 7️⃣ ADX Trend Strength & Market Zones
ADX Zones:
< 20 → Rangebound
20 – 25 → Weak Trend
25 – 40 → Trending
40 – 60 → Strong Trend
> 60 → Very Strong Trend
Optional background highlighting helps instantly identify:
🔵 Sideways
🟢 Bullish dominance
🔴 Bearish dominance
🔶 8️⃣ BBP – Bull Bear Power Confirmation
Shows:
Bull Power strength
Bear Power strength
Strong / Weak / Neutral zones
Useful for:
Entry confirmation
Partial profit booking
Avoiding late entries
🔶 9️⃣ Dynamic Option Strikes (Index Traders)
Automatically calculates:
ITM / ATM / OTM strikes
Based on Entry Price
Strike step auto-adjusts:
NIFTY → 50
BANKNIFTY → 100
SENSEX → 100
Also clearly shows:
Buy CALL (CE) for BUY signals
Buy PUT (PE) for SELL signals
Disabled automatically on option charts to avoid confusion.
🔶 🔟 Manual Option Chain (Advanced Feature)
✔ Fixed strikes around ATM
✔ Live CE & PE LTP
✔ Previous day comparison
✔ Black-Scholes Delta (Δ)
✔ Expiry-aware volatility
✔ Indian VIX integration
Perfect for:
Directional option buyers
Strike selection
Confidence-based entries
🔶 1️⃣1️⃣ Risk / Reward Calculator
Automatically computes:
Risk (SL distance)
Reward (Target distance)
R-Multiple (R)
Supports:
TGT3 or TGT5 based RR
Auto or Manual SL source detection
🔶 1️⃣2️⃣ Advanced Pivot Points (Bonus Module)
Supported Pivot Types:
Camarilla
Traditional
Fibonacci
Woodie
Classic
DM
Timeframes:
1MIN
3 MIN
5 MIN
10 MIN
15 MIN
30 MIN
45 MIN
1H
2H
4H
DAILY
✔ Individual level toggle
✔ Labels + Price
✔ Historical pivots
✔ Clean auto-cleanup
🔶 Example Workflow (Simple) - For Buy signal
📍 Chart: NIFTY 5-min
Buy arrow appears with B (buy) Signal
Entry above triggers (with buffer)
Auto SL plotted below swing
TGT1 & TGT2 hit
TSL trails price
Table confirms R:R + ADX trend
Option chain suggests ATM CE
Everything visible. No guesswork.
🔶 Example Workflow (Simple) - For Sell signal
📍 Chart: NIFTY 5-min
Sell arrow appears with S (Sell) Signal
Entry below triggers (with buffer)
Auto SL plotted above swing
TGT1 & TGT2 hit
TSL trails price
Table confirms R:R + ADX trend
Option chain suggests ATM PE
Everything visible. No guesswork.
⚠️ Disclaimer
This indicator is for educational & analysis purposes only.
It does NOT guarantee profits.
Always follow risk management and trade responsibly.
JATAYU Institutional Vision Engine# JA-VIEW
JATAYU – Institutional Vision Engine
A single-symbol intraday market intelligence dashboard that displays:
• Daily range exhaustion (DATR)
• Activity insights
• 5m & 15m trend structure with strength
Built to help traders observe whether a stock shows expansion potential or exhaustion through objective data visualization.
JA-VIEW is an analysis and observation tool only.
It does not provide buy/sell calls or financial advice.
Access: Invite Only
Instagram: @kraftoncharts
www.instagram.com
For requesting access to JATAYU – Market Vision Engine. Please DM me on Instagram: @kraftoncharts instagram.com/kraftoncharts?igsh=d with your TradingView username and reason for access. This is a private tool shared selectively.
A Humbled Trader Strategy + ChecklistHumbled Trader Swing Strategy + Checklist
This indicator is a complete swing trading system based on the high-probability strategies popularized by Humbled Trader. It is designed to help traders identify trend breakouts and low-risk momentum pullbacks on the Daily Timeframe.
The script combines trend filtering, automated resistance lines, and specific entry triggers into a single chart overlay, complete with a real-time Strategy Checklist Dashboard to confirm your setups instantly.
🎯 Core Components
Trend Filter (Purple Line): The 200 Simple Moving Average (SMA). This acts as your long-term trend filter. We only look for long trades when the price is above this line.
Momentum Guide (Orange Line): The 8 Exponential Moving Average (EMA). This tracks short-term momentum. In a strong trend, price will "ride" this line. We look to enter when price pulls back to touch this area.
Multi-Month Resistance (Orange Horizontal Line): Automatically plots the highest price over the last X Months (adjustable). This helps you instantly visualize the key level the stock needs to break out from.
Checklist Dashboard: A real-time table that evaluates Trend, Resistance, and Momentum conditions to give you a clear "✅ ENTER", "🚀 GAP UP", or "⏳ WAIT" signal.
🛠 How It Works
This indicator scans for two specific setups:
1. The Daily Gap Up ("GAP" Label) This signal appears when a stock shows strong momentum by gapping up overnight.
Condition: The stock opens at least 3% higher (adjustable) than the previous day's Close AND opens above the previous day's High.
Trend: Must be above the 200 SMA.
Visual: Marked with a green "GAP" label on the chart.
2. The Trend Pullback ("ENTER" Signal) This is a trend-following entry that lets you join an existing move with lower risk.
Condition: The stock is in an uptrend but dips down to touch or test the 8 EMA.
Validation: The candle must show a "dip" (red candle or lower close) to ensure we are buying a pullback, not chasing a top.
Visual: The Dashboard "Action Signal" will turn orange and display "✅ ENTER".
📋 The Checklist Dashboard
Located in the corner of your chart, this table provides a live status report for the current bar:
Trend (> 200 SMA):
🟢 Bullish: Price is in an uptrend. Safe to look for entries.
🔴 Bearish: Price is below the 200 SMA. Stay away.
Above Resistance?:
🟢 Breakout: Price has cleared the multi-month resistance line.
⚪ ---: Price is currently below the key breakout level.
Near 8 EMA?:
🟢 Yes: Price is near the "value zone" (8 EMA) for a potential pullback entry.
Action Signal:
🚀 GAP UP: Strong momentum gap detected.
✅ ENTER: Valid pullback entry detected.
⏳ WAIT: No clear setup found.
⚙️ Settings
Momentum EMA Length: Default is 8. Controls the sensitivity of the pullback line.
Trend SMA Length: Default is 200. The standard for long-term trend filtering.
Gap Up % Threshold: Default is 3.0%. Minimum overnight gap size required to trigger a signal.
Resistance Lookback (Months): Default is 3. The script will look back this many months to find and draw the key resistance line.
Table Position: Move the checklist to any corner of your screen.
⚠️ Disclaimer
This tool is for educational purposes only and does not constitute financial advice. Always manage your risk and use a stop loss.
ATR + BJ Signal V3ATR + BJ Signal (Optimized for GOLD)
This indicator is designed for mean-reversion scalping on GOLD, focusing on volatility expansion and momentum exhaustion.
Key features:
ATR-based candle expansion filter to detect abnormal moves
RSI overbought / oversold confirmation
Optional Bollinger Band deviation filter
Clear BUY / SELL signals for reversal entries
Automatic SL / TP projection lines and price labels (individually toggleable)
Best suited for short-term reversal and scalp trades during high-volatility conditions.
All visual components can be enabled or disabled independently. be enabled or disabled independently.
Above VWAP (Y/N)Background-only overlay script.
It does not plot VWAP, does not draw any lines, and exists only to color the chart background based on above / below VWAP.
Trappp's Advanced Multi-Timeframe Trading ToolkitTrappp's Advanced Multi-Timeframe Trading Toolkit
This comprehensive trading script by Trappp provides a complete market analysis framework with multiple timeframe support and resistance levels. The indicator features:
Key Levels:
· Monthly (light blue dashed) and Weekly (gold dashed) levels for long-term context
· Previous day high/low (yellow) with range display
· Pivot-based support/resistance (pink dashed)
· Premarket levels (blue) for pre-market activity
Intraday Levels:
· 1-minute opening candle (red)
· 5-minute (white), 15-minute (green), and 30-minute (purple) session levels
· All intraday levels extend right throughout the trading day
Technical Features:
· EMA 50/200 cross detection with alert labels
· Candlestick pattern recognition near key levels
· Smart proximity detection using ATR
· Automatic daily/weekly/monthly updates
Trappp's script is designed for traders who need immediate visual reference of critical price levels across multiple timeframes, helping identify potential breakouts, reversals, and pattern-based setups with clear, color-coded visuals for quick decision-making.
Advanced Trading ToolkitTrappp's Advanced Multi-Timeframe Trading Toolkit
This comprehensive trading script by Trappp provides a complete market analysis framework with multiple timeframe support and resistance levels. The indicator features:
Key Levels:
· Monthly (light blue dashed) and Weekly (gold dashed) levels for long-term context
· Previous day high/low (yellow) with range display
· Pivot-based support/resistance (pink dashed)
· Premarket levels (blue) for pre-market activity
Intraday Levels:
· 1-minute opening candle (red)
· 5-minute (white), 15-minute (green), and 30-minute (purple) session levels
· All intraday levels extend right throughout the trading day
Technical Features:
· EMA 50/200 cross detection with alert labels
· Candlestick pattern recognition near key levels
· Smart proximity detection using ATR
· Automatic daily/weekly/monthly updates
Trappp's script is designed for traders who need immediate visual reference of critical price levels across multiple timeframes, helping identify potential breakouts, reversals, and pattern-based setups with clear, color-coded visuals for quick decision-making.
Eccodax Robust k-NN Machine Learning LorentzianHere is the complete, final, corrected, and clean code, already including:
✅ Fixed shadowing of the variable d
✅ No compilation warnings
✅ No temporal leaks
✅ Target = real future return
✅ Robust Lorentzian distance
✅ Correct Matrix structure
✅ Consistent feature engineering
✅ Min-Max normalization
✅ Weighted k-NN inference
✅ Correct price reconstruction
1. What this code is
It is a predictive indicator based on classic Machine Learning (k-Nearest Neighbors), fully implemented in PineScript v6, designed to:
Learn historical market patterns
Compare the current state with similar past states
Estimate the expected future price movement
Reconstruct a projected price consistent with the current level
It is not an oscillator, it is not a traditional technical indicator, and it does not react only to the immediate past.
2. What the Model Learns (Supervised Learning)
2.1 Features (Input Variables)
The model uses three dimensions of information, all normalized by Z-score:
Return
Measures the percentage change in price
Captures the immediate momentum of the market
Momentum (ROC)
Measures acceleration or deceleration of the movement
Differentiates trends from consolidations
Volatility
Measures the degree of market uncertainty
Adjusts the weight of strong movements vs. noise
These three variables form a market state vector.
2.2 Normalization (Z-Score)
Each feature is converted to:
Mean ≈ 0
Standard deviation ≈ 1
This ensures that:
No variable dominates the distance
The statistical comparison is valid
The model is stable in different price regimes
2.3 Target (Predicted Variable)
The model does not predict absolute price. It learns:
Observed future return after forecastBars
That is:
Learns movement, not level
Eliminates historical bias
Avoids predictions inconsistent with the current price
3. How the model makes the prediction
3.1 Search for similar patterns (k-NN)
For each current candle, the model:
Analyzes the last lookback candles
Calculates the Euclidean distance between the current state and each past state
Selects the k most similar states
Observes what happened after them
3.2 Inference
The predicted return is calculated as:
Weighted average of the future returns of the neighbors
Weights inversely proportional to the distance
More similar states → greater influence.
4. Price Reconstruction (Key Information)
From the predicted return, the model reconstructs:
Predicted Price = Current Close × (1 + Predicted Return)
Predicted Price = Current Close × (1 + Predicted Return)
This ensures that:
The forecast respects the current market level
The output is visually interpretable
There is no regression to past regimes
5. Relevant Information the Indicator Delivers
5.1 Predicted Price (Green Line)
What it is: Estimated price after forecastBars.
How to use:
Above the current price → bullish bias
Below → bearish bias
Large distance → expectation of strong movement
5.2 Predicted Return (Implicit)
Even though not plotted directly, it is the most important information in the model.
Positive → expectation of appreciation
Negative → expectation of decline
Negative → expectation of decline
Near zero → sideways market
5.3 Directional Classification (optional)
The model also acts as a binary classifier:
High if expected return > 0
Low if expected return < 0
This is used as:
Noise filter
Trend confirmation
False signal reduction
5.4 Implicit statistical context
The indicator carries information that is not visual, but is fundamental:
Market regime (trending vs. sideways)
Statistical similarity with the past
Relative confidence (via distance from neighbors)
6. What this indicator does NOT do
It is important to align expectations:
❌ Does not predict exogenous events
❌ Does not anticipate gaps
❌ Does not work well on illiquid assets
❌ Does not extrapolate long trends
k-NN replicates patterns, does not create scenarios Unprecedented.
7. Where this model works best
Markets with repetitive structure
Medium timeframes (5m – 1D)
Liquid assets
Environments with alternating regimes
8. How to use it in practice (professional recommendation)
Ideal use:
k-NN direction → bias
Technical indicator → timing
Risk management → execution
Never use it in isolation for entry.
9. Executive summary
This code delivers:
A functional supervised ML model in Pine
Prediction consistent with the current price
Statistical market direction
Reduction of historical bias
Solid foundation for quantitative strategies
Flexible S/R Channels🟩 Flexible S/R Channels is a visualization tool that draws curved support and resistance boundaries through user-defined anchor points. Unlike traditional trendlines and channels that force linear interpretation onto price action, this indicator captures the curved structures that markets frequently form—rounded tops and bottoms, parabolic advances and declines, arcing rallies and pullbacks. Three anchor points per curve define the shape; the indicator fits a smooth mathematical curve through these points and projects it forward. The approach is simple: draw what you see. Curved market structure that resists precise definition with traditional tools can now be rendered with mathematical accuracy.
The indicator bridges the gap between static drawing tools and programmable indicators. TradingView's arc tool draws curves but produces only visual pixels with no analytical value. Flexible S/R Channels creates live data series that integrate with other analysis tools. Four curve-fitting methods—Quadratic, Quadratic-Linear, Weighted Linear, and Natural Cubic Spline—accommodate different market structures. The curved levels naturally lend themselves to breakout and reversion strategies—applications left to the trader's discretion. The open-source code invites experimentation and customization.
💡 THEORY AND CONCEPT 💡
Traders have long relied on horizontal levels and diagonal trendlines to define support and resistance. Linear tools assume constant slope—a property rarely exhibited by actual market movement. When momentum accelerates or decelerates, price trajectories curve rather than hold to fixed angles. The resulting structures—parabolic advances during expansion phases, arcing pullbacks during consolidation, rounded formations at reversal points—represent changes in the rate of change itself. Traditional drawing tools cannot accommodate this variable geometry without sacrificing mathematical precision..
Flexible S/R Channels extends familiar support and resistance concepts into curved space. The approach is simple: draw what you see. When the eye recognizes a curved boundary in price action, this indicator provides the means to define it precisely. Three anchor points per curve—an initial point, an intermediate point, and a recent point—are all that is required. The indicator fits a smooth mathematical curve through these points and extends it forward as a projection.
This indicator represents a blend of human pattern recognition and algorithmic precision. Fully automated indicators make decisions without user input—efficient but detached from trader discretion. Manual drawing tools rely entirely on freehand skill—expressive but imprecise. Flexible S/R Channels occupies the middle ground. The trader identifies the curved structure; the algorithm renders it mathematically. The result is human insight expressed with computational accuracy—for traders who recognize curved structure in price action but lack precise tools to define it.
This projection is not a prediction. It is a visual hypothesis—a structured way of asking "if this trajectory continues, where would price be?" The underlying assumption is simple: like Newton's first law of motion, a trajectory in motion tends to continue unless acted upon by an external force. Future price action validates or invalidates the projection, just as it does with any trendline or channel.
TradingView offers an arc drawing tool for freehand curved lines, but these are purely visual—static pixels on a screen with no programmable value. Flexible S/R Channels bridges this gap. The fitted curves exist as data series that can generate alerts, trigger signals, and interact with other analysis tools. The visual drawing becomes operational structure.
🔁 CURVE METHODS 🔁
The indicator offers four curve-calculation methods, each producing different shapes suited to different market structures:
Quadratic — Fits a parabolic arc through the three anchor points. Best for smooth, continuous curves such as rounded tops and bottoms. It captures the natural "swing" of the market, assuming the momentum will maintain its current rate of acceleration or deceleration.
Quadratic-Linear — Uses a parabolic curve through the anchor points, then transitions to a straight line after the final anchor. Useful when curved structure gives way to linear trend continuation. This is the "bridge" between a turning market and a steady, directed move, preventing the projection from curving back on itself when the price begins to run.
Weighted Linear — Connects anchor points with straight line segments rather than a smooth curve. Suited for angular market structures with distinct inflection points. It treats the market as a series of rigid shifts, providing a clear "corridor" when the price is bouncing between sharp, diagonal levels.
Natural Cubic Spline — Produces the smoothest curve by minimizing abrupt directional changes. Ideal for organic, flowing market movements. It acts as a flexible spine that adapts to complex transitions without the rigid constraints of a fixed geometric shape.
Quadratic Fitting : A smooth, parabolic arc defines a curved resistance boundary. By fitting a mathematical path through three anchor points, the curve captures rounded structures and arcing price action that traditional linear trendlines fail to represent.
Weighted Linear Fitting : This method produces an angular, segmented path by connecting anchor points with distinct linear slopes. Unlike the continuous smoothness of a quadratic arc, the weighted linear approach creates a more jointed geometry, allowing for a precise match to market structures that exhibit sharp, localized changes in trajectory.
Natural Cubic Spline Fitting : This method creates a highly fluid, elastic curve that can accommodate complex price oscillations. In this instance, the curves define a narrowing range as support and resistance converge, highlighting the volatility compression that often precedes a significant breakout or breakdown from established structures.
🖱️ HOW IT WORKS 🖱️
1️⃣ Initial Setup
Unlike traditional indicators that calculate values automatically from price data, Flexible S/R Channels requires user-defined anchor points. This is intentional. The trader's eye is the pattern recognition engine—no algorithm can see the curved structure that experience and intuition reveal. The indicator waits for this input, then applies mathematical precision to render what the trader has identified.
The Recognition of Natural Structure : Effective analysis begins when a curved rhythm becomes visible within price action that traditional trendlines cannot satisfy. Identifying the specific swing highs and swing lows that define these boundaries is the first step in organizing a chart. By isolating three key pivots for resistance and three for support, the underlying framework of the market's trajectory is established, providing the necessary coordinates to accurately map the path.
Interactive Setup Workflow : Upon loading, the indicator prompts for the sequential selection of six points—three swing highs and three swing lows—to serve as the raw data for the calculation. While the chart remains blank during this initial phase, the curves generate instantly once the final anchor is confirmed. These points are not permanent; they appear as interactive grips that can be dragged in real time to refine the boundaries as the market structure evolves.
The indicator prompts for six sequential selections—three for resistance, three for support. The first three selections define the resistance boundary; the final three define support. This sequential grouping is distinct from zigzag-style selection patterns. Within each group, clicking order is flexible—the algorithm automatically sorts points chronologically, allowing traders to select visually prominent pivots in whatever sequence feels natural.
Structural Anchor Identification : Identifying three key swing highs and three key swing lows provides the foundation for the dual-curve geometry. These specific structural peaks and troughs serve as the coordinates for the mathematical models, ensuring that the resulting boundaries accurately reflect the underlying skeleton of the market action.
2️⃣ Interactive Adjustment
After the initial setup, all six anchor points are fully adjustable:
Points are automatically sorted chronologically regardless of selection order
Grip handles appear at each anchor location
Any point can be repositioned by clicking and dragging its grip handle
The curves recalculate instantly as points are adjusted
The algorithm produces a mathematically perfect curve based on the anchor points provided. If the result does not match the trader's vision, adjustments are immediate. This iterative refinement—see, adjust, refine—continues until the rendered curve represents what the trader sees in the price action. The user remains in control; the algorithm remains in service.
Interactive Channel Boundaries : Six user-defined anchor points—three for resistance and three for support —establish a non-linear range that moves beyond the constraints of a flat, horizontal channel. This configuration captures the arcing trajectory of the market while showing price action respecting the curved boundaries in a classic reversion pattern. By manually positioning these anchors, a dynamic dimension is added to the chart that maintains structural integrity even as the price follows a rounded path.
🛠️ SETTINGS 🛠️
Customizable Visual Feedback : Beyond the core geometry, the visualization offers various user-defined settings to tailor the chart's information density. From identifying specific price targets to toggling structural labels, these options allow the trader to adjust the level of detail to suit their personal analysis style while maintaining a clear view of the non-linear boundaries.
Configuration Options
Curve Method — Select the curve-fitting algorithm: Quadratic, Quadratic-Linear, Weighted Linear, or Natural Cubic Spline.
Projection Length — Number of bars to project the curves beyond current price action. Projections appear as dashed lines.
Visual Settings
Grip Size — Size of the draggable handles displayed at each anchor point. Set to zero to hide grips entirely.
Line Width — Thickness of the support and resistance curves.
Support Color / Resistance Color — Color settings for each curve.
Show Info Table — Toggle display of the info table showing the current curve method in the chart corner.
Advanced: Time/Price Coordinates
The settings panel includes precise time and price values for each of the six anchor points, grouped under Resistance Time/Price and Support Time/Price. These values are populated automatically when points are selected on the chart.
Adjusting anchor points by dragging the grip handles directly on the chart is faster and more intuitive. The time/price fields are available for situations requiring exact coordinate entry—such as aligning an anchor to a specific candle timestamp or a precise price level. These fields can be safely ignored unless fine-tuning is necessary.
🖼️ CHART EXAMPLES 🖼️
The Flexible S/R Channels indicator adapts to diverse market structures across multiple timeframes and instruments. Curved boundaries can define subtle momentum shifts in near-linear trends, dramatic reversals in rounding formations, or volatility compression as channels converge toward breakout points. The four curve-fitting methods accommodate different geometries—smooth parabolic arcs for continuous momentum changes, segmented linear paths for angular structures, and elastic splines for complex oscillations. Each anchor point adjustment instantly recalculates the curves, allowing iterative refinement until the rendered boundaries align with the trader's interpretation of market structure. Forward projections extend these mathematical relationships into future territory, providing visual context for hypothetical support and resistance levels if current trajectories persist.
Subtle Curve Alignment : Even in structures that appear linear, subtle curvature allows the channel boundaries to breathe with the market’s internal momentum. By utilizing three anchor points rather than two, the channel adapts to the slight acceleration of a trend, providing a more precise fit than a rigid, straight corridor.
Decelerating Momentum and Convergence : This classic rounding structure illustrates a transition where the initial wide oscillations between highs and lows begin to contract. As the boundaries converge, the curve captures the diminishing volatility and the shift in market energy, providing a clear visual representation of a trend losing its expansive momentum as it approaches a potential turning point.
Organic Trend Modeling : In an accelerating uptrend, the Natural Cubic Spline provides a highly adaptable boundary that mirrors the organic flow of momentum. This non-traditional approach allows the channel to follow complex price pulses that a standard linear trendline would likely cut through, maintaining a precise fit even as the angle of the trend shifts over time.
Non-Linear Projections : Unlike standard trendlines that converge at a fixed rate, curved projections adapt to the historical momentum of the move. This allows the indicator to map a dynamic squeeze, capturing the subtle nuances of how price action tightens toward an apex. It provides a more sophisticated view of future convergence points that traditional linear channels often fail to anticipate.
The "Draw What You See" Philosophy : Market structures are rarely perfect, and this example highlights the indicator’s ability to map unconventional rhythms. Rather than forcing price into a predefined category, the tool remains flexible enough to define any structural path the trader identifies. If you can see a trend's trajectory, the indicator can provide the mathematical framework to support it.
Comparative Projection Modeling : Using identical anchor points as above, this example demonstrates how selecting a different calculation method can alter the projected path. While the historical fit remains precise, the variation in the forward-looking trajectory allows traders to explore multiple mathematical interpretations of the same market structure, choosing the model that best aligns with the current volatility and trend behavior.
Extended Timeframe Channel Definition : This multi-year perspective demonstrates the indicator's ability to define curved channel boundaries across extended timeframes spanning hundreds of bars and multiple market cycles. The resistance curve captures the rounded distribution of swing highs while the support curve follows the accelerating base formation, creating a non-linear channel that frames long-term structural trends more precisely than traditional parallel channels or static trendlines.
Rounding Bottom Reversal and Channel Convergence : This example captures a classic rounding bottom formation—a reversal pattern that linear tools cannot adequately define. The Quadratic method produces a smooth parabolic arc through the resistance anchors, tracing the deceleration of the downtrend, the capitulation low, and the subsequent re-acceleration upward as a single continuous curve. The support boundary mirrors this momentum shift from below, creating a curved channel that narrows toward current price. This convergence represents structural compression—the boundaries tightening as volatility contracts and directional resolution approaches. Price action oscillates within these non-linear boundaries, demonstrating that channel behavior persists even when the geometry is curved rather than parallel. The projection extends both curves forward, mapping the hypothetical trajectory if the current momentum structure continues, providing visual context for potential breakout or breakdown levels as the channel reaches its apex.
Built-in Precision vs. Algorithmic Power : While TradingView offers basic curve drawing tools (shown here as dashed lines), the Flexible S/R Channels indicator elevates this concept into a functional analytical framework. By converting manual observations into mathematical models, it moves beyond mere drawing to provide a data-driven structure that can be utilized for advanced technical analysis and future Pine Script trading logic.
⚙️ TECHNICAL DETAILS ⚙️
Curve Fitting vs. Overfitting: The term curve fitting often carries negative connotations in quantitative analysis due to its association with overfitting—the practice of adjusting a model until it perfectly matches historical data, producing an illusion of accuracy that fails when applied to new data. The application here is fundamentally different. Flexible S/R Channels does not optimize parameters to maximize historical fit; it constructs a mathematical curve through user-selected anchor points, then projects that curve into unknown territory. The curve is not fitted to price data—it is fitted to structural pivots identified by the trader. The projection represents a hypothesis about trajectory continuation, not a prediction derived from statistical optimization. Future price action validates or invalidates this hypothesis in real time, exactly as it does with any trendline or channel. The anchor points remain fixed unless manually adjusted, ensuring the curve does not adapt to new data retroactively.
Non-Repainting Behavior: The indicator does not repaint historical bars. The mathematical coefficients that define each curve are calculated once—when the final anchor point is set—and stored as fixed values. These coefficients remain constant unless an anchor point is manually repositioned. The backfit polyline is drawn once using these coefficients, spanning the known range from the first to last anchor point. The plot() function applies the same coefficients to each subsequent bar, updating in real-time as new bars form but never altering previously plotted values. The projection polyline extends forward from the current bar using the same fixed coefficients, projecting a user-defined number of future bars (maximum 500). This projection redraws on each tick to maintain its position relative to the moving current bar, but the mathematical trajectory remains constant—only the starting point advances. The current bar's curve value will update tick-by-tick as price develops, which is standard real-time behavior, not repainting. Once a bar closes, all curve values on that bar are permanent. The hybrid architecture (backfit polyline for known history, plot() for unlimited real-time range, projection polyline for controlled forward extension) prevents overflow errors while maintaining non-repainting integrity across all components.
🗒️ NOTES 🗒️
The indicator renders curves based on any anchor points provided without validation. Unusual anchor placement produces mathematically accurate but potentially non-useful results. Adjustment is iterative—if the curve doesn't match expectations, reposition the anchors.
Because anchor points are stored as specific time and price coordinates, a new instance of the indicator should be added when analyzing a different chart or timeframe.
Grip handles can be hidden by setting Grip Size to zero in the settings. This is useful for clean chart screenshots or presentations where interactive elements are not needed.
Projection length can be set to zero if forward-looking curves are not desired. The indicator will still render the backfit curves through the anchor points and continue plotting in real-time without the dotted projection extensions.
Anchor points remain fixed at their selected time-price coordinates as new bars form. The curves extend forward automatically from these historical anchors, allowing observation of how projected trajectories align with developing price action.
⚠️ DISCLAIMER ⚠️
The Flexible S/R Channels indicator is a visual analysis tool designed to illustrate geometric market inertia and serve as a framework for understanding dynamic support and resistance. While the indicator generates structural channels and projected paths, no guarantee is made regarding the accuracy or profitability of these projections. Like all technical indicators, the curves and boundaries generated by this tool may appear to align with favorable trading opportunities in hindsight. However, these visualizations are not intended as standalone recommendations for trading decisions. This indicator is intended for educational and analytical purposes, complementing other tools and methods of market analysis.
🧠 BEYOND THE CODE 🧠
Flexible S/R Channels is part of a broader collection of tools designed to provide structured market analysis. This includes the Grid Bot Simulator , the Grid Bot Auto , the Grid Bot Parabolic , and the Gridbot Ping Pong . While each tool serves a distinct purpose, they all utilize dynamic anchor mechanics and non-linear boundaries to adapt to evolving market conditions.
This indicator shares the same educational philosophy as the Fibonacci Time-Price Zones and the Fibonacci Geometry Series - providing frameworks for understanding market concepts through visualization and experimentation rather than black-box signals.
The Flexible S/R Channels indicator, like other xxattaxx indicators , is designed to encourage both education and community engagement. Feedback and insights are invaluable to refining and enhancing this tool. We look forward to the creative applications, observations, and discussions this indicator inspires within the trading community.
Eccodax Advanced kNN Lorentziano Matrix1. What this code is
It is a predictive indicator based on classic Machine Learning (k-Nearest Neighbors), fully implemented in PineScript v6, designed to:
Learn historical market patterns
Compare the current state with similar past states
Estimate the expected future price movement
Reconstruct a projected price consistent with the current level
It is not an oscillator, it is not a traditional technical indicator, and it does not react only to the immediate past.
2. What the Model Learns (Supervised Learning)
2.1 Features (Input Variables)
The model uses three dimensions of information, all normalized by Z-score:
Return
Measures the percentage change in price
Captures the immediate momentum of the market
Momentum (ROC)
Measures acceleration or deceleration of the movement
Differentiates trends from consolidations
Volatility
Measures the degree of market uncertainty
Adjusts the weight of strong movements vs. noise
These three variables form a market state vector.
2.2 Normalization (Z-Score)
Each feature is converted to:
Mean ≈ 0
Standard deviation ≈ 1
This ensures that:
No variable dominates the distance
The statistical comparison is valid
The model is stable in different price regimes
2.3 Target (Predicted Variable)
The model does not predict absolute price. It learns:
Observed future return after forecastBars
That is:
Learns movement, not level
Eliminates historical bias
Avoids predictions inconsistent with the current price
3. How the model makes the prediction
3.1 Search for similar patterns (k-NN)
For each current candle, the model:
Analyzes the last lookback candles
Calculates the Euclidean distance between the current state and each past state
Selects the k most similar states
Observes what happened after them
3.2 Inference
The predicted return is calculated as:
Weighted average of the future returns of the neighbors
Weights inversely proportional to the distance
More similar states → greater influence.
4. Price Reconstruction (Key Information)
From the predicted return, the model reconstructs:
Predicted Price = Current Close × (1 + Predicted Return)
Predicted Price = Current Close × (1 + Predicted Return)
This ensures that:
The forecast respects the current market level
The output is visually interpretable
There is no regression to past regimes
5. Relevant Information the Indicator Delivers
5.1 Predicted Price (Green Line)
What it is: Estimated price after forecastBars.
How to use:
Above the current price → bullish bias
Below → bearish bias
Large distance → expectation of strong movement
5.2 Predicted Return (Implicit)
Even though not plotted directly, it is the most important information in the model.
Positive → expectation of appreciation
Negative → expectation of decline
Negative → expectation of decline
Near zero → sideways market
5.3 Directional Classification (optional)
The model also acts as a binary classifier:
High if expected return > 0
Low if expected return < 0
This is used as:
Noise filter
Trend confirmation
False signal reduction
5.4 Implicit statistical context
The indicator carries information that is not visual, but is fundamental:
Market regime (trending vs. sideways)
Statistical similarity with the past
Relative confidence (via distance from neighbors)
6. What this indicator does NOT do
It is important to align expectations:
❌ Does not predict exogenous events
❌ Does not anticipate gaps
❌ Does not work well on illiquid assets
❌ Does not extrapolate long trends
k-NN replicates patterns, does not create scenarios Unprecedented.
7. Where this model works best
Markets with repetitive structure
Medium timeframes (5m – 1D)
Liquid assets
Environments with alternating regimes
8. How to use it in practice (professional recommendation)
Ideal use:
k-NN direction → bias
Technical indicator → timing
Risk management → execution
Never use it in isolation for entry.
9. Executive summary
This code delivers:
A functional supervised ML model in Pine
Prediction consistent with the current price
Statistical market direction
Reduction of historical bias
Solid foundation for quantitative strategies
Relevant information provided by this code
1. Forecasted price (line)
Statistical projection consistent with the current level
Based on similar historical patterns
2. Implicit direction
Return > 0 → bullish bias
Return < 0 → bearish bias
3. Structural robustness
Lower sensitivity to outliers
Lower scale bias
Better adaptation to different regimes
This refactored version introduces significant improvements based on modern quantitative Machine Learning practices (similar to those found in jdehorty's "Lorentzian Classification" indicator):
Lorentzian Distance: Replaces the Euclidean distance (which is affected by noise and outliers) with Lorentzian Distance, which is much more robust for financial markets.
Matrix Structure: Uses the matrix object in Pine V6 to manage training data more efficiently and cleanly than loose arrays.
Feature Engineering (WaveTrend & RSI): Replaces simple Momentum with normalized indicators (RSI, WaveTrend, CCI, ADX), better capturing market dynamics.
Min-Max Normalization: Features are normalized on a 0-100 scale so that indicators with different magnitudes do not distort the distance calculation.
Inverse Distance Weighting: Instead of a simple average, the nearest neighbors (most similar) have greater weight in the prediction.






















