DLRC ModifiedThis is a modification of Iravan's Dynamic Linear Regression Channels indicator, modified by Claude 4.6 to limit the lookback period, resulting in the indicator not appearing on some chartsIndicador Pine Script®por ronalmstead8
Hybrid Regression Screener This script is a dedicated companion filter and multi-symbol screener designed to expand the capabilities of our core "Hybrid Regression & Dual PVT Flow" indicator system. Instead of manually flipping through charts, this helper dashboard allows you to filter and monitor the real-time regression trends of 10 customizable assets simultaneously from a single screen. 📈 Key Filter Features: 10-Symbol Simultaneous Scanning: Runs background Linear Regression analysis for 10 user-defined symbols (Crypto, Stocks, or Forex) in real-time. Trend Phase & Timing Indicator: Displays whether an asset is in a "Bullish" or "Bearish" cycle, while accurately calculating the exact number of bars passed since the bullish reversal. Fresh Reversal Filtering: By checking the "Bars Ago" metric, you can easily filter out overextended moves and pinpoint assets that have just triggered a fresh trend shift aligned with your main trading strategy. Indicador Pine Script®por sselmantr1110
Hybrid Regression & Dual PVT Flow🇺🇸 ENGLISH DESCRIPTION TEXT Overview Hybrid Regression & Dual PVT Flow is an institutional-grade hybrid analysis system designed to uncover the footprints of market whales. It bridges the gap between pure price geometry and volume-weighted momentum, preventing retail traders from falling into "bull/bear traps" by exposing hidden institutional accumulation and distribution phases. Key Technical Pillars: Linear Regression Core: Computes a noise-filtered baseline representing the true mathematical equilibrium of price. The curve turns green during a bullish slope and red during a bearish slope. Dynamic Fibonacci Volatility Envelope: Employs an ATR-driven deviation mechanism instead of traditional standard deviations. It projects key institutional overbought (Resistance) and oversold (Support) thresholds based on the 2.618 Fibonacci ratio. Volume Anomaly Engine: Scans for extreme institutional anomalies where candle volume exceeds 1.5x of its 20-period moving average. These high-activity institutional bars are highlighted in Yellow on your chart. Dual-Layer Multi-Timeframe PVT Dashboard: Micro PVT Status: Tracks real-time smart money participation directly on your active trading timeframe (e.g., 5m, 15m, 1h). Macro PVT Status: Permanently anchors a Daily (1D) Price Volume Trend core against its 10-period EMA, providing an unshakeable perspective of the "Big Picture" regardless of your active asset chart. How to Read the Intelligence Dashboard: BULLISH / BEARISH CONVERGENCE: Absolute alignment between the macro trend line and multi-timeframe capital flows. Indicates high-probability trend continuation. HIDDEN BEARISH DIVERGENCE (Distribution Trap): Price regression slope is upward, but both macro and micro PVT metrics are flashing negative. Highly indicative of institutional selling into retail FOMO. STRONG ACCUMULATION DIVERGENCE (Whale Accumulation): Price regression slope is sliding downward, but dual-layer PVT inflows are accelerating heavily. Signals structural retail liquidation being absorbed by institutional market makers right before a major reversal. 🇹🇷 TÜRKÇE AÇIKLAMA METNİ Özet Giriş Hybrid Regression & Dual PVT Flow, piyasada sıklıkla karşılaşılan "fiyat yükselirken kurumsal oyuncuların arka kapıdan mal çıkması" (dağıtım) veya "fiyat düşerken balinaların dipten gizlice mal toplaması" (akümülasyon) durumlarını yakalamak için tasarlanmış hibrit bir takip sistemidir. Matematiksel gücünü Doğrusal Regresyon Eğrisi ve Çift Katmanlı Price Volume Trend (PVT) momentum motorunun sentezinden alır. Ana Özellikler: Doğrusal Regresyon Hattı (Linear Regression Trend): Piyasanın ana dengesini ve makro yönünü gürültüden arındırılmış bir eğri olarak sunar. Eğim yukarıysa yeşil (Boğa), aşağıysa kırmızı (Ayı) olarak grafiğe işlenir. Dinamik Fibonacci Volatilite Bantları: Klasik Bollinger bantları yerine, ATR (Average True Range) tabanlı dinamik volatilite sınırları kullanır. Üst kırılımlar kurumsal aşırı alım/direnç, alt bantlar ise kurumsal güvenli alım/destek bölgelerini işaret eder. Hacim Anomalisi Mum Boyama: Son 20 mumun ortalama hacmini %150 aşan ani balina aktivitelerinde, mumlar otomatik olarak Sarı renge boyanarak dikkat çeker. Çift Katmanlı PVT ve Trend Matris Paneli: * Mikro PVT: Bulunduğunuz anlık aktif grafik zaman dilimindeki (5dk, 15dk, 1sa vb.) para akışı yönünü ölçer. Makro PVT: Grafiğiniz ne olursa olsun, arka planda Günlük (1D) kurumsal para akışının 10 günlük ortalamasını denetler. Panel Strateji Notları Nasıl Okunur? TAM UYUM (BOĞA / AYI): Trend yönü ile tüm vadelerdeki para akışları aynı yöndedir. Güvenli katılım bölgesidir. GİZLİ AYI UYUMSUZLUĞU (Dağıtım Tuzağı): Regresyon eğrisi yukarı bakarken, hem günlük hem anlık para akışları negatif yönlüdür. Balinaların küçük yatırımcıya mal devrettiği tepe tuzaklarını gösterir. GİZLİ BOĞA UYUMSUZLUĞU (Mal Toplama): Grafik aşağı akarken, hem günlük hem anlık PVT'nin güçlü yönlü yukarı gitmesidir. Balinaların dipten toplama yaptığını ve sert bir yükselişin yakın olduğunu gösterir.Indicador Pine Script®por sselmantr6
Sloped LinReg Volume Profile [MarkitTick]💡 This indicator introduces a highly dynamic approach to volume and price analysis by merging standard volume principles with vector-based linear regression. Rather than plotting volume distributions on a static horizontal plane, this tool maps volume nodes parallel to the prevailing mathematical trend. By constructing a localized volume profile that follows the trajectory of price action, it captures momentum-adjusted value areas, providing an advanced lens for interpreting market geometry, support/resistance, and volume anomalies. It is strictly engineered for standard candlestick charts, specifically excluding non-standard formats to ensure pristine volume and price data integrity. ● ✨ Originality and Utility Standard volume profiles aggregate historical volume at fixed price levels, which often creates fragmented or obsolete value nodes when a market is actively trending. This indicator resolves that structural limitation by angling the volume bins to match the slope of a linear regression channel. It identifies where volume is concentrated relative to the trend's axis, not just the absolute price. It reveals volume-weighted momentum, highlighting whether buying or selling pressure is accelerating in the direction of the regression slope. The tool includes an integrated, dark-mode optimized analytics dashboard that processes quantitative metrics natively on the chart without requiring secondary oscillators. ● 🔬 Methodology and Concepts The foundational logic relies on computing a rolling linear regression to establish a baseline trajectory over a specified period. The methodology relies on Pine Script's time-series event loop, evaluating arrays of data dynamically as new bars form. Vector-Based Binning: Instead of horizontal rows, the profile utilizes a dynamic upper and lower deviation band. The mathematical distance between these bands is partitioned into a user-defined number of rows. Volume Distribution: As the script loops through the historical lookback window, it evaluates the volume of each bar. The volume is divided proportionally across the sloped bins that intersect the bar's high-low range. Directional Volume (Delta): Each bin further categorizes volume into "Buy" or "Sell" categories based on whether the bar's closing price was greater than or equal to its opening price. Value Area Calculation: The Point of Control (POC) identifies the sloped bin with the highest total volume. The Value Area High (VAH) and Value Area Low (VAL) expand outward from the POC until they encapsulate a specific percentage of the total allocated volume, dynamically updating as price action develops. ● 🎨 Visual Guide Every visual element is rendered utilizing Pine Script's advanced drawing arrays and is fully user-configurable to support dark-mode analytical environments. • The Sloped Profile Volume Bars: Rendered as polygons extending inward from the right side of the channel. The length of each polygon represents the relative volume allocated to that specific standard deviation bin. Color Coding: Bullish volume defaults to a translucent teal, while bearish volume displays as a translucent red. Bins experiencing extraordinary volume influxes override with a bright, high-visibility color to highlight anomalous market participation. • Channel and Level Lines Regression Bounds: Solid or semi-transparent lines mapping the start and end of the regression channel, defining the upper and lower standard deviation extremes. POC Line: A thick, solid yellow line plotting the Point of Control across the length of the channel. Value Area Lines: Dashed blue lines tracking the VAH and VAL. The area between these lines is shaded with a deep blue fill to instantly highlight the trend's core acceptance zone. Delta POC: A dashed fuchsia line identifying the bin with the most extreme difference between buying and selling volume. • Analytics Dashboard Located in the top right, this table provides real-time quantitative readouts formatted to precise tick values. LinReg Slope: Indicates the mathematical direction of the trend (Bullish/Bearish). Price Regime: Identifies if the current close is inside the channel or breaking the upper/lower bounds. Volume POC & Delta POC: Displays the exact price equivalents of the sloped control lines at the current bar index. Buy Vol Bias: A visual progress bar detailing the ratio of bullish to bearish volume within the regression window. Vol Compression: Evaluates the density of the value area. A highly concentrated value area yields a higher compression score. ● 📖 How to Use The indicator serves as a complete environmental map for trending markets. Trend Qualification: Utilize the slope of the regression channel to establish the primary directional bias. Trades should ideally align with the slope. Value Area Rejections: The VAH and VAL lines function as dynamic support and resistance. A price action rejection at the VAH within a downward-sloping channel offers a high-probability continuation setup. POC Magnetism: Price will naturally gravitate toward the sloped POC. Deviations far outside the Value Area typically mean-revert to the POC unless accompanied by a severe volume imbalance. Interpreting Delta: Compare the traditional POC to the Delta POC. If the Delta POC rests significantly higher or lower than the overall Volume POC, it indicates an aggressive concentration of directional absorption (trapped buyers or sellers). Repainting Warning: Because this indicator calculates a dynamic linear regression over a moving lookback window, the visual placement of the channel and profile will continually recalculate and shift on the real-time bar until the bar closes. This is standard behavior for dynamic geometric overlays, but users should wait for bar confirmation before executing trades based on channel interactions. ● ⚙️ Inputs and Settings • Linear Regression Settings Channel Length: Defines the historical lookback window (default is 100). Higher values create smoother, macro-trend profiles. Source: The price data used for the regression calculation (Open, High, Low, Close, HL2, HLC3, OHLC4). Upper/Lower Deviation: Toggles the outer bounds of the channel and sets the standard deviation multipliers. • Sloped Volume Profile Settings Number of Rows: The granularity of the profile. More rows create thinner, more precise volume nodes. Profile Width %: Determines how far the volume polygons stretch across the screen relative to the channel length. Value Area %: The percentage of total volume to include within the VAH and VAL bounds (default 70%). • Advanced Quant Analytics Highlight Footprints: Visually isolates volume bins that exceed two standard deviations above the mean bin volume. Calculate Anchored VWAP: Toggles the inclusion of an Anchored VWAP (anchored to the start of the regression window) within the dashboard matrix. ⚠️ Disclaimer All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. I expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion.Indicador Pine Script®por MarkitTick297
VIGAX/VVIAX 10Y & 15Y Detrended Z-ScoresThis indicator measures how stretched U.S. large-cap growth is versus U.S. large-cap value by analyzing the VIGAX/VVIAX ratio. Because VIGAX represents large-cap growth and VVIAX represents large-cap value, a rising ratio means growth is outperforming value, while a falling ratio means value is outperforming growth. The script calculates the ratio, converts it to log scale, and then fits rolling 10-year and 15-year regression trends. It plots the residual z-score of the ratio relative to those trends. In plain terms, the indicator shows whether growth is unusually strong or weak versus value after accounting for the long-term upward trend in growth/value leadership. A z-score near 0 means the ratio is near trend. A positive z-score means growth is above trend versus value. A negative z-score means growth is below trend versus value. The script plots reference bands at ±1.5, ±2.0, and ±2.5 standard deviations . The signal logic is contrarian and re-entry based. A VALUE signal occurs when the selected z-score has moved above the chosen positive threshold and then crosses back below it. This means growth became statistically stretched and then started to fail. A GROWTH signal occurs when the selected z-score has moved below the chosen negative threshold and then crosses back above it. This means growth became statistically washed out and then started to recover. Suggested use: Use the 15-year z-score for the cleaner, long-cycle signal. Use the 10-year z-score for a more responsive, current-regime read. The ±2.5 threshold is the highest-conviction signal and will fire rarely. The ±2.0 and ±1.5 levels are better treated as early-warning zones rather than automatic trade signals. The indicator does not read manual TradingView trendlines. It creates its own statistical trend using rolling regression. The strongest setup occurs when the z-score signal aligns with the visual long-term channel on the VIGAX/VVIAX chart. The indicator is not designed to work with charts other than the VIGAX/VVIAX chart. Code by ChatGPT 5.5 Thinking Prompts by Jeremy L. A. Hill EdwardsIndicador Pine Script®por jlamadehe8
Z-Score Probability Pro KAMA Z-Score Probability Pro KAMA, v1.0 by Erika Barker Hey guys, this is the successor to my original Z-Score Probability HMA Indicator, which you can still use if you prefer that one. This is version 1.0 of the new rebuild, and it is a pretty big upgrade. The goal was to keep the statistical foundation that made the original useful, but make it more adaptive, cleaner, and better at understanding different market conditions. What is new 1. Timeframe auto-adaptation No more constantly re-tuning the indicator when you switch charts. The lookback now automatically adjusts based on the chart timeframe, using a calendar-style window, defaulting to about 5 trading days. The dashboard also shows the effective lookback being used, so you always know what the script is calculating from. It works from 1 minute charts all the way up to weekly charts. 2. Better smoothing logic The original HMA was doing a lot of work at once. In this version, the baseline and the Z-score smoothing are separated so each one can do its own job better. By default: * Baseline: KAMA, great for adapting to noisy markets * Z-score smoothing: ALMA, smoother and cleaner on the oscillator HMA is still available if you prefer the original feel. 3. Modified Z-Score option There is now an optional Modified Z-Score mode using MAD, median absolute deviation. This is useful for markets with big outliers, fat tails, sudden spikes, crypto moves, small caps, and anything that tends to behave a little wild. When this mode is turned on, the threshold bands automatically adjust. 4. Regime filter using Hurst logic (been needing out on this a lot lately on personal stuff) This version attempts to classify the market as: * Trending * Mean-reverting * Random That matters because an extreme Z-score does not always mean the same thing. In a mean-reverting market, an extreme Z-score can suggest exhaustion. In a trending market, that same extreme can sometimes mean continuation or breakout strength. This was one of the biggest things I wanted to improve from the original. 5. Divergence engine The indicator now includes both regular and hidden divergence. It can detect: * Regular bullish divergence * Regular bearish divergence * Hidden bullish divergence * Hidden bearish divergence Divergences are confirmed using pivots, so they are non-repainting, but they will appear a few bars after the actual pivot. That is the tradeoff for confirmation. 6. Higher-timeframe confirmation The script can pull Z-score confirmation from a higher timeframe. You can use the automatic HTF mode or set it manually. HTF values only update after the higher-timeframe candle closes, so this is designed to avoid repainting. 7. Strong Buy and Strong Sell signals Signals are based on a confluence score instead of just one condition. The score looks at things like: * Z-score reversal * Divergence * Baseline slope * Market regime * Higher-timeframe agreement * Volume confirmation, when volume is available You can choose the conviction level: * Low * Medium * High Medium is the default and should give fewer, cleaner signals. 8. Live dashboard The dashboard shows: * Detected timeframe * Effective lookback * Current Z-score * Market regime * Hurst value * Higher-timeframe status * Bull and bear scores * Conviction threshold * Last signal You can move it to any corner of the chart. 9. More stable defaults The defaults were chosen to be centered in stable performance zones, not over-optimized for one market. Basically, I did not want this to be something that only looks good on one ticker, one timeframe, during one perfect backtest window. 10. Built in Pine v6 This version uses Pine v6 features, including dynamic higher-timeframe requests and confirmed-bar alert logic. Repaint disclosure This indicator is designed to avoid repainting, but there are a few things to know: * Divergence and Strong Buy/Sell labels appear after pivot confirmation, default is 3 bars later * Higher-timeframe confirmation only updates after the higher-timeframe candle closes * Alerts fire on confirmed bars, not intrabar ticks So, signals are delayed slightly by design, but that is what makes them confirmed. How to use it Beginner Leave everything on default. Watch the dashboard and look for: * Strong Buy * Strong Sell Medium conviction is probably the best starting point. Intermediate Try the Modified Z-Score mode on crypto, small caps, or anything with sharp moves and big outliers. Turn on Hidden Divergence if you like trading trend continuation setups. Advanced You can tune the component weights to match your own strategy. The indicator is flexible, so you can make it more reversal-focused, more trend-following, or more confirmation-heavy depending on your trading style.Indicador Pine Script®por erikabarkerAtualizado 23
Linear Regression Scanner (KenshinC)Linear Regression Scanner (KenshinC) + Slope Visual is a powerful real-time multi-symbol dashboard combined with advanced Linear Regression visualization. It analyzes up to 12 major cryptocurrency pairs simultaneously, displaying trend direction, price position relative to the regression midline, RSI(14), and precise slope values in a clean table. Additionally, it plots the Linear Regression Curve and dynamic slope direction arrows directly on the current chart for deeper visual insight. 🔍 WHAT MAKES IT ORIGINAL 1. True Multi-Symbol Linear Regression Engine — Simultaneously calculates full Linear Regression Channels (intercept, endpoint, deviation, and slope) for 12 symbols using request.security(). 2. Dual Linear Regression System — Uses two independent regression calculations: one for the scanner table (default 100 bars) and one for on-chart visualization (default 150 bars) with slope arrows. 3. Slope-Based Trend & Momentum Arrows — Detects trend direction from regression slope and displays intuitive teal/orange arrows showing slope strength on every bar. 4. Price vs Regression Midline Positioning — Real-time comparison of price against the dynamic regression center line. 5. Professional All-in-One Dashboard — Clean, color-coded table with Trend, Price Position, RSI, and Slope — all updated on bar close. 6. Highly Customizable — Independent settings for scanner channel and on-chart regression curve. ⚙️ HOW IT WORKS The scanner uses a custom get_channel() function to compute the best-fit Linear Regression line as follows: mid = math.sum(src, len) / len slope = ta.linreg(src, len, 0) - ta.linreg(src, len, 1) intercept = mid - slope * math.floor(len / 2) + (1 - len % 2) / 2 * slope This produces: - The midline (average of the source over the chosen Channel Length) - The true slope of the regression line (rate of change) - Intercept and projected endpoint for accurate current-bar positioning - Standard deviation around the line (ready for future deviation bands) Trend is determined directly from the slope: positive slope = Bullish, negative slope = Bearish. Price vs Middle compares the current price to the regression line value at the current bar. For the on-chart visualization (inspired by emiliolb): lrc = ta.linreg(close, lrc_len, 0) lrprev = ta.linreg(close , lrc_len, 0) slope_current = (lrc - lrprev) This plots a smooth red Linear Regression Curve (default 150 bars) and displays slope direction with arrows: Teal ↑ for positive/strengthening slope (bullish momentum) and Orange ↓ for negative/strengthening slope (bearish momentum). RSI(14) is calculated independently for each symbol to show overbought (>70) and oversold (<30) conditions. The entire dashboard refreshes on every bar close using efficient array looping. 📖 HOW TO USE Reading the Dashboard Table (Top Right): - Symbol: Ticker name (e.g., BTCUSDT) - Trend: Green = Bullish (positive slope), Red = Bearish (negative slope) - Price VS Middle: Green = Price above regression midline (bullish positioning), Red = Below midline (bearish positioning) - RSI: Lime Green (<30) = Oversold, Yellow (30–70) = Neutral, Red (>70) = Overbought - Slope: Precise numerical value — the higher the positive number, the stronger the uptrend; the lower the negative number, the stronger the downtrend. Reading On-Chart Visuals: - Red Curve: Linear Regression Curve (default 150 bars) — serves as a dynamic trend baseline. - Teal Arrows ↑: Positive and strengthening slope → bullish momentum. - Orange Arrows ↓: Negative and strengthening slope → bearish momentum. Suggested Trading Workflow: 1. Scan the table for Bullish symbols showing “Bullish” + “Above” + strong positive Slope. 2. Confirm RSI is not extremely overbought (>70). 3. Switch to the symbol and observe the Red LRC Curve together with Slope Arrows for precise timing. 4. Look for strong confluence: Positive slope + price above midline + teal arrows = high-probability trend continuation setup. 5. Best performance on 15m, 1H, and 4H timeframes. 6. Always combine with support/resistance levels, volume, or higher-timeframe analysis. Best Practices: - Use longer Channel Length (100+) for smoother, longer-term trend detection. - Adjust Linear Regression Length (150) to control the smoothness of the on-chart curve and arrows. - Works excellently on major USDT perpetual pairs. ⚙️ KEY SETTINGS REFERENCE - Symbols: 12 pre-loaded major Binance USDT pairs (fully customizable) - Linear Regression Slope Section: Show Curve, Show Arrows, Length (default 150), Color, Width - Channel Settings: Source (default = low), Channel Length (default 100), RSI Length (default 14) - Colors: Up Trend and Down Trend colors 🔔 Alerts No built-in alerts yet. You can easily create manual alerts for slope direction changes, price crossing the regression midline, or RSI extremes. ⚠️ IMPORTANT NOTES — On-chart Linear Regression Curve and Slope Arrows are calculated and displayed only for the current symbol you are viewing. — The scanner table analyzes all 12 symbols independently in real time. — All calculations are performed on bar close to prevent repainting. — Slope values are not normalized across different assets — only compare them within the same symbol and timeframe. — Strong slope signals indicate trend strength but do not guarantee future price movement. — This indicator uses multiple request.security() calls. Avoid overloading the chart with too many other indicators. — Past performance is not indicative of future results. This tool is for educational and analytical purposes only. — Not financial advice. Always use proper risk management and trade at your own risk. --- Made with passion by KenshinC Happy trading & trend hunting! 🚀Indicador Pine Script®por KenshinC10
Daily Bias with Linear RegressionOverview The Daily Bias with Linear Regression is a trend-following tool designed to help traders identify the prevailing market direction by aligning the momentum of two critical timeframes: the Daily (D1) and the 4-Hour (H4). By using Linear Regression slopes, this indicator filters out market noise and provides a clear "Bullish," "Bearish," or "Neutral" signal. How It Works The indicator calculates the slope of price action using Linear Regression over two specific periods: Daily (D1): 20-period lookback. 4-Hour (H4): 18-period lookback. The Daily Bias is determined as follows: 🟢 BULLISH: When both the D1 and H4 slopes are positive. 🔴 BEARISH: When both the D1 and H4 slopes are negative. ⚪ NEUTRAL: When the slopes are conflicting (e.g., D1 is up, but H4 is down). Key Features Multi-Timeframe Analysis: Automatically fetches data from higher timeframes (D1 and H4) to provide a macro perspective even if you are on a lower timeframe. Anti-Repaint Logic: The script is coded to fetch the slope of the *previous* closed bar, ensuring that the signals remain stable and do not repaint. Real-time Dashboard: A clean table in the top-right corner displays the current ticker and the live bias status. Visual Labels: Direct "Bullish" or "Bearish" labels are plotted on the chart for immediate visual confirmation. Timeframe Guard: Includes a built-in warning if the chart timeframe is set below 1-Hour (H1), as the indicator is optimized for higher timeframe confluence. How to Use Trend Confirmation: Use the "BULLISH" or "BEARISH" status to align your trades with the higher timeframe momentum. Filter: Avoid taking long positions when the bias is "BEARISH" or short positions when it is "BULLISH." Wait for Alignment: A "NEUTRAL" bias suggests a ranging market or a potential trend change; waiting for both timeframes to align can increase trade probability. Disclaimer: Trading involves significant risk. This indicator is for educational and informational purposes only and does not constitute financial advice. Indicador Pine Script®por aideelystAtualizado 12
Artemis Regression Bands🟦 Artemis Regression Bands is a kernel-driven volatility envelope indicator built on the KernelLens Nadaraya–Watson regression library (a_jabbaroff/KernelLens/1). A single kernel estimate — selectable from eight classical kernel families — anchors the Fair Value line. Around it, three residual-standard-deviation bands (±1σ, ±2σ, ±3σ) fan outward with either Linear or Exponential spacing, producing a statistically grounded envelope far cleaner than the classical close-stdev approach used by legacy Bollinger-style indicators. A four-gate Romb signal engine overlays buy / sell diamond markers when price pokes through the outermost enabled σ boundary and reverses back inside. 🟦 HOW IT WORKS Artemis calls the KernelLens library's unified dispatcher once per bar to build the Fair Value line, then queries three additional library exports to derive the band widths, slope direction, and residual σ: ``` fair = kl.estimate (type, src, ℓ, α, period, phase, filter) sigma = kl.confidenceBand(src, fair, window) slopeVal = kl.slope (fair, 1) trendSt = kl.trendState (fair, 1) dev = baseMult · sigma upper1 = fair + 1·dev lower1 = fair − 1·dev upper2 = fair + 2·dev lower2 = fair − 2·dev upper3 = fair + k3·dev lower3 = fair − k3·dev (k3 = 3 Linear | 4 Exp) ``` The library handles all weighted-sum computation, loop-depth selection, NA-safe iteration, division-by-zero guards, and input validation internally. Artemis contains zero kernel math — every bug fix or optimization in the library automatically propagates to this indicator. 🟦 KERNEL LIBRARY INTEGRATION Artemis imports the published KernelLens library and uses the following exports: | Library Export | Used For | |---|---| | `kl.estimate()` | Unified dispatcher — routes to the correct kernel based on the user's Kernel Type dropdown. Called once per bar to produce the Fair Value line. | | `kl.confidenceBand()` | Rolling standard deviation of the (source − Fair Value) residual. Drives the band half-widths on every bar. | | `kl.slope()` | Discrete first derivative of the Fair Value line. Feeds trend flip alerts. | | `kl.trendState()` | Ternary classifier (+1 rising / −1 falling / 0 flat) of the Fair Value line. Drives the slope-adaptive color, the kernel trend confluence filter, and the dashboard Trend row. | Every regression computation — kernel weight evaluation, NA-safe summation, bandwidth-aware loop termination, residual stdev, finite-difference slope — is delegated to the library. The indicator itself only orchestrates the four library calls and layers the visual pipeline on top. 🟦 EIGHT KERNEL FAMILIES A single Kernel Type dropdown selects any of the eight kernels shipped with the KernelLens library. Each is a different mathematical smoother with its own statistical character: | Kernel | Formula | Best For | |---|---|---| | Rational Quadratic | (1 + d² / (2·α·ℓ²))^(−α) | Multi-scale mixer; α controls stretch. Recommended default. | | Gaussian / RBF | exp(−d² / (2·ℓ²)) | Canonical smoother; infinitely differentiable. | | Periodic | exp(−2·sin²(π·d/p) / ℓ²) | Resonates with a known repetition distance p. | | Locally Periodic | Periodic × Gaussian | Seasonal patterns with slow trend drift. | | Epanechnikov | (3/4)·(1 − u²), \|u\| ≤ 1 | MSE-optimal; compact support, no tail contamination. | | Tricube | (70/81)·(1 − \|u\|³)³, \|u\| ≤ 1 | LOWESS standard; near-Gaussian compact profile. | | Triangular | (1 − \|u\|), \|u\| ≤ 1 | Simplest compact kernel; cheapest to compute. | | Cosine | (π/4)·cos(π·u/2), \|u\| ≤ 1 | Raised-cosine; smooth boundary transition. | Because the dropdown feeds the library's `kl.estimate()` dispatcher directly, every kernel inherits the same three-mode filter layer (No Filter / Smooth / Zero Lag) and the same non-repainting guarantees — there is no special case per kernel in Artemis. 🟦 FILTER LAYER A second dropdown applies an optional post-processing layer on top of the raw Nadaraya–Watson estimate: | Filter | Formula | Trade-off | |---|---|---| | No Filter | ŷ = ŷ_raw | Single-pass kernel. Rawest output, most reactive. | | Smooth | ŷ = K(ŷ_raw) | Double-pass — kernel applied to its own output. Cleaner line, slightly more lag. | | Zero Lag | ŷ = 2·ŷ_raw − K(ŷ_raw) | Ehlers de-lagging identity — sharpens edges without adding lag. | The filter is resolved entirely inside `kl.estimate()`, so switching modes incurs no runtime cost beyond the extra kernel pass. 🟦 RESIDUAL-σ BAND ENGINE Artemis bands are statistically grounded on the residual standard deviation — not on raw close stdev as in classical Bollinger indicators. The residual is computed as: ``` residual = src − fair sigma = ta.stdev(residual, window) // via kl.confidenceBand() ``` Because Fair Value is already an unbiased local estimate of the source, the residual is a zero-mean noise series and its stdev captures **only the portion of price variance that the kernel could not explain**. This produces three benefits over the classical approach: 1. **Tighter bands in trending regimes** — close-stdev widens during strong trends because the trend itself inflates the variance; residual-σ does not, because the kernel absorbs the trend. 2. **Faster reaction to volatility regime changes** — residual-σ tightens as soon as the kernel fits well, and widens the instant the market breaks out of the kernel's neighborhood. 3. **True statistical interpretation** — under the assumption of locally Gaussian residuals, ±1σ / ±2σ / ±3σ enclose approximately 68 % / 95 % / 99.7 % of near-term price variation. The traditional close-stdev envelope carries no such interpretation. A dedicated Residual σ Window input controls the lookback; typical values range from 50 (reactive, scalping) to 300 (stable, position trading). 🟦 BAND SPACING MODES Two spacing presets shape the outward fan of the three σ bands: | Mode | Multipliers | Character | |---|---|---| | Linear | 1·, 2·, 3· | Classical Bollinger-style uniform steps. Predictable, symmetric. | | Exponential | 1·, 2·, 4· | Fibonacci-flavored — outer band (4σ) is reserved for genuine blow-off excursions. | Base Multiplier scales all three bands uniformly (default 1.0). The formula is: ``` band_level = fair ± (baseMult · k · sigma) k ∈ {1, 2, k3} ``` where k3 resolves to 3 in Linear mode and 4 in Exponential mode. Every band has an independent visibility toggle, so minimalist users can run ±1σ only, swing traders ±3σ only, or any combination. 🟦 FOUR-GATE ROMB SIGNAL ENGINE The Romb engine prints buy / sell diamond markers when price pokes through the outermost enabled σ band and reverses back inside. Four sequential gates protect against false entries: | Gate | Logic | Purpose | |---|---|---| | 1 — Crossover | `ta.crossunder(high, triggerUp)` / `ta.crossover(low, triggerDn)` | Detects the reversal back through the outer band. | | 2 — Warm-up | Residual σ computable for N consecutive bars | Blocks signals during the early kernel-settlement window. | | 3 — Confluence | Fair Value slope aligns with the reversal direction | Optional PRO filter — Sell Romb requires falling kernel, Buy Romb requires rising kernel. | | 4 — Cooldown | Minimum bar gap since the last same-side Romb | Prevents signal clustering on a single extended poke-and-reverse sequence. | A Signal Mode toggle layers on top: - **Confirmed** — signals fire only on `barstate.isconfirmed`; zero repaint on closed bars. - **Realtime** — signals fire live on the current open bar; faster reaction, may vanish if price reverses before close. Each confirmed signal is rendered as a two-layer neon diamond: - **Halo** — `size.small`, 40 % transparent theme hue (glow layer). - **Core** — `size.tiny`, fully opaque theme hue (bright center). The halo renders first so the core sits cleanly on top, producing a sharp luminous marker that reads instantly even on dense price charts. 🟦 ADAPTIVE OUTER-BAND TRIGGER The Romb engine does not hard-code the ±3σ band as the signal trigger. Instead, it resolves the outermost currently-enabled band on every bar: ``` triggerUp = show3 ? upper3 : show2 ? upper2 : show1 ? upper1 : na triggerDn = show3 ? lower3 : show2 ? lower2 : show1 ? lower1 : na ``` The result is an envelope that respects the user's visibility choices: | Visible Bands | Romb Fires At | |---|---| | ±1σ + ±2σ + ±3σ | ±3σ (default) | | ±1σ + ±2σ | ±2σ | | ±1σ only | ±1σ | | All off | no signals | Diamond positioning follows the same trigger, so the glyph always floats ~0.3σ outside whatever envelope is actually drawn on the chart. The behavior matches user intent: the band I can see is the band that fires signals. 🟦 NON-REPAINTING BEHAVIOR Artemis inherits non-repainting behavior directly from the KernelLens library's `_phase` parameter. A single Phase input (default 2) shifts the kernel center into the past by that many bars: - **Phase = 0** — live estimate, flickers on the current bar (real-time only; history is immutable). - **Phase = 1** — 1-bar lag, non-repainting once the bar is confirmed. - **Phase = 2** — recommended balance between freshness and stability (default). - **Phase = 3+** — extra margin against erratic ticks, higher lag. Historical repainting never occurs at any phase value. The library contains no `request.security` calls, no lookahead, and no array rotation that could leak future data. Every historical bar's plotted Fair Value, band, and Romb signal is final once confirmed. 🟦 VISUAL PIPELINE **σ Band Outlines** — Three upper bands (±1σ / ±2σ / ±3σ) in progressively lighter `thBear` hues, three lower bands in progressively lighter `thBull` hues. Hidden bands collapse to na via their individual visibility toggles; the outline widths share a single Band Line Width input. **Tapered Gradient Fills** — Six fills drawn between the Fair Value line and each σ band. Opacity scales progressively from ±1σ (densest, most opaque) to ±3σ (lightest, most transparent), creating a halo that mirrors the statistical density of price residuals under normality. Master Fill Opacity input (0 = invisible, 100 = fully opaque) scales all three fills uniformly. **Fair Value Line** — Slope-adaptive color resolver swaps between `thBull` (rising kernel) and `thBear` (falling kernel). Flat bars retain the previous color so the line never flashes neutral on a perfectly horizontal tick. Width is user-controlled (1–5 px). **Romb Diamonds** — Two-layer neon glow at the adaptive trigger band; halo + core rendering described above. **Bar Coloring** — Optional theme-aware candle coloring driven by the Fair Value slope. Off by default; when enabled it paints every bar with the active theme's bull / bear hue based on the current trend state. 🟦 THEME SYSTEM Twelve cohesive color palettes drive every visual component — Fair Value line, σ band outlines, gradient fills, Romb diamonds, bar coloring, and dashboard accents — all sharing the same four color axes (`thBull`, `thBear`, `thNeutral`, `thSignal`): | Theme | Bull | Bear | |---|---|---| | Tropic | Cyan steel | Deep orange | | Amber | Warm amber | Indigo blue | | Pastel | Sky blue | Soft lavender | | Cyber | Neon lime | Hot crimson | | Helios | Bright gold | Scarlet | | Electric | Electric aqua | Magenta | | Candy | Neon green | Hot pink | | Bloomberg | Terminal orange | Cyan | | Solar | Solarized olive | Crimson | | Royal | Imperial gold | Deep purple | | Midnight | Deep navy | Dark crimson | | Graphite | Near-black | Silver grey | A separate Display Mode toggle (Dark / Light) controls the dashboard palette independently of the chart theme — so a Bloomberg chart theme with a Light dashboard is a valid configuration, as is Midnight chart + Dark dashboard. 🟦 DASHBOARD A 2-column, 12-row theme-aware status panel that updates only on the last bar (zero historical overhead). Supports Dark and Light display modes, six docking positions, and four text sizes. Renders via `force_overlay = true` on the main price chart. | Row | Label | Content | |---|---|---| | Header | ARTEMIS | DARK / LIGHT | | Theme | Theme | Active palette name | | Kernel | Kernel | Selected kernel type | | Divider | REGRESSION | — | | Bandwidth | Bandwidth ℓ | Bandwidth value / Phase offset φ | | Filter | Filter | No Filter / Smooth / Zero Lag | | Fair Value | Fair Value | Current Fair Value in chart mintick format | | Divider | BANDS | — | | Spacing | Spacing | Linear 1·/2·/3· or Exp 1·/2·/4· | | Residual σ | Band σ | Rolling residual standard deviation | | Trend | Trend | ▲ BULL / ▼ BEAR / ━ FLAT (bull/bear colored) | | Last Romb | Last Romb | ▲ BUY (N ago) / ▼ SELL (N ago) — bull/bear colored | **Zebra-stripe layout** — alternating `dashBg` / `dashBgAlt` row backgrounds improve scan-ability on narrow cells. Section dividers (REGRESSION, BANDS) use a third background tone (`dashSection`) with the theme's bull accent as the header color — preserving brand identity across both Display Modes. 🟦 ALERT CONDITIONS Six opt-in alert conditions, each gated by its own toggle: | Alert | Fires When | |---|---| | Bullish Trend Flip | Fair Value slope crosses from ≤ 0 into positive territory | | Bearish Trend Flip | Fair Value slope crosses from ≥ 0 into negative territory | | Buy Romb | Confirmed Buy Romb fires — all four signal gates passing | | Sell Romb | Confirmed Sell Romb fires — all four signal gates passing | | Upper Band Touch | Price touches or exceeds the outermost enabled upper band | | Lower Band Touch | Price touches or falls below the outermost enabled lower band | All alerts use `alertcondition()` for maximum compatibility with TradingView's alert system including webhooks. Messages are structured as `"Artemis Regression Bands: "` for easy parsing in downstream automation. Touch alerts are off by default (can be noisy in trending markets); the four core alerts are on by default. 🟦 RECOMMENDED PRESETS | Style | Bandwidth ℓ | Filter | Phase | Spacing | σ Window | Chart | |---|---|---|---|---|---|---| | Scalper | 10–20 | No Filter | 1 | Linear | 50–80 | 1m–5m | | Day Trader | 20–40 | Smooth | 2 | Linear | 80–120 | 15m–1h | | Swing | 30–60 | Smooth | 2 | Linear or Exp | 100–200 | 4h–1D | | Position | 60–120 | Smooth or Zero Lag | 3 | Exp | 200–300 | 1D–1W | **Kernel type tuning** - **Trending instruments** — Rational Quadratic (α = 1–3) or Gaussian. Smooth multi-scale response. - **Mean-reverting instruments** — Epanechnikov or Tricube. Compact support keeps the band envelope tight. - **Session-cyclic patterns** — Periodic (with p = session length in bars) or Locally Periodic. Resonates with known cycles. **Romb filter tuning** — Keep Kernel Trend Confluence ON for high-conviction setups only. Switch OFF on range-bound instruments to capture both sides of the oscillation. 🟦 COMPATIBILITY - Pine Script v6 - All exchanges, all asset classes (crypto, forex, equities, commodities, indices) - All timeframes (1 minute through Monthly) - Both Dark and Light chart themes — the Display Mode toggle controls dashboard palette independently - No exchange-specific logic — fully deterministic 🟦 TECHNICAL NOTES - **Library dependency** — `import a_jabbaroff/KernelLens/1` — all kernel regression, residual σ, slope, and trend-state math is delegated to the published library. - **Plot budget** — 6 band plots + 1 Fair Value anchor + 1 Fair Value visible + 6 gradient fills + 4 Romb plotshapes + 1 barcolor = well under Pine's plot limits. - **Table** — Single `var table` rebuilt on `barstate.islast` with `force_overlay = true`; zero historical overhead. - **Signal state** — Two `var int` cooldown anchors (`lastSellBar`, `lastBuyBar`) seeded at −10000 so the very first bar always passes the gap test. A `var int stabCount` warm-up counter blocks signals during early kernel settlement. - **No persistent drawing objects** — no `box.new`, `line.new`, no array rotations; every visual is either a plot or a single-bar plotshape. - **Adaptive trigger resolver** — Romb crossover detection, touch alerts, and diamond positioning all read from the same `triggerUp` / `triggerDn` resolver, so band visibility toggles stay semantically coherent across every layer of the indicator. - **Non-repainting** — inherits from the library's `_phase` parameter; no `request.security`, no lookahead, no future-bar leakage at any phase value. 🟦 DISCLAIMER Artemis Regression Bands is a technical analysis indicator built on the KernelLens Nadaraya–Watson regression library. It is provided solely for educational and research purposes and does not constitute financial, investment, or trading advice. Kernel regression is a local smoothing technique. It estimates the mean of a source series in the neighborhood of the current bar based on historical data, but it does not predict future prices, does not generate trading signals on its own, and does not guarantee the profitability of any strategy built on top of its output. The residual-σ envelope describes past dispersion around the kernel estimate — not a forecast of future range — and should always be combined with broader context: higher-timeframe structure, volatility regime, liquidity, news, and risk management. Past performance of any model does not guarantee future results. Markets contain systemic risks that cannot be eliminated by any amount of mathematical rigor. Responsibility for any trading decisions rests entirely with the user. Always apply sound capital management, conduct your own independent analysis, and never risk capital you are not prepared to lose. The author assumes no liability for direct or indirect losses incurred through the use of Artemis Regression Bands or the underlying KernelLens library.Indicador Pine Script®por a_jabbaroff66743
Adaptive ProjectionAdaptive Projection is a personal chartist projection tool I use on my own charts to estimate what could be the most logically consistent continuation of trend structure. This script is not built to “predict” the future with certainty. Its purpose is to project, in the most structurally disciplined way possible, what trend continuation could look like if the current market architecture keeps unfolding in a coherent manner. Most projections are simplistic. They extend one line, one slope, or one regression and assume that is enough. This script takes a much more demanding approach. It evaluates trend structure across three different horizons — short-term, long-term, and very long-term — because a serious chart model should not treat all trends as if they were describing the same layer of information. The core idea is simple to understand intuitively: if trend continuation is going to remain chart-consistent, then the best projection should come from the alignment of multiple valid channel structures, not from one isolated line. So instead of relying on a single channel, this script: - finds the best short-term channel, - finds the best long-term channel, - finds the best very long-term channel, - evaluates how solid each one is, - then combines them with weighted logic so that higher-timeframe structure does not have the same role as lower-timeframe structure. This is what makes the projection much more robust than a standard extrapolation. At a practical level, the script tries to answer this question: if the market continues in the most structurally logical way, what could that path look like? To do that, it does not draw one naive straight projection. It builds the forward path adaptively, step by step. That is why the result is a curved projection rather than a rigid line to a distant endpoint. Each segment is informed by the structural information extracted from the three channel horizons, with different weights and multiple quality filters. Why this approach is strong: 1. It is multi-horizon by design. A short-term channel can capture recent acceleration or deceleration. A long-term channel can capture the dominant structure. A very long-term channel can capture the background trend regime. The script does not flatten these into one simplistic view. It lets each horizon contribute according to its own importance. 2. It does not trust channels blindly. Each candidate channel is filtered and scored using several structural criteria. The script is not just looking for a slope that “looks good”. It checks whether the channel is statistically coherent and structurally usable. 3. It favors robustness over convenience. The script gives priority to channels that are eligible under demanding conditions. If no channel fully satisfies all conditions, it can still fall back to the best available candidate, but the model’s confidence reflects that reduced robustness. 4. It projects adaptively instead of mechanically. A single straight projection assumes the same structure stays dominant all the way forward. This script is more nuanced: it builds the path progressively, so the projected curve better reflects how trend continuation would logically unfold if current structure persists. 5. It expresses internal agreement. The confidence reading is not a claim of probability. It is a structural coherence score. It tells you how strongly the selected channels and their projected paths agree with each other. High confidence means stronger internal alignment. Low confidence means weaker convergence or more structural disagreement. This indicator is especially useful if you want a serious chart-based framework for thinking about continuation, scenario planning, and directional structure without reducing everything to a simplistic trendline extension. How the model works in more detail: - The script scans predefined ranges for short-term, long-term, and very long-term channel lengths. - For each candidate, it computes a regression-based channel structure. - It measures Pearson correlation to evaluate linear coherence. - It measures containment to verify whether price behavior actually respects the channel. - It measures channel width to penalize structures that are too loose to be informative. - It uses ADX-based information to confirm that the structure is supported by meaningful trend conditions rather than noise. - It computes trend efficiency to distinguish cleaner trends from unstable ones. - It computes a stability score by comparing neighboring candidate lengths, which helps avoid selecting fragile one-off fits. - It combines these elements into a selection score designed to favor robust structural candidates. Once the best channel has been identified for each horizon, the script then: - projects the future location of each channel, - measures where current price sits within each channel, - estimates the most logical future continuation relative to that internal channel position, - applies horizon-specific importance weights, - applies quality-based weights, - adjusts for horizon fit, - and blends everything into one adaptive projection path. That means the final projection is not the result of one indicator condition. It is the result of a layered structural decision process. The Annualized Line Return should also be interpreted carefully. It is not a claim of expected performance. It is simply a normalized way to express the implied rate of change of the projected path over the selected horizon. Important limitations: - This script does not know the future. - It does not incorporate news, macro shocks, liquidity events, or sudden regime changes. - It is not a trading system and should not be read as a guaranteed directional forecast. - It is a structural chart model designed to estimate the most logically consistent continuation of trend if the existing architecture persists. - It is most meaningful in markets where structure exists. In chaotic or regime-shifting environments, confidence will usually degrade, which is appropriate. In short, this is the projection tool I personally keep on my charts when I want the most advanced and structurally grounded chartist estimate of what trend continuation could logically look like. It is built for one purpose: to project trend continuation with as much internal discipline, multi-horizon structure, and robustness as possible.Indicador Pine Script®por Julien_ExeAtualizado 216
Automate on Hyperliquid - Strategy Webhook Template [HYPR-run]DESCRIPTION You define the entry signal. The system manages everything after the fill. This is a production-grade trade system for automating strategies on Hyperliquid using TradingView webhooks. Five-level priority chain trade system. Four ATR trailing architectures including volume-weighted ATR with Efficiency Ratio scaling and ratchet floor. Smart stops that exit when a trade is invalidated. Pyramid scaling into winners and a redundant failsafe stop. Three signal systems are included ready to backtest and deploy (EMA crossover, Turtle breakout, SFP - Swing Failure Pattern) that you can toggle on/off independently; replace or extend them with your own logic in three places: the input toggle, the signal condition, and the priority chain entry call. There are clear landmarks in the code to make it as straightforward as possible. This strategy is built for you to hit the ground running backtesting or automating with a systematic framework to execute around your entry logic or the example signals provided. All signals fire on confirmed bar closes only. Entries, exits, pyramids, and stops are evaluated at close, not during the bar, so intrabar wick spikes do not trigger the system. This is by design. No lookahead bias: all highest/lowest references use prior-bar offsets, LinReg is calculated with offset=1, and no security() calls are used. The script does not repaint or compound returns. WHAT THE STRATEGY SYSTEMIZES 1. Five-Level Priority Action Chain Entries fire first. Pyramids fire second and block exits on the same bar. Trailing exits ride winners. Smart stops catch failing trades early. Failsafe stop is the absolute floor. The if/else order is intentional and prevents conflicts so that every action occurs only when it should. 2. Four ATR Trailing Stop Modes Select from a dropdown. All use separate long/short look backs and multipliers because drops are faster than rallies; the defaults reflect this asymmetry. • A3.1: LinReg + plain ATR, no ratchet. Baseline for comparison. • A4.0 (default): LinReg + volume-weighted ATR + Efficiency Ratio + ratchet. VWATR discounts low-volume bars. ER tightens in chop (0.8x), widens in trend (1.2x). Ratchet means the stop only moves in your favor. • A4.1: Chandelier + VWATR + ratchet + first-bar multiplier for tighter initial protection. • A4.2: LinReg + VWATR, no ratchet or ER. Stop moves freely with projection. ***The multipliers determine how much room the stop gives price before triggering. They have the greatest influence on overall system performance and must be tuned to the asset and timeframe being traded. Default values are a starting point, not final settings. • L Multi: 4.0 (long stop distance). Wider because uptrends are slower and require more room. • S Multi: 2.0 (short stop distance). Tighter because drops are faster and corrections are sharper. • Long LB: 14 bars. ATR lookback for long stops. • Short LB: 26 bars. ATR lookback for short stops; longer lookback smooths volatile short-side moves. • LinReg LB: 10 bars. LinReg projection window (A3.1, A4.0, A4.2). • First Bar Mult: 1.5x (A4.1 only). Tighter stop on the entry bar; expands to standard multiplier after. 3. Smart Stops Two trigger paths, both requiring open P&L below threshold (default -3.5%): (1) price crosses under the trailing stop while losing, or (2) price breaks the entry bar’s structure while losing. Either path exits the trade before the failsafe would trigger. The P&L condition on both paths prevents exits on noise when the trade is still within normal range. 4. Pyramid Entries Scales into winning trades on 5-bar extremes. Requires full bar confirmation and must be within 13 bars of the initial entry. 5. Basic Entry Quality Filters Applied automatically to every entry: • Wick nullification: bars with wicks > 38.2% of range block entries in that direction • SFP nullification: active reversal patterns block opposing entries • Full bar filter: candle body must be >= 66.6% of total range • Bar confirmation: entries only fire on confirmed bars THREE SIGNALS INCLUDED (replace or extend) • XO/XU: EMA crossover with four configurable pairs (5/13, 9/26, 12/25, 26/128). Requires price above swing high (longs) or below swing low (shorts) plus volume spike (Dropdown Selection). • Turtle: 13/26 bar breakout with Lost Trade System logic. First breakout after an opposing signal gets priority. • SFP: Swing Failure Pattern. Longs fire on either 5/5 with full-body confirmation or 5/2 with bullish candle confirmation and strong volume spike (1.618x average). Shorts fire on 5/5 with full-body or 13/3 with bearish candle confirmation. Dual-path per direction allows the signal to catch both high-conviction structure failures and high-volume reversals. The function accepts any left/right look back combination, making it straightforward to adapt. (#/# refers to pivot look back left and right) Each has its own toggle. Enable one, combine them, or swap in your own signals. WEBHOOK AUTOMATION Every fill event fires through TradingView’s built-in webhook system when enabled: entries, exits, pyramids, smart stops, and failsafe closes. To execute those webhooks on Hyperliquid, an intermediary service (execution layer) that accepts TradingView webhooks and routes orders to Hyperliquid's API is required. Setup: 1. Create an alert on this strategy 2. Set trigger to "Order fills only" 3. Check Webhook URL, paste your endpoint 4. Message box: {"ticker":"{{ticker}}","position":"{{strategy.market_position}}"} 5. Set expiration to Open-ended The snippet will most likely require customization depending on your execution layer. The {{ticker}} and {{strategy.market_position}} fields are TradingView placeholders that auto-populate when a strategy signal fires. We recommend referencing TradingView’s Strategy Alerts documentation to fully understand placeholder use and function when setting up your snippet for your execution layer: www.tradingview.com BUILDING WITH YOUR OWN SIGNALS The most straightforward path is adding your own entry logic. The ATR module, smart stops, and pyramids can also be edited to preferred logic while still leveraging the systemized structure for clean execution when automating on an exchange. Option 1: Replace an existing signal. Find its section under the SIGNALS header (look for "EXAMPLE 1", "EXAMPLE 2", or "EXAMPLE 3"). Delete the example code and write your condition in its place. Find the matching entry in the STRATEGY CALLS priority chain and swap the condition variable. The toggle still works; rename its label in the input line. Everything downstream works automatically. Option 2: Add a new signal. Three places to touch: 1. Copy a strategy toggle line from the STRATEGIES input group, change the variable name and label 2. Add your signal logic in the SIGNALS section as a boolean 3. Add an else-if block in the STRATEGY CALLS priority chain using your toggle as the gate Two test switches (Tsw1, Tsw2) are reserved in Settings for custom signals. READING THE CHART Candles are colored by direction: black bodies up, gray bodies down (Quant Filter toggle). The trailing stop draws as a colored line following your position: green below price when long, red/orange above price when short. A gradient fill shades the zone between price and the stop; it intensifies as price approaches the exit level. Green dots on the long stop line and red dots on the short stop line are ratchet markers (A4.0 and A4.1 only). Each dot means the stop locked in a new level and will not pull back. Entry labels appear at each fill: "xoL" (EMA long), "xuS" (EMA short), "tL" (Turtle long), "tS" (Turtle short), "sfpL"/"sfpS" (SFP entries), "pyrL"/"pyrS" (pyramid adds). Exit labels: "Cl"/"Cs" (trailing close long/short), "smrtstp" (smart stop), "fstp" (failsafe). SFP candle wicks are color-coded by lookback: 5/5 bull wick = bright green, 5/2 bull wick = dark green, 5/5 bear wick = bright red, 13/3 bear wick = dark red. The shade tells you which configuration triggered — brighter means the more common 5/5 detection, darker means the secondary lookback fired. Horizontal lines extending from entry price are the Late Entry Window: white solid line is entry price, green dashed line is entry + ATR window, red dashed line is entry - ATR window. Visual reference only; does not affect trade logic. Useful when away from the screen to quickly see if a missed entry is still within a safe ATR range. Market structure labels (HH, LH, HL, LL) appear at swing pivots when the Structure toggle is enabled. RISK MATH Order size is fixed at $5,000 (50% of starting capital). That means it's always a flat $5k order, no compounding. With the failsafe at -5.25%, maximum loss per trade is $262.50, or 2.625% of the $10,000 starting balance. *Because order size is fixed in dollars while equity grows, risk as a percentage of equity decreases over time: 2.625% at start, 2.1% at $12,500, 1.75% at $15,000. The smart stop triggers before the failsafe in most cases, reducing average realized loss further. STRATEGY PROPERTIES (What's used in the chart published here) Strategies (all off by default - toggle on to activate): • XO/XU: on • Turtle: on • SFP: on Settings: • Mode: Historical (switch to Bot Mode for live automation - limits calculation depth for speed) • EMA Pair: 9/26 Risk Management: • Smart Stop: on | -3.5% • Failsafe Stop: on | -5.25% • Mech TP/Cls: on ATR Trailing Exits: • Mode: A4.0 • L Multi: 4.0 | S Multi: 2.0 • Lng LB: 14 | Shrt LB: 26 • LinReg: 10 | First Bar: 1.5 (A4.1 only) Backtest Properties: • Initial capital: $10,000 • Commission: 0.05% • Slippage: 2 ticks • Order size: $5,000 (cash, fixed) • Fill limit assumption: 5 ticks • Max risk per trade: $262.50 (2.625% of starting equity) CREDITS ATR: J. Welles Wilder (1978). Efficiency Ratio: Perry Kaufman. Turtle breakout concept: Richard Donchian.Estratégia Pine Script®por HYPR-run60
OBV Linear Regression Multi-Slope [HYPR-run]DESCRIPTION: Three linear regression slopes fitted to On-Balance Volume. Measures whether accumulation or distribution is accelerating, decelerating, or reversing across short, medium, and long lookbacks simultaneously. Raw OBV tells you the cumulative direction of volume flow. Fitting a linear regression to it gives you the rate of change: the slope. Three slopes at different lookbacks show the structure of volume commitment. When all three agree, volume flow is structurally committed in one direction. When they disagree, the timeframes are in conflict. DISCOVERING EDGE Dual and triple slope alignment has proven to be a staple confirmation signal in our most reliable automated strategies for both entries and exits. When two or three independent lookbacks agree on the direction of volume flow, the commitment is structural, not noise. When alignment breaks, the first slope to flip tells you exactly where conviction cracked. We built this indicator to surface that alignment as a first-class signal rather than something you eyeball across separate panes. THREE LR SLOPES vs RAW OBV LINE Three slopes at different lookbacks show whether all timeframes of volume flow agree or conflict. Dual alignment (short + long) is the entry signal; triple (all three) confirms later for pyramids. When triple breaks, that's the exit. Values above 0.3 mean the slope is steeper than one standard deviation per bar (very strong trend). Sigma/bar above 0.1 means the slope is statistically strong; below 0.05 is weak. FEATURES - Three linear regression slope lines on OBV (short 9, medium 26, long 50) - Optional adaptive short lookback (ATR-scaled for low timeframes) - Slope alignment detection: dual (short+long) and triple (all three) - Universal angle normalization (slope/sigma x 45 degrees) - Sigma/Bar ratio: slope strength relative to OBV noise - Auto-adjusts all lookbacks by timeframe (weekly/monthly compress) - Webhook alerts on slope flip or triple alignment - Full bar filter rejects doji/wick-heavy bars - Dashboard with lookback, angle, and sigma/bar for all three lines HOW IT WORKS Linear regression calculates the best-fit line through OBV values over a lookback window. The slope of that line is the rate of volume flow. Positive slope = accumulation accelerating. Negative slope = distribution accelerating. The universal angle normalizes raw slope by OBV standard deviation so the dashboard reads consistently across any asset (BTC's OBV in millions, a low-cap's in thousands, same angle scale). UNIVERSAL ANGLE Slope divided by OBV standard deviation per bar, multiplied by 45. A value of 45 degrees means the slope equals one standard deviation per bar. Makes angle comparable across any asset and timeframe: 30 degrees on BTC means the same relative strength as 30 degrees on SOL. ALERT MODES Slope Flip: fires when selected lookback crosses zero. Negative to positive = accumulation starting (LONG). Positive to negative = distribution starting (SHORT). Triple Alignment: fires when all three slopes agree on direction. Fewer signals, higher conviction. Alert payload is built into the script as JSON; works with any webhook receiver. CREDITS On-Balance Volume: Joseph Granville, Granville's New Key to Stock Market Profits (1963)Indicador Pine Script®por HYPR-runAtualizado 19
Adaptive Trend ChannelAdaptive Trend Channel is designed to find the most reliable short-term and long-term trend channels automatically, instead of forcing the user to work with one arbitrary lookback length. The script scans a broad range of candidate periods, builds a regression-based channel for each one, and then compares them through a multi-factor selection process. The goal is not just to find a channel that looks clean, but one that is statistically solid and structurally meaningful. To do that, the indicator favors channels with strong linearity, efficient trend behavior, sufficient directional strength, good price containment inside the bands, controlled width, and stable quality across nearby lengths. This helps avoid weak or accidental fits and gives priority to channels that are more robust in practice. For best results, it is strongly recommended to use a logarithmic chart and to enable the option "Enable for logarithmic price scale" in the indicator settings. This is especially important on assets with large percentage moves over time, because the channel geometry then reflects percentage-based price movement more accurately. Color is also important and very simple to read: if a very robust channel is found, it is displayed in blue by default. This means the selected channel passed the eligibility filters and qualified as a strong structure. If no channel is robust enough, the script can still display the best available candidate, but it will appear in gray by default. OVERVIEW Adaptive Trend Channel helps identify the best short-term and long-term trend channels without manually testing many different lengths. Instead of relying on fixed settings, it adapts to the market structure by selecting the channels that best balance fit, strength, consistency, and usability. The indicator can display: - the best short-term channel - the best long-term channel - an optional midline - an optional data table with channel diagnostics HOW IT WORKS For each tested lookback period, the script builds a regression-based trend channel and measures its quality. Two selection modes are available: 1. Pearson r This mode focuses mainly on linear fit quality. 2. Robust Composite This mode uses a broader decision framework and combines several factors to favor channels that are not only well fitted, but also more reliable as usable trend structures. In Robust Composite mode, the selection can include: - Pearson correlation - trend efficiency - ADX trend strength - price containment inside the channel - channel width control - local stability across neighboring tested lengths A channel is considered eligible only if it passes the minimum filters defined by the user, such as: - minimum absolute Pearson r - minimum ADX - minimum containment ratio - maximum allowed channel width If at least one eligible channel is found, the strongest one is selected and displayed in blue by default. If none qualifies, the script still displays the best available fallback channel, but in gray by default. WHY THIS APPROACH A fixed-length channel can work well in one market condition and fail badly in another. This script addresses that problem by testing multiple candidate lengths and ranking them with a more complete selection logic. The method is designed to reduce three common issues: - choosing an arbitrary lookback period - overvaluing channels that only look good visually - accepting channels that fit price poorly or are too unstable By combining fit quality, structure, strength, containment, and stability, the indicator aims to produce channels that are more trustworthy and easier to interpret. HOW TO READ IT - The short-term channel helps track the active market structure. - The long-term channel helps frame the broader trend. - Blue by default means a robust eligible channel was found. - Gray by default means the displayed channel is the best available one, but it did not pass the eligibility filters. - The position of price inside the channel helps show whether price is near the upper band, lower band, or midline. FEATURES - Automatic search for the best short-term and long-term channels - Adaptive selection across multiple lookback lengths - Robust eligibility filtering - Blue default color for robust eligible channels - Gray default color for fallback non-eligible channels - Support for linear and logarithmic mode - Optional midline display - Optional table with channel metrics - Two detection methods: Pearson r or Robust Composite TABLE METRICS Depending on your settings, the table can display: - best length - selection metric - stability - trend efficiency - Pearson r - ADX - annualized channel return - annualized channel price return MAIN INPUTS - Show Best Short-Term Channel - Show Best Long-Term Channel - Enable for logarithmic price scale - Display Deviation Multiplier - Best Channel Detection - minimum eligibility filters for Pearson r, ADX, containment, and width - optional table settings NOTES - For best interpretation, use logarithmic mode on a logarithmic chart. - Blue by default means the channel passed the eligibility filters and was considered robust. - Gray by default means the script is showing the best fallback channel, but it is not eligible. - Annualized return metrics are intended for daily, weekly, and monthly timeframes. Adaptive Trend Channel is built for traders who want a more objective, adaptive, and robust way to identify high-quality trend channels.Indicador Pine Script®por Julien_ExeAtualizado 77335
LinReg SlopeChangeThis indicator is a precise trend-following tool that tracks the acceleration (rate of change) in the price's linear regression curve. While a standard Linear Regression (LR) indicator simply shows the direction of the price, this tool focuses on detecting whether a trend is gaining momentum or exhausting by measuring the Slope Delta. Here is a detailed guide explaining the technical structure, parameters, and usage of the indicator: 1. Core Calculation Logic -The indicator processes market movements through a three-stage mathematical filter: -Linear Regression (LR): It calculates the "best-fit" line for prices over a specified period (len). -Slope Percentage (Slope %): It calculates the difference between the current LR value and the previous bar's LR value, expressed as a percentage of the current value. -Slope Change (Slope Delta): This is the heart of the indicator. It calculates the difference between the current slope percentage and the previous bar's slope percentage. Mathematically, this acts as the "acceleration" (second derivative) of the price action. 2. Input Parameters -LR Length : The number of lookback bars used for the regression calculation. Higher values lag more but provide more reliable signals. -Slope Change Threshold (%) : The minimum slope change required to trigger a signal. This can be increased to avoid false signals in noisy (sideways) markets. -Source : The price data used for calculations (Usually set to close). 3. Signals and Visualization The indicator operates on a sequential signal logic, meaning it does not produce consecutive "BUY" or "SELL" signals; it waits for a trend reversal. BUY Signal: Occurs when the momentum of the slope (Slope Delta) breaks above your defined threshold_chg. It is marked by a green triangle on the chart. SELL Signal: Occurs when the slope momentum breaks below the negative threshold. It is marked by a red inverted triangle. Background Color: Highlights the active trend by shading the "BUY" zone green and the "SELL" zone red. 4. Usage Strategies A. Catching Trend Reversals Because this indicator notices weakening in the slope before the price fully turns, it can respond faster than classic Moving Averages (MA). If the slope begins to decrease (negative delta) during an uptrend, it may serve as a leading signal of a potential peak. B. Consolidations and Breakouts When the price is moving sideways, the slope is near zero. Thanks to the Slope Change Threshold parameter, the indicator captures the surge in momentum when price breaks out of stagnation, confirming the start of a new trend. C. Filtering Using this indicator in conjunction with a volume indicator (e.g., RV) or an oscillator (like RSI) will increase the success rate. It is particularly powerful for determining trend direction on higher timeframes (4H, Daily). Note: The threshold_chg (Threshold) parameter should be adjusted according to the volatility of the pair you are trading. For volatile assets like cryptocurrencies, keeping this value slightly higher will reduce "whipsaw" or false signals.Indicador Pine Script®por oberezAtualizado 22
Trend Duration Forecast v1.04 [Far_Q]Based on Trend Duration Forecast . This version includes a few usability improvements and a small label-placement fix. The indicator plots a Hull Moving Average (HMA), tracks the current bullish or bearish trend duration in bars, and estimates the probable trend length from historical completed trend durations. Indicador Pine Script®por gcamptonAtualizado 33106
Z-Score line Daily/Weekly# Z-Score Line Daily/Weekly **A forward-projected linear regression z-score that measures how far current price has deviated from where its statistical trend *expects* it to be — turning regression residuals into a normalized mean-reversion oscillator.** --- ## What It Does Z-Score Line computes a linear regression with a configurable forward offset, then measures the residual distance between current price and that projected regression line, normalized by the standard deviation of non-offset regression residuals. The result is a statistically grounded oscillator where readings beyond ±2σ represent historically rare deviations from the projected trend. A smoothed moving average overlay provides momentum context — rising MA confirms z-score direction, divergences flag potential reversals. The forward offset is the key differentiator: rather than measuring deviation from the *current* best-fit line (which always passes near recent price), it measures deviation from where the trend *was heading*, making it structurally better at identifying overshoot conditions. --- ## Theoretical Foundations - **Linear regression residual analysis** — OLS residuals measure the component of price unexplained by the linear trend; standardizing by residual σ converts this to a z-score with known statistical properties under normality assumptions - **Forward-projected regression (offset parameter)** — Projecting the regression line forward by `offset` bars creates a "where price should be" reference, rather than a retrospective best-fit; deviations from this projection identify trend exhaustion and overshoot - **Z-score normalization** — Dividing residuals by their rolling standard deviation produces a unit-free oscillator where ±1σ, ±2σ, ±3σ levels carry standard probabilistic interpretation (68/95/99.7 under Gaussian assumptions — wider in practice for fat-tailed crypto returns) - **Smoothed z-score as momentum filter** — The SMA of the z-score acts as a second-order trend confirmation, analogous to a signal line on MACD; slope direction separates impulsive moves from mean-reverting ones --- ## Signals **Bullish:** - Z-score crosses above zero → price has moved above its projected regression, trend bias shifting positive - Z-score crosses below lower threshold (−4.7) → extreme negative overshoot, potential mean-reversion long entry - Z-score MA turning green (rising) while z-score is positive → confirmed bullish momentum **Bearish:** - Z-score crosses below zero → price has fallen below its projected regression, trend bias shifting negative - Z-score crosses above upper threshold (+5.1) → extreme positive overshoot, potential mean-reversion short entry or profit-taking - Z-score MA turning red (falling) while z-score is negative → confirmed bearish momentum **Neutral / Caution:** - Z-score near zero with flat MA → price tracking projected regression, no actionable deviation - Z-score and MA diverging (z-score rising, MA falling or vice versa) → signal conflict, reduce conviction --- ## Oscillator Pane Fields | Plot | Description | Range | |------|-------------|-------| | **Z-Score** | Standardized residual from forward-projected linear regression (green = positive, red = negative) | Unbounded (typically ±6) | | **Z-Score MA** | SMA of z-score (green when rising, red when falling) | Same scale as z-score | | **Upper Line** | Static upper extreme threshold | +5.1 (default) | | **Lower Line** | Static lower extreme threshold | −4.7 (default) | | **Zero Line** | Trend-neutral reference | 0 | --- ## Key Inputs | Input | Default | Guidance | |-------|---------|----------| | **Timeframe** | D | Daily is the primary design target. Weekly smooths signals for swing/position trading. Both apply to the regression computation — chart timeframe is independent. | | **Linear Regression Length** | 21 | Lookback for OLS fit. 21 ≈ one trading month. Shorter (10–14) increases sensitivity to recent moves; longer (30–50) captures broader trend structure. Affects both the offset projection and residual σ. | | **Linear Regression Offset** | 30 | Forward projection distance in bars. 30 bars on daily ≈ 1.5 months ahead. This is the core parameter — higher offset creates a more "stale" reference line, amplifying deviation signals. Reduce to 10–15 for faster mean-reversion signals; increase to 40–60 for identifying macro-scale overshoot. | | **Z-Score MA Length** | 13 | SMA smoothing period for the momentum overlay. 13 ≈ half the regression length. Shorter (5–8) tracks z-score more closely; longer (21+) filters noise but lags direction changes. | --- ## Data Sources & request.security() Budget | Symbol | Purpose | Calls | |--------|---------|-------| | Chart symbol (`close`) | All regression, residual, and z-score computations | 0 | **Total request.security() usage: 0 of 40.** The indicator operates entirely on the current chart's close data with no external security calls, making it fully compatible as a companion pane alongside request.security()-heavy indicators. The Timeframe input uses TradingView's built-in `input.timeframe()` resolution override, not `request.security()`. --- ## Alerts | Alert | Trigger | Use Case | |-------|---------|----------| | **Z-Score Crosses Above Zero** | `ta.crossover(zscore, 0)` | Trend bias flips positive — potential long entry or short exit | | **Z-Score Crosses Below Zero** | `ta.crossunder(zscore, 0)` | Trend bias flips negative — potential short entry or long exit | | **Z-Score Crosses Above Upper Line** | `ta.crossover(zscore, 5.1)` | Extreme positive overshoot — mean-reversion short or profit-taking zone | | **Z-Score Crosses Below Lower Line** | `ta.crossunder(zscore, -4.7)` | Extreme negative overshoot — mean-reversion long or capitulation signal | All alerts fire via `alertcondition()` (static presets). Alerts trigger on **bar close only** for the selected timeframe resolution — no intra-bar repainting. --- ## Important Notes - **Anti-repainting:** All computations use `close` (confirmed bar data). The `ta.linreg()` offset parameter projects the regression line forward but does not use future data — it extrapolates the regression slope computed from the trailing `length` bars. No `request.security()` calls, no `barmerge.lookahead_on`, no future data references. - **Offset interpretation:** The offset does *not* look ahead. It computes the regression from the most recent `length` bars, then evaluates where that line would be `offset` bars in the future. The residual measures current price vs. that extrapolated point. This means the z-score is structurally biased: when trends persist, the offset projection undershoots; when trends reverse, it overshoots. This is the intended behavior for mean-reversion detection. - **Asymmetric thresholds:** The default upper (+5.1) and lower (−4.7) thresholds are asymmetric, reflecting empirical BTC behavior where downside deviations tend to be sharper but shorter-lived than upside overextensions. Calibrate these to your asset — use the v2 adaptive mode (percentile-based thresholds) for automatic adjustment. - **Recommended timeframes:** Daily (primary), Weekly (swing). The 21-bar regression on daily captures ~1 month of structure. On 4H, the same 21-bar length captures only 3.5 days — reduce offset proportionally or switch to Weekly resolution via the Timeframe input. - **Asset scope:** Designed for BTC and major crypto pairs. The z-score normalization assumes roughly stationary residual variance — works on any liquid asset with sufficient history (>50 bars minimum for regression warmup). Not calibrated for low-liquidity altcoins where gap behavior distorts regression fits. Indicador Pine Script®por whitekidspaz31
SPAZZ Daily/Weekly# SPAZZ Daily/Weekly (SFI) **A mean-reversion entry filter that combines RSI z-score zero-crossings with Bollinger Band touch-and-reclaim — triggering only when momentum normalization and price envelope reversion agree on the same bar.** --- ## What It Does SPAZZ SFI computes a z-score of RSI(14) by subtracting its 14-period SMA and dividing by its 14-period standard deviation, then gates entries on the z-score crossing zero coinciding with price crossing back inside a Bollinger Band (20-period, 1.76σ default). The dual-gate design filters out standalone BB touches that lack momentum confirmation and standalone RSI recoveries that haven't reached envelope extremes. Signals only fire when both conditions align on the same bar — a conjunction filter that materially reduces false positives relative to either component alone. --- ## Theoretical Foundations - **Bollinger Bands (Bollinger, 1983)** — Price envelope defined as SMA(20) ± kσ. The non-standard default multiplier of 1.76σ (vs. the typical 2.0σ) widens the signal zone, capturing reversion setups before price reaches full 2σ extension — a deliberate sensitivity tradeoff - **RSI z-score normalization** — Raw RSI is bounded and non-stationary across regimes. Z-scoring against its own rolling distribution converts it to a zero-centered, approximately unit-variance series where zero-crossings represent transitions from below-mean to above-mean momentum (and vice versa), independent of the prevailing RSI level - **Conjunction filtering** — Requiring two independent conditions to fire simultaneously on the same bar exploits the low joint probability of co-occurrence under noise. If each condition fires independently with probability *p*, the conjunction fires with probability ≈ *p²* under independence — geometrically reducing false signal rates --- ## Signals **Bullish (BUY):** - RSI z-score crosses above zero (momentum recovering from below-average) **AND** price crosses above the lower Bollinger Band (reclaiming the envelope from below) - Interpretation: price was extended to the downside and is now showing simultaneous mean-reversion in both price level and momentum — a high-probability long entry zone **Bearish (SELL):** - RSI z-score crosses below zero (momentum deteriorating from above-average) **AND** price crosses below the upper Bollinger Band (failing to hold the upper envelope) - Interpretation: price was extended to the upside and is now losing momentum while falling back inside the band — a high-probability short entry or exit zone **No Signal:** - Z-score crosses zero but price is mid-band → momentum shift without envelope extremity - Price touches a band but z-score doesn't cross zero → envelope touch without confirmed momentum reversal --- ## Overlay Fields | Plot | Description | |------|-------------| | **Up Triangle** | Green triangle below bar on BUY signal | | **Down Triangle** | Red triangle above bar on SELL signal | | **BUY Label** | Optional text label at low of signal bar | | **SELL Label** | Optional text label at high of signal bar | No Bollinger Band lines are plotted (overlay remains clean). The BB computation is internal to the signal logic only. --- ## Key Inputs | Input | Default | Guidance | |-------|---------|----------| | **BB Multiplier** | 1.76 | Controls band width. Lower values (1.5–1.7) increase signal frequency by catching shallower pullbacks. Higher values (2.0–2.5) require deeper extension before triggering — fewer but more extreme signals. The 1.76 default sits between standard (2.0) and aggressive (1.5). | | **Show Labels** | On | Toggle BUY/SELL text labels. Disable for cleaner charts when using alerts instead of visual scanning. | | **Timeframe** | D | Selector for Daily or Weekly. **Note:** This input is declared but not wired to `request.security()` in the current version — the indicator runs on the chart's native timeframe regardless of this setting. | --- ## Data Sources & request.security() Budget **Total request.security() usage: 0 of 40.** All computations use the chart's native timeframe and symbol. No external data calls. --- ## Alerts | Alert | Trigger | Frequency | |-------|---------|-----------| | **BUY** | RSI z-score crosses above 0 AND close crosses above lower BB | Once per bar close | | **SELL** | RSI z-score crosses below 0 AND close crosses below upper BB | Once per bar close | Both alerts use `alertcondition()` — static presets configured in TradingView's alert dialog. No dynamic `alert()` calls. --- ## Important Notes - **Anti-repainting:** All computations use `close`, `ta.crossover()`, and `ta.crossunder()` on confirmed bar data. No `request.security()` calls, no lookahead. Signals are fixed once the bar closes. - **Timeframe input is cosmetic:** The `input.timeframe()` selector is present in the UI but not connected to any MTF logic. The indicator always runs on the chart's native timeframe. To analyze Daily signals on a Weekly chart (or vice versa), change the chart timeframe directly. - **BB multiplier sensitivity:** At the default 1.76σ, bands are ~12% tighter than standard 2.0σ Bollinger Bands. This means signals fire more frequently but at less extreme price levels. If you observe excessive false signals, increase toward 2.0–2.2. - **RSI z-score warmup:** The z-score requires 2× RSI_LENGTH bars (28 bars) to stabilize — 14 for the RSI series itself and 14 for its rolling mean and standard deviation. Signals within the first ~30 bars of chart history are unreliable. - **Conjunction is strict:** Because both conditions must co-occur on the exact same bar, signal frequency is low. On daily BTC charts, expect roughly 2–6 signals per month depending on regime. This is by design — it is an entry filter, not a continuous scoring system.Indicador Pine Script®por whitekidspaz20
Z-score filter Daily/Weekly# Z-Score Filter — Daily / Weekly **Identifies statistically extreme price dislocations from a linear regression trend using a standardized residual z-score, firing high-precision mean-reversion entries at historically rare extremes.** --- ## What It Does Fits a linear regression to `close` over a configurable lookback and offset, then standardizes the residual of current price against that trend using a rolling standard deviation — producing a classical z-score of price deviation. Signals fire when the z-score crosses back through extreme upper or lower thresholds (default: ±5.1 / ±4.7), identifying price dislocations far enough into the tail distribution to represent genuine mean-reversion opportunity rather than noise. The offset parameter decouples the regression anchor from the current bar, eliminating the lookahead that plagues most regression-based overlays. --- ## Theoretical Foundations - **Ordinary Least Squares (linear regression):** Minimizes squared residuals to produce a best-fit price trend; `ta.linreg(close, length, offset)` with non-zero offset is non-repainting by design. - **Standardized residuals / z-scores:** Residual normalized by the rolling standard deviation of `close`; values beyond ±3σ are statistically rare under a normal distribution (~0.3% frequency), making the default thresholds (4.7–5.1σ) extremely selective. - **Mean-reversion in financial time series:** Grounded in error-correction dynamics — when price overshoots its equilibrium trend, restoring forces (liquidity, arbitrage, position unwinds) tend to pull it back. High σ thresholds act as a filter for only the most dislocated conditions. - **Signal polarity:** Crossover (z-score rising back through −lower) = **bullish** (price recovering from extreme negative dislocation). Crossunder (z-score falling back through +upper) = **bearish** (price rolling over from extreme positive dislocation). --- ## Signals | Signal | Condition | Interpretation | |---|---|---| | 🟢 **Deep Value (BUY)** | `zscore` crosses **above** `−lower` threshold | Price has been at extreme negative residual and is reverting toward trend — mean-reversion long entry | | 🔴 **Over Value (SELL)** | `zscore` crosses **below** `+upper` threshold | Price has been at extreme positive residual and is rolling back toward trend — mean-reversion short/exit entry | | ⬜ **No Signal** | `zscore` inside threshold band | Price within statistically normal range relative to trend; no actionable dislocation | --- ## Key Inputs | Input | Default | Type | Guidance | |---|---|---|---| | **Timeframe** | `D` | Dropdown (D / W) | `D` for swing entries; `W` for position-sizing filter or macro regime context. MTF security call pulls higher-TF data cleanly. | | **Linear Regression Length** | `21` | Integer | Controls the lookback window for trend fitting and σ estimation. Shorter (10–15) = more responsive, noisier. Longer (34–55) = slower, fewer signals but higher quality. | | **Linear Regression Offset** | `30` | Integer | Shifts the regression anchor back N bars, ensuring the fitted value at bar is based on historical data only — critical for anti-repainting. Do not set to 0. | | **Plot Linear Regression Line** | `true` | Boolean | Toggle the blue regression overlay. Disable to reduce chart clutter when stacking indicators. | | **Upper Threshold** | `5.1` | Float | Bearish trigger level (σ above trend). Increase to 5.5–6.0 on higher-volatility assets (altcoins, meme coins). | | **Lower Threshold** | `4.7` | Float | Bullish trigger level (σ below trend, stored as positive value, applied as negative). Slightly lower than upper to account for the well-documented negative skew in crypto. | **Threshold calibration guidance:** On BTC/ETH at daily resolution, 4.7–5.1σ yields 1–4 signals per year — true tail events. Reduce to 3.0–4.0 for higher-frequency assets or 4H charts with the understanding that signal quality degrades. --- ## Dashboard / Visual Elements | Visual Element | Description | |---|---| | **Blue line (Linear Regression)** | Best-fit OLS trend over `length` bars, anchored `offset` bars back. Toggleable. | | **Green cross + "BUY" label (below bar)** | Deep Value signal — z-score crossover through `−lower` | | **Red cross + "SELL" label (above bar)** | Over Value signal — z-score crossunder through `+upper` | *No dashboard table. This is an overlay-only signal indicator — no separate pane required.* --- ## Data Sources | Source | Ticker / Field | Usage | |---|---|---| | Chart symbol | `close`, `volume` | Primary price series and volume (built-in, no `request.security()` calls) | **`request.security()` budget:** **0 calls.** This indicator uses only the native chart series. The timeframe input switches chart context via the timeframe parameter on `ta.linreg` — note that standard Pine Script indicators do not auto-request the selected TF; for true MTF operation, a companion wrapper using `request.security()` is needed. --- ## Alerts | Alert Name | Trigger | Suggested Use | |---|---|---| | **Deep Value** | `zscore` crosses above `−lower` | Long entry watchlist — confirm with volume or funding rate context before execution | | **Over Value** | `zscore` crosses below `+upper` | Short entry / long exit watchlist — higher false-positive rate in strong trends; use regime filter | Both alerts use `alertcondition()` (static presets). Compatible with TradingView webhook delivery to execution systems. --- ## Important Notes **Anti-repainting:** The non-zero `offset` (default: 30) is the critical anti-repainting mechanism. The regression is evaluated at `bar_index - offset`, meaning it is computed entirely from historical bars at the time it fires. **Do not set offset to 0** — this creates lookahead bias where the regression re-fits to include the current bar, causing historical signals to shift position on replay. The signal shapes (`plotshape`) are plotted on confirmed close data. **Recommended timeframes:** Daily and Weekly. The default thresholds (4.7 / 5.1σ) are calibrated for daily BTC/ETH behavior. On intraday charts, reduce thresholds significantly or the indicator will rarely trigger. Can be used on any timeframe. **Asset scope:** Optimized for crypto majors (BTC, ETH, SOL, XRP). Apply cautiously to high-beta altcoins — the σ distribution has fatter tails, so fixed thresholds will be hit more frequently and signal quality degrades. Consider switching to adaptive percentile-based thresholds (97th/95th percentile of rolling |z|) for non-major assets. **Signal frequency expectation:** At default settings on BTCUSD daily, expect 1–5 signals per year. This is intentional — these are designed as high-conviction tail-event entries, not a frequent signal system. **Trend vs. mean-reversion regime:** This indicator performs best in ranging / oscillating markets. In strong directional trends, "Deep Value" signals may be sequentially triggered as price continues lower — always context-check against a trend/regime classifier before trading mechanically. Indicador Pine Script®por whitekidspaz36
Polynomial Regression Moving Average (PRMA)1. WHAT IS PRMA? PRMA is a non-repainting, smoothed moving average that uses the endpoint of polynomial regression as its core value. It generalizes the classic Linear Regression Moving Average (LSMA) to any polynomial degree — including fractional values — and adds a comprehensive multi-method, multi-iteration smoothing layer on top. In Simple Terms PRMA fits a mathematical curve (polynomial) to recent price history, takes the last point of that curve as the current value, then optionally smooths the result using your choice of 9 different smoothing algorithms — applied up to 10 times in sequence. 2. CORE ARCHITECTURE text ┌─────────────────────────────────────────────────────┐ │ PRMA PIPELINE │ │ │ │ Price Data ──► Polynomial Regression ──► Endpoint │ │ (OLS with degree d) Extraction │ │ │ │ │ ▼ │ │ Raw PRMA Value │ │ │ │ │ ▼ │ │ Smoothing Layer │ │ (Method × Iterations)│ │ │ │ │ ▼ │ │ Final PRMA Output │ │ │ │ │ ▼ │ │ Signal Generation │ │ (Direction Change) │ └─────────────────────────────────────────────────────┘ 3. MATHEMATICAL FOUNDATION 3.1 Polynomial Regression (OLS) For the last n bars, a polynomial of degree d is fitted: text ŷ(x) = β₀ + β₁x + β₂x² + ... + βₐxᵈ The coefficients are solved via the Normal Equation: text β = (XᵀX)⁻¹ · Xᵀ · y Where X is the Vandermonde matrix: text X = | 1 0 0² ... 0ᵈ | | 1 1 1² ... 1ᵈ | | 1 2 2² ... 2ᵈ | | . . . ... . | | 1 n-1 (n-1)² ... (n-1)ᵈ | 3.2 The Weight Kernel (Efficiency Innovation) Instead of solving full regression every bar, a fixed weight kernel is precomputed once: text Kernel K = x_last · (XᵀX)⁻¹ · Xᵀ Where x_last = Then each bar simply computes: text PRMA_raw = Σ K × price for i = 0 to n-1 This is a constant-time weighted sum — extremely efficient. 3.3 Fractional Degree Interpolation For degree = 3.7: text kernel_3 = compute_kernel(degree=3) kernel_4 = compute_kernel(degree=4) final_kernel = 0.3 × kernel_3 + 0.7 × kernel_4 This allows infinitely fine-grained control over responsiveness. 3.4 Smoothing Layer The raw PRMA value passes through a selectable smoothing function, applied iteratively: text smoothed₁ = smooth(raw_PRMA) smoothed₂ = smooth(smoothed₁) smoothed₃ = smooth(smoothed₂) ... smoothedₙ = smooth(smoothedₙ₋₁) Each iteration further reduces noise while adding controlled lag. 4. ALL PARAMETERS EXPLAINED 4.1 Core Parameters Parameter Default Range Description Source close Any price The price data fed into the regression Period 100 ≥ 2 Number of bars in the regression lookback window Degree 4.0 ≥ 1.0 (step 0.1) Polynomial degree — controls curve complexity 4.2 Color Parameters Parameter Default Description Up Green rgb(36,223,23) PRMA line color when rising Down Fuchsia PRMA line color when falling 4.3 Smoothing Parameters Parameter Default Range Description Smoothing Method EMA 10 options Type of smoothing filter applied Smoothing Length 5 ≥ 1 Lookback for the smoothing algorithm Smoothing Iterations 1 1–10 Number of sequential smoothing passes 4.4 Signal Parameters Parameter Default Description Show Signals true Toggle buy/sell labels on chart 5. SMOOTHING METHODS IN DETAIL 5.1 Complete Smoothing Method Comparison Method Formula Concept Lag Smoothness Best For None No smoothing Zero Raw Fastest response, noisy SMA Equal-weight average High Moderate Simple baseline smoothing EMA Exponential decay Medium Good General purpose WMA Linear weight decay Medium Good Recent-data emphasis RMA Wilder's smoothing High Very High Ultra-smooth trending HMA Hull method Low Good Low-lag smoothing DEMA Double EMA Low Good Lag reduction TEMA Triple EMA Very Low Moderate Minimum lag VWMA Volume-weighted mean Medium Good Volume-aware smoothing Gaussian Bell-curve kernel Medium Excellent Natural, artifact-free 5.2 Smoothing Method Formulas text SMA(n) = (P₁ + P₂ + ... + Pₙ) / n EMA(n) = α × P + (1-α) × EMA_prev where α = 2/(n+1) WMA(n) = (n×P₁ + (n-1)×P₂ + ... + 1×Pₙ) / (n×(n+1)/2) RMA(n) = (1/n) × P + (1 - 1/n) × RMA_prev HMA(n) = WMA(√n, 2×WMA(n/2) - WMA(n)) DEMA(n) = 2×EMA(n) - EMA(EMA(n)) TEMA(n) = 3×(EMA - EMA²) + EMA³ VWMA(n) = Σ(P×V) / Σ(V) Gaussian(n) = Σ(P × e^(-0.5×(i/σ)²)) / Σ(e^(-0.5×(i/σ)²)) where σ = n/3 5.3 Multi-Iteration Effects text Iterations: 1 2 3 4+ │ │ │ │ Noise: Low Very Low Minimal Near Zero Lag: Low Moderate Higher Highest Shape: Sharp Rounded Very Round Gaussian-like Iterations Equivalent Behavior 1 Standard single-pass filter 2 Similar to Butterworth 2nd-order 3 Approaching Gaussian response 4+ Ultra-smooth, trend-only extraction 6. SIGNAL LOGIC 6.1 Direction Detection text PRMA Rising → prma > prma → Bullish PRMA Falling → prma < prma → Bearish 6.2 Buy Signal (Long — "L") text Conditions (ALL must be true): ✅ PRMA turns UP (was falling on previous bar, now rising) ✅ Close > PRMA (price confirms above the moving average) ✅ Show Signals ON Displayed as: Green "L" label below the bar 6.3 Sell Signal (Short — "S") text Conditions (ALL must be true): ✅ PRMA turns DOWN (was rising on previous bar, now falling) ✅ Close < PRMA (price confirms below the moving average) ✅ Show Signals ON Displayed as: Fuchsia "S" label above the bar 6.4 Signal Flow Diagram text PRMA Direction │ ┌─────────┴──────────┐ ▼ ▼ Rising Falling │ │ │ Was Falling? │ Was Rising? │ │ │ │ ▼ ▼ ▼ ▼ Yes No Yes No │ └── No Signal │ └── No Signal │ │ ▼ ▼ Close > PRMA? Close < PRMA? │ │ Yes ──► BUY "L" Yes ──► SELL "S" No ──► No Signal No ──► No Signal 7. NON-REPAINTING GUARANTEE Why PRMA Never Repaints Factor Explanation Fixed kernel Weight matrix computed once on first bar, never recalculated Fixed lookback Each bar uses exactly length bars ending at length bars ago No future data Uses source through source — all confirmed Deterministic smoothing All smoothing methods are causal (backward-looking only) One value per bar Once a bar closes, its PRMA value is permanently locked Important Note The indicator uses source check, meaning the PRMA value is plotted with a length-bar delay from the source data. This ensures that ALL input data is from closed, confirmed bars — the ultimate non-repainting guarantee. Repainting vs Non-Repainting Comparison text REPAINTING Polynomial Regression Channel: Bar 100: Draws curve across bars 1-100 Bar 101: REDRAWS curve across bars 2-101 ← ALL previous values change! NON-REPAINTING PRMA: Bar 100: Computes endpoint of regression on bars 1-100 → single fixed value Bar 101: Computes endpoint of regression on bars 2-101 → new single fixed value Bar 100's value NEVER changes ✅ 8. USE CASES 8.1 Trend Following Goal: Identify and ride medium-to-long-term trends Setup: text Period: 150–200 Degree: 1.5–2.5 Smoothing: EMA, Length 10, Iterations 2 Strategy: Go Long when PRMA turns green (rising) + price above PRMA Go Short when PRMA turns fuchsia (falling) + price below PRMA Exit on opposite signal or when price crosses PRMA against position Example: text SELL signal ↓ Price: ──╱╲──╱╲──╱╲──╲╱──╲──╲╱──╲── PRMA: ────────╱──────╲────────╲──── Color: ████████GREEN███FUCHSIA██████ ↑ BUY signal Markets: Stocks, ETFs, Forex (trending pairs like EUR/USD, USD/JPY) Risk Management: Stop loss: Below PRMA line (for longs) or recent swing low Take profit: When opposite signal appears or fixed R:R ratio Position sizing: Based on ATR distance from PRMA 8.2 Swing Trading Goal: Capture medium-term price swings with clean entry/exit signals Setup: text Period: 50–100 Degree: 3.0–4.0 Smoothing: HMA, Length 5, Iterations 1 Strategy: Enter Long on "L" signal when price is above a higher-timeframe support Enter Short on "S" signal when price is below a higher-timeframe resistance Use PRMA direction color as bias filter Example — Multi-Timeframe Approach: text Daily PRMA (Period 100, Degree 2): Rising → BULLISH BIAS 4H PRMA (Period 50, Degree 4): "L" signal appears Action: Enter Long (aligned with daily bias) Markets: Stocks, Crypto (BTC, ETH), Commodities 8.3 Scalping / Day Trading Goal: Quick entries and exits on short timeframes Setup: text Period: 20–50 Degree: 1.0–2.0 Smoothing: TEMA, Length 3, Iterations 1 Strategy: Use on 1m–15m charts Enter on signal in direction of PRMA slope Exit quickly — target 1:1 or 1:1.5 R:R Avoid signals during consolidation (flat PRMA) Example — 5-Minute Chart: text 09:30 ─────────╱── PRMA turns green 09:35 ── "L" signal, price > PRMA → BUY 09:50 ── Target hit, close position 10:15 ──╲──── PRMA turns fuchsia → flat/reverse Markets: Futures (ES, NQ), Forex (major pairs), Crypto 8.4 Mean Reversion Goal: Trade pullbacks to the PRMA line Setup: text Period: 100–150 Degree: 2.0–3.0 Smoothing: Gaussian, Length 8, Iterations 2 Strategy: Identify trend direction via PRMA color Wait for price to pull back TO the PRMA line (touch or cross slightly) Enter in the direction of the PRMA trend when price bounces off PRMA Stop loss: Beyond the PRMA line Example: text Uptrend (PRMA green): Price: ──╱──╱──╲──╱──╱──╲──╱── PRMA: ────╱────╱────╱────╱──── ↑ ↑ Pullback Pullback to PRMA to PRMA = BUY = BUY Markets: Stocks with strong trends, Index ETFs (SPY, QQQ) 8.5 Volatility Regime Detection Goal: Determine if market is trending or ranging Setup: text Period: 100 Degree: 4.0 (high responsiveness) Smoothing: SMA, Length 15, Iterations 3 (ultra-smooth) Strategy: Flat PRMA (minimal direction changes) → Ranging market → Use mean reversion strategies Clearly sloped PRMA (consistent color) → Trending market → Use trend following strategies Frequent color changes → Choppy market → Reduce position size or stay out Example: text Trending Phase: Choppy Phase: Ranging Phase: PRMA: ────╱──╱── PRMA: ╱╲╱╲╱╲╱╲ PRMA: ────────── Color: GREEN GREEN Color: G F G F G F Color: GREEN (flat) Action: TREND FOLLOW Action: STAY OUT Action: MEAN REVERT Markets: All — this is a meta-strategy for selecting other strategies 8.6 Multi-PRMA System Goal: Use multiple PRMA instances for confluence-based trading Setup (3 PRMA instances on same chart): Instance Period Degree Smoothing Role Fast PRMA 30 3.0 TEMA, 3, 1 Entry trigger Medium PRMA 80 2.5 EMA, 5, 1 Trend filter Slow PRMA 200 1.5 SMA, 10, 2 Major trend direction Strategy: text STRONG BUY: ✅ Slow PRMA rising (major uptrend) ✅ Medium PRMA rising (confirmed trend) ✅ Fast PRMA gives "L" signal (entry timing) ✅ Price > all 3 PRMAs STRONG SELL: ✅ Slow PRMA falling (major downtrend) ✅ Medium PRMA falling (confirmed trend) ✅ Fast PRMA gives "S" signal (entry timing) ✅ Price < all 3 PRMAs AVOID: ❌ PRMAs disagree on direction ❌ Price between fast and slow PRMA Markets: All — particularly effective on Daily charts for position trading 8.7 Crossover System with Other Indicators Goal: Combine PRMA with traditional indicators for confirmation PRMA + RSI: text Setup: PRMA (100, 3.0, EMA 5) + RSI(14) Long Entry: ✅ PRMA "L" signal ✅ RSI > 50 (bullish momentum) ✅ RSI not overbought (< 70) Short Entry: ✅ PRMA "S" signal ✅ RSI < 50 (bearish momentum) ✅ RSI not oversold (> 30) PRMA + MACD: text Setup: PRMA (80, 2.5, HMA 5) + MACD(12,26,9) Long: PRMA "L" + MACD histogram positive + MACD above signal line Short: PRMA "S" + MACD histogram negative + MACD below signal line PRMA + Volume: text Setup: PRMA (100, 3.0, VWMA 5) — already volume-aware via VWMA smoothing Long: "L" signal + Volume > 1.5× average volume = HIGH CONVICTION Long: "L" signal + Volume < average = LOW CONVICTION (smaller position) 8.8 Crypto-Specific Use Case Goal: Navigate volatile crypto markets with adaptive smoothing Setup: text Chart: 4H BTC/USDT Period: 60 Degree: 3.5 Smoothing: Gaussian, Length 8, Iterations 2 Strategy: Crypto moves fast → higher degree (3.5) catches reversals quickly Crypto is noisy → Gaussian smoothing + 2 iterations removes whipsaws Only trade signals aligned with Daily PRMA direction Use wider stops (crypto volatility is 3-5× traditional markets) Example — BTC Bull Run: text $40,000 ──────╱── PRMA green, "L" signal → ENTER LONG $45,000 ──╱───── PRMA still green → HOLD $48,000 ──╲───── PRMA turns fuchsia, "S" signal → EXIT $44,000 ──╲───── PRMA still fuchsia → SHORT or FLAT $42,000 ──╱───── PRMA green, "L" → ENTER LONG again 8.9 Portfolio / Asset Allocation Goal: Use PRMA as a filter for risk-on/risk-off decisions Setup: text Asset: SPY (S&P 500 ETF) Period: 200 Degree: 1.5 Smoothing: RMA, Length 20, Iterations 3 Strategy: text Weekly PRMA Rising (Green): → 100% Equities allocation → Overweight growth stocks → Risk-on positioning Weekly PRMA Falling (Fuchsia): → Reduce to 50% Equities → Increase bonds / cash → Risk-off positioning Weekly PRMA Flat / Choppy: → 70% Equities → Diversified allocation → Neutral positioning 8.10 Adaptive Degree Selection Guide Goal: Choose the right degree for current market conditions text Market Condition → Recommended Degree ───────────────────────────────────────────── Strong linear trend → 1.0 - 1.5 Gradual curve/acceleration→ 2.0 - 2.5 Trend with pullbacks → 3.0 - 3.5 Complex / oscillating → 4.0 - 5.0 Very choppy → 1.0 (with heavy smoothing) 9. PARAMETER OPTIMIZATION TABLE Trading Style Timeframe Period Degree Smooth Method Smooth Length Iterations Scalping 1m–5m 20–30 1.0–2.0 TEMA 3 1 Day Trading 5m–15m 30–60 2.0–3.0 HMA 5 1 Swing Trading 1H–4H 50–100 3.0–4.0 EMA 5–8 1–2 Position Trading Daily 100–200 2.0–3.0 Gaussian 8–12 2 Investing Weekly 50–100 1.0–2.0 RMA 10–20 2–3 Crypto Trading 4H 50–80 3.0–4.0 Gaussian 8 2 Forex 1H 60–120 2.0–3.0 DEMA 5 1 Futures 5m–30m 30–60 2.0–3.0 HMA 5 1 Low Noise Any Any 1.5–2.5 SMA 15–20 3–4 Fast Response Any 20–50 4.0–5.0 None – – 10. DEGREE COMPARISON VISUAL text Degree 1.0 (Linear): Price: ╱╲╱──╱╲──╱╲╱╲──╱╲ PRMA: ────────╱────────── Very smooth, slow to turn Signals: ▲ Rare signals Degree 2.0 (Quadratic): Price: ╱╲╱──╱╲──╱╲╱╲──╱╲ PRMA: ──────╱──────╲──── Moderate curvature Signals: ▲ ▼ Balanced signals Degree 3.0 (Cubic): Price: ╱╲╱──╱╲──╱╲╱╲──╱╲ PRMA: ────╱──╱──╲──╲╱─── Catches inflections Signals: ▲ ▲ ▼ ▲ More signals Degree 4.0 (Quartic): Price: ╱╲╱──╱╲──╱╲╱╲──╱╲ PRMA: ──╱╲─╱╲──╲╱╲─╱╲── Very responsive Signals: ▲▼ ▲▼ ▼▲▼ ▲▼ Many signals (may whipsaw) Degree 4.0 + Smoothing (EMA 5, Iter 2): Price: ╱╲╱──╱╲──╱╲╱╲──╱╲ PRMA: ───╱───╱───╲───╲── Responsive but clean Signals: ▲ ▲ ▼ ▼ Filtered, reliable signals ✅ 11. SMOOTHING ITERATIONS VISUAL text Raw PRMA (No Smoothing): ╱╲╱╲╱──╱╲──╲╱╲╱╲──╱╲ Noisy, many direction changes 1 Iteration (EMA 5): ─╱╲╱───╱╲───╲╱╲───╱─ Some noise removed 2 Iterations (EMA 5): ──╱─────╱─────╲────╱─ Much cleaner 3 Iterations (EMA 5): ───╱─────╱──────╲───╱ Very smooth, clear trend 5 Iterations (EMA 5): ────╱──────╱───────╲─ Ultra-smooth, trend only 12. STRENGTHS & LIMITATIONS ✅ Strengths Feature Benefit Non-repainting Reliable for backtesting and live trading — what you see is what you get Fractional degree Unprecedented fine-tuning between integer polynomial degrees 10 smoothing methods Adapt to any market condition or trading style Multi-iteration smoothing Cascaded filtering for noise-free output Precomputed kernel Computationally efficient — fixed weights, simple weighted sum Generalizes LSMA Degree 1 = LSMA; higher degrees capture curves Confirmed signals Price must be on the correct side of PRMA for signal validation Visual clarity Color-coded direction makes trend identification instant ⚠️ Limitations Limitation Mitigation Lag (inherent in all MAs) Use lower period, higher degree, or TEMA/HMA smoothing Overfitting (high degree + short period) Keep degree ≤ period/20 as rule of thumb Whipsaws in ranging markets Increase smoothing iterations or add trend filter No prediction — shows current state, not forecast Combine with leading indicators (RSI, MACD) Runge's phenomenon at extreme degrees Stay below degree 8–10 for practical use Fixed lag offset of length bars This ensures non-repainting — a deliberate trade-off Over-smoothing possible with high iterations Start with 1–2 iterations, increase only if needed 13. QUICK-START RECOMMENDATIONS Beginner Setup (Start Here) text Period: 100 | Degree: 2.0 | Smooth: EMA | Length: 5 | Iterations: 1 → Clean, balanced, works on most markets and timeframes Intermediate Setup text Period: 80 | Degree: 3.0 | Smooth: HMA | Length: 5 | Iterations: 1 → More responsive to curves, low-lag smoothing Advanced Setup text Period: 60 | Degree: 3.5 | Smooth: Gaussian | Length: 8 | Iterations: 2 → Captures complex patterns with natural noise reduction 14. SUMMARY PRMA bridges the gap between simple moving averages and complex curve-fitting analysis. It transforms polynomial regression from a repainting analytical overlay into a practical, non-repainting trading tool with: Fractional polynomial degrees for precision tuning 9 smoothing methods + multi-iteration for adaptive noise reduction Clean directional signals validated by price confirmation Zero repainting guaranteed by fixed kernel architecture Whether you're scalping crypto on a 1-minute chart or managing a portfolio on weekly timeframes, PRMA's configurable parameters can be optimized for your specific trading style and market conditions.Indicador Pine Script®por ZakAlgoTradeAtualizado 86
Market Gravity: Relative Value Engine--- **Relative Value Model (Enhanced)** This indicator calculates a statistically-derived fair value for your asset by modeling its historical relationship with a reference symbol (default: USDT Dominance). It supports three model types — Linear Range, Linear Regression, and Logarithmic Range — and outputs a prediction line, residual bands, Z-Score signals, and a full metrics dashboard. --- **What Does This Indicator Do?** This indicator builds a statistical price model output by comparing your current chart's price to a reference symbol. It calculates what your asset's price *should* be based on the historical relationship between the two symbols, then measures how far the actual price deviates from that prediction. In short: it answers the question — *"Is this asset overvalued or undervalued relative to a correlated market driver?"* --- **How the Three Models Work** **Linear Range** Maps the reference symbol's high/low range to the current chart's high/low range using a simple slope/intercept formula. Best for assets that move in proportion to the reference linearly. **Linear Regression (Correlation)** *(Default)* Uses Pearson correlation, standard deviation, and rolling means to calculate a beta (slope) and alpha (intercept) — essentially a rolling OLS regression. This is the most statistically rigorous method and handles non-proportional relationships better. **Logarithmic Range** Performs the same range mapping as Linear Range but in log space, then exponentiates back. Ideal for assets with exponential price behavior (e.g., crypto over long timeframes). --- **Dashboard Panel — What Each Row Means** **Regime** — Whether price is above (Premium) or below (Discount) the model. Green = overpriced vs model; Red = underpriced. **Diff %** — Percentage deviation of actual price from predicted price. +5% means price is 5% above the model estimate. **Prediction** — The model's estimated fair price for the current bar. Your fair value anchor. **Z-Score** — How many standard deviations price is from the prediction. Above +2 or below -2 is considered statistically extreme. **Z-Score State** — Normal or Extreme based on your threshold setting. Extreme signals a potential mean-reversion setup. **R²** — R-squared, goodness of fit from 0 to 1. ≥0.6 = Strong, 0.35–0.6 = Moderate, below 0.35 = Weak. Only trust the model when quality is at least Moderate. **Model Quality** — Text label derived from R². Use signals only when this reads Moderate or Strong. **MAE** — Mean Absolute Error in price units. Lower = model tracks price more closely. **MAPE %** — Mean Absolute Percentage Error. Lower percentage = more accurate model overall. **Smoothing** — Shows the active moving average type and length applied to the prediction line. --- **Visual Elements on the Chart** - Yellow line — The predicted fair-value price line - Aqua bands — Upper and lower residual bands (predicted ± multiplier × standard deviation). Price outside these bands is statistically stretched. - Green fill — Premium zone, price is above the model - Red fill — Discount zone, price is below the model - LONG label — Price crossed above the prediction line, bullish regime shift - SHORT label — Price crossed below the prediction line, bearish regime shift - Z+ triangle — Z-Score crossed above the extreme threshold, potential reversal warning - Z- triangle — Z-Score crossed below the negative threshold, potential reversal warning --- **Settings Guide** *Data and Model* - Reference Symbol: Default is USDT Dominance. Try DXY, SPX, BTC, or any asset correlated to your chart. - Reference Timeframe: Leave blank to match your chart, or set a higher timeframe for macro-level signals. - Model Type: Start with Linear Regression. Switch to Logarithmic Range for crypto on long-term charts. - Lookback Period: Use 10–20 on lower timeframes (1H, 4H), and 50–100 on daily or weekly charts. *Smoothing* - Smoothing Type: EMA reacts faster, RMA is smoother, None gives the raw model output. - Smoothing Length: Increase to reduce noise, decrease for more responsiveness. *Signals and Risk* - Residual Band Multiplier: Default 1.5. Try 1.0–2.5. Higher = wider bands, fewer signals. - Z-Score Threshold: Default 2.0. Use 1.5 for more frequent signals, 2.5 for rarer and stronger ones. *Visualization* - All colors, band visibility, and panel on/off are fully customizable. Auto theme detects your chart background automatically. --- **Built-in Alerts** Three alert conditions are included: 1. Z-Score Premium Threshold Crossed — price enters extreme overvalued territory above the model. 2. Z-Score Discount Threshold Crossed — price enters extreme undervalued territory below the model. 3. Price Crossed Model — price crosses the prediction line in either direction, possible regime change. To activate, go to Alerts → Create Alert → Condition → select this indicator. --- *This indicator is for educational and analytical purposes only. Not financial advice.*Indicador Pine Script®por hasanaksoy19926433214
LSMA SD | GForgeLSMA SD | GForge LSMA SD is a trend-following oscillator built for swing trading on higher timeframes. It generates rules-based long and exit signals by measuring where price sits within a statistically-defined volatility envelope anchored to a regression-based trend line. Core Calculation The basis line is a Least Squares Moving Average. Unlike a standard moving average which weights past prices, LSMA computes the mathematically optimal straight-line fit across a defined lookback window. This means the basis reflects the actual gradient of a trend — its slope tells you the rate and direction of price movement, not a smoothed echo of where price has been. A short EMA pass is applied to the raw LSMA output as a robustness measure, absorbing single-bar snap artifacts that occur when outlier candles enter or exit the regression window. This is not a smoothing aesthetic — it directly addresses a known fragility in raw LinReg endpoints. The default source is hlc3 — the average of high, low, and close — rather than close alone. This distributes the regression input across the full bar range, reducing sensitivity to end-of-session price mechanics such as stop runs and last-minute order flow that can distort the trend line without reflecting genuine directional movement. A Standard Deviation envelope is then constructed around the LSMA basis at a fixed multiplier. The band width is driven entirely by actual price volatility — it widens during high-volatility periods and tightens during quiet ones. There is no secondary adaptive scaling layer. This is intentional: additional dynamic scaling introduces a second noisy signal on top of the basis movement, which in practice degrades signal quality. The Oscillator The oscillator expresses where price currently sits within the SD bands on a 0–100 scale. A reading of 0 means price is at the lower band. A reading of 100 means price is at the upper band. A reading of 50 means price is sitting directly on the LSMA trend line itself — the neutral zone between the two signal thresholds represents price consolidating around the regression basis. Long signals fire when the oscillator crosses above the long threshold (default 74), meaning price has broken decisively into the upper band zone — a momentum confirmation in the direction of the trend, not a mean-reversion trigger. Exit and short signals fire when the oscillator crosses below the short threshold (default 33). This is a trend-continuation system, not a reversal indicator. Parameters The indicator is intentionally low-parameter. LSMA Length sets the regression window. StdDev Length sets the band width lookback and can differ from the LSMA length. StdDev Multiplier sets the fixed band scale. Endpoint Smoothing controls how aggressively window-edge artifacts are absorbed — setting it to 1 disables it entirely. Fewer parameters means less surface area for curve-fitting to historical data. Default settings are optimised for BTC on the 1D timeframe. Optimize thresholds and lengths for different assets and timeframes before use. Risk Warning This indicator is provided for informational and educational purposes only. Past performance, including any results visible on historical bars, does not guarantee or imply future returns. All trading involves risk. You should not make trading decisions based solely on any single indicator. Always apply independent analysis and appropriate risk management. Developed by GForgeIndicador Pine Script®por GForge1167
HMA + Kalman + LinReg Channel [Pointalgo]HMA + Kalman + Linear Regression Channel HMA + Kalman + LinReg Channel is a volatility-adaptive price channel that blends three smoothing techniques into a single dynamic midline and adjusts its band width based on market conditions (trending vs. sideways). This script is designed for traders who want: A smoother central bias line Volatility-based dynamic bands Context-aware channel width Simple breakout visual signals Core Components This indicator combines three different smoothing methods: Hull Moving Average (HMA) – Reduces lag while maintaining smoothness Kalman Filter – Adaptive filtering to reduce noise Linear Regression (LinReg) – Captures short-term trend direction The three values are averaged to form a composite midline, providing balanced responsiveness and stability. Adaptive Channel Logic The channel width is based on ATR (Average True Range). When the midline moves significantly over a lookback period (relative to ATR), the market is considered Trending When movement remains within a defined ATR zone, the market is considered Sideways Channel behavior: Trending → Multiplier is reduced (tighter bands) Sideways → Full multiplier (wider bands) This creates a dynamic structure that adapts to market conditions automatically. Visual Features: Midline changes color depending on market state Upper and lower bands plotted around the midline Optional shaded channel for better visibility Breakout markers when price crosses outside the channel Breakout Signals: Bullish signal: Close crosses above upper band Bearish signal: Close crosses below lower band These signals are informational only and do not represent financial advice. Inputs: Length Source Standard Multiplier Trend Lookback Trend Threshold (ATR multiple) Kalman R and Q parameters All parameters are user-adjustable. Disclaimer This script is provided for educational and research purposes only. It does not provide financial advice. Users are responsible for their own trading decisions.Indicador Pine Script®por pointalgo62
Rolling Trendline [LuxAlgo]The Rolling Trendline indicator provides a dynamic, self-adjusting trendline that tracks price action using linear regression slope projections and automatically resets when price deviates beyond a specific threshold. 🔶 USAGE The indicator is designed to provide a continuous trend bias without the "lag" often associated with static linear regression lines. It projects a line forward based on a calculated slope and only shifts its trajectory when the market demonstrates a significant change in momentum. The addition of ATR-based volatility zones allows traders to visualize a range of expected price action around the projected trend, providing a buffer that accounts for market volatility at the time of each trend reset. 🔹 Interpreting the Line and Zones Bullish Phase (Green): Indicates an upward-sloping trajectory. The trendline and its surrounding ATR zones will be colored green, suggesting a bullish bias. Bearish Phase (Red): Indicates a downward-sloping trajectory. The trendline and its surrounding ATR zones will be colored red, suggesting a bearish bias. ATR Zones: These shaded areas represent a volatility-adjusted range. As long as price remains within the deviation threshold, the zones follow the trendline's trajectory. Reset Points: Visualized by a small circle and a break in the line, these occur when price moves too far from the projection. At this moment, the indicator re-anchors to the current price and recalculates both the slope and the ATR zone width. 🔶 DETAILS The indicator follows a specific logic flow to maintain its "Rolling" characteristic: 1. Slope Calculation: It calculates the Linear Regression slope over a user-defined lookback period. This slope represents the average rate of change in price. 2. Projection: On every new bar, the indicator projects the next value of the trendline by adding the active slope to the previous trendline value. 3. Deviation Check: The indicator calculates a Standard Deviation threshold. If the distance between the current price and the projected trendline value exceeds this threshold, a reset is triggered. 4. Re-Anchoring: Upon a reset, the trendline "rolls" to the current price and adopts the most recent linear regression slope. Simultaneously, it captures the current ATR to set the width of the new trend zones. 🔶 SETTINGS 🔹 Trend Settings Slope Lookback: The period used to calculate the linear regression slope. Higher values result in a slope that considers more historical data. Deviation Multiplier: Determines how far price can deviate from the trendline before a reset occurs. Slope Divisor: This setting allows you to tame the trajectory of the line. Higher values divide the captured slope, resulting in flatter trendlines. Source: The price data used for all calculations (default is Close). 🔹 ATR Zones ATR Length: The lookback period used for the Average True Range calculation, which determines the width of the volatility bands. ATR Multiplier: Controls the width of the shaded zones around the trendline. 🔹 Visuals Bullish/Bearish Trend Colors: Customizes the colors for the trendline and zones based on the slope direction. Zone Color: Sets the base color for the ATR area fills. Line Width: Adjusts the thickness of the primary rolling trendline. Indicador Pine Script®por LuxAlgo22737