EMA 9/50/200 - Hailstone AnalyticsSlope aware color coding. - Green for upsloping, red for downslopingインジケーターfarid109の投稿2
Joe 9/21 EMA Cloud [Slope Shade + Regime]9/21 ema cloud with slope, Bearish, Neutral, Bullish Indicator, MA crossoversインジケーターjoe487vbの投稿19
AlligatorFlex Reversal Engine AlligatorFlex Reversal Engine detects potential early trend-shift conditions using modified Alligator structure, line slope, volume expansion, and range confirmation. NASDAQ:QQQ AlligatorFlex Reversal Engine is a modified Alligator-style indicator designed to identify potential early trend-shift conditions using slope, volume, and price-range validation. Unlike a traditional Alligator indicator that only plots trend structure, AlligatorFlex adds confirmation filters to highlight moments where the market may be transitioning from one directional state to another. The indicator uses three EMA-based Alligator lines: - Jaw: slower structure line - Teeth: medium structure line - Lips: faster structure line Each line changes color based on its current slope, allowing traders to quickly visualize whether the internal structure is pushing upward or downward. Signal validation includes: - All three Alligator lines must show directional slope. - Current volume must exceed the average volume by a user-defined multiplier. - The recent price range must expand beyond its average range. - Line structure must meet the required alignment condition. A LONG signal appears when the Alligator structure is still positioned in a bearish alignment, but all three lines are rising with strong volume and range expansion. This can suggest a possible bullish reversal or early recovery attempt. A SHORT signal appears when the structure is still positioned in a bullish alignment, but all three lines are falling with strong volume and range expansion. This can suggest a possible bearish reversal or early rejection. This makes the indicator useful for traders looking for possible transition zones, reversal pressure, momentum shifts, and early directional expansion. Best used with: - Higher timeframe trend context - VWAP - Support and resistance - Market structure - Volume analysis - Breakout or reclaim setups AlligatorFlex Reversal Engine helps traders detect potential early market shifts by combining a modified Alligator structure with slope, volume, and range expansion filters. Instead of only showing moving average lines, the indicator evaluates whether the market is showing enough directional pressure to justify a possible transition signal. It highlights moments where: - Alligator lines begin to slope in the same direction - Volume expands above average - Price range expands beyond normal conditions - Structure suggests a possible reversal or directional shift LONG and SHORT labels are plotted directly on the chart when all confirmation layers align. The goal of AlligatorFlex is to help traders spot possible early reversal pressure before a fully developed trend becomes obvious. Jaw Length: Controls the slowest Alligator structure line. Teeth Length: Controls the medium Alligator structure line. Lips Length: Controls the fastest Alligator structure line. Volume Length: Defines the lookback period used to calculate average volume. Range Length: Defines the lookback period used to calculate recent price-range expansion. Slope Threshold: Minimum slope required from each Alligator line before a signal can be considered valid. Volume Multiplier: Requires current volume to be greater than average volume by the selected multiplier. Range Multiplier: Requires the recent price range to expand beyond its average range by the selected multiplier. Limitations: - This is a modified Alligator-style indicator, not the classic Williams Alligator. - Signals are designed for potential early shifts, not confirmed trend continuation. - Volume filters may behave differently across markets with unreliable or synthetic volume. - Range expansion can trigger late signals after a move has already started. - Choppy markets can still produce false signals. - The indicator does not include stop loss, take profit, or position sizing logic. Important: This indicator is not a standalone trading system and does not predict future price movement. It is designed as a visual confirmation tool for identifying potential directional shifts. Signals may fail during choppy, low-liquidity, or range-bound conditions.インジケーターTy_yanseの投稿更新済 99958
Sigma Channel [JOAT]JOAT Sigma Channel Introduction JOAT Sigma Channel is an open-source regression-based channel overlay built to identify the best-fit directional corridor across a search range of candidate windows. It is designed to show whether price is traveling normally inside a fitted corridor, stretching away from it, reclaiming it, or moving into stress territory. The problem it solves is model selection. A fixed-length regression channel can look excellent in one regime and poor in the next. If the market accelerates, slows down, or shifts its dominant drift horizon, a static window becomes less useful. Sigma Channel solves that by searching a range of possible windows and selecting the strongest available fit. That fit becomes the active corridor. Around it the script builds multiple sigma tiers. These tiers create a richer price-state map than a single upper and lower band. The result is a more useful framework for reading acceptance, stretch, reclaim, and exhaustion. Core Concepts 1. Multi-Window OLS Search The script evaluates multiple candidate regression windows and scores them by fit quality. for len = minWindow to maxWindow by stepWindow = f_model(len) 2. Sigma-Tier Envelope Stack The fitted centerline is surrounded by inner, core, outer, and stress layers. 3. Slope and Quality Diagnostics The chosen model exposes both slope and fit quality. 4. Reclaim and Acceptance States The script identifies when price reclaims or accepts back inside the corridor after extension. 5. Stress-State Shading The most extreme statistical layer is visually emphasized. 6. Forward Projection The active model projects forward to keep the corridor useful at the right edge. 7. Residual Awareness Residual behavior helps judge whether the active model remains representative. 8. Gradient Candle Context Bar coloring transitions with the current statistical state. Features Adaptive regression search: scans multiple windows instead of using one fixed length Inner, core, outer, and stress bands: multiple sigma tiers for normal and abnormal travel Slope-aware corridor logic: distinguishes positive and negative drift Reclaim and acceptance events: return-to-channel behavior is identified Stress shading: abnormal statistical extension is highlighted Forward projection: the active corridor extends to the chart edge Gradient candle tinting: bar color reflects the current z-state Dashboard: slope, quality, window, and deviation state are summarized Input Parameters Model Search: Minimum Window Maximum Window Window Step Minimum R-Squared Projection Bars Deviation Envelope: Inner Sigma Core Sigma Outer Sigma Stress Sigma Filter Stack / Visual System: Bias EMA ATR Length Momentum RSI Use EMA Bias Gate Use RSI Gate Use Volume Gate Tint Bars Show Projection Show Dashboard How to Use This Indicator Step 1: Check the active slope and whether the corridor is upward, downward, or balanced. Step 2: Check fit quality before trusting the active statistical path. Step 3: Read whether price is inside the core corridor, at the outer layer, or in stress territory. Step 4: Watch reclaims back into the channel after extension. Step 5: Use the projection to organize the near-future chart space. Indicator Limitations The selected best-fit window can change as the market evolves Linear regression becomes less representative in strongly nonlinear markets Statistical extension does not guarantee immediate reversal The indicator measures deviation from a model, not directional certainty Originality Statement This script is original in the way it combines adaptive regression selection, multi-tier sigma structure, reclaim logic, stress-state shading, and forward projection into one corridor framework. The goal is not just to draw a regression channel. The goal is to keep the active model responsive while preserving statistical context. Disclaimer This indicator is provided for educational and informational purposes only. It is not financial advice. Regression fit and statistical deviation do not predict future price with certainty. Markets can remain extended or break away from the active fit entirely. Best Use Cases Reading whether price is behaving normally inside a fitted directional corridor Identifying statistical stretch and stress states Watching for reclaim behavior after extension Combining statistical deviation with separate structure or liquidity analysis Interpretation Notes The channel should be trusted more when fit quality is stronger and the slope is clear. Core travel is generally more normal than outer-band travel. Stress states are especially useful when they coincide with separate structural or participation warnings. The projection should be read as a continuation of the current best-fit model, not as a forecast guarantee. Publication Notes This script is intended to be published with a clean chart where the corridor, the active slope, and at least one reclaim or extension state are obvious. The example chart should help the viewer understand how the band hierarchy works. Avoid combining it with unrelated overlays in the publication image. -Made with passion by jackofalltrades インジケーターofficialjackofalltradesの投稿18
[ A L P H A X ] Slope Spectrum ProAlphaX Slope Spectrum Pro — Multi-Period Regression Oscillator, Adaptive Signal Line, Momentum Acceleration, Statistical Regime Detection, Classic & Hidden Divergence & Conviction Dashboard AlphaX Slope Spectrum Pro is a professional-grade trend momentum oscillator built on a proprietary multi-period linear regression engine that scans across an entire range of lookback periods simultaneously and synthesizes them into a single adaptive oscillator value per bar. Rather than relying on a fixed-period momentum calculation, Slope Spectrum Pro measures the statistical slope of price across every period in the scan range and combines them using inverse-variance weighting — giving more influence to periods whose regression fits are more consistent, and less to those where price has been noisy. The result is a momentum oscillator that is simultaneously responsive and robust. On top of this engine sits a complete analytical layer: an adaptive signal line that changes speed with market conditions, a momentum acceleration histogram, statistical regime detection bands, classic and hidden divergence detection, regime-filtered entry signals with main chart overlay, and a live 10-row conviction dashboard. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 📸 Visual Overview AlphaX Slope Spectrum Pro in the oscillator pane — gradient-colored slope line with gradient fill, acceleration histogram in the background, adaptive signal line, regime threshold bands, divergence markers, bull/bear signal dots, main chart triangles, and the conviction dashboard ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🔬 The Slope Engine — Multi-Period Regression Core At the foundation of Slope Spectrum Pro is a multi-period linear regression scanner . On every bar, the engine runs a complete set of linear regressions across every period from your configured minimum to maximum, stepping at your chosen interval. With default settings of Min Period 10, Max Period 100, and Step Size 5, this means 19 independent regressions are computed and synthesized per bar. Each regression fits a straight line to the logarithm of price over the lookback window and extracts the slope of that fit — a dimensionless measure of directional momentum at that timescale. Positive slope means upward momentum. Negative slope means downward momentum. Steeper slope means stronger momentum. Inverse-Variance Weighting: When Inverse-Variance Weighting is enabled, each regression period's slope is weighted by the inverse of its residual variance — how consistently price tracked the regression line over that lookback. A period where price followed its regression cleanly gets high weight. A period where price bounced erratically around the fitted line gets low weight. The result is that cleaner, more consistent trend periods contribute more to the final oscillator value than noisy, choppy periods — the oscillator becomes naturally less sensitive to random price fluctuations and more responsive to genuine directional momentum. What the oscillator value means: A value above zero means the weighted regression slope is net positive — more periods are trending upward than downward across the scanned range. A value below zero means the weighted slope is net negative — dominant downward trend momentum. The magnitude reflects how steep the consensus slope is. A large positive value means strong, consistent upward momentum. A value near zero means flat or contested momentum. The oscillator is plotted as a gradient-colored line that transitions dynamically from bear red to bull green based on its rolling 200-bar min/max range — the stronger the current momentum relative to recent history, the brighter the color. A gradient fill between the oscillator line and the zero line reinforces the directional bias visually. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 〰 Adaptive Signal Line The signal line tracks the slope oscillator — but instead of a fixed-period EMA, Slope Spectrum Pro uses an adaptive alpha-based EMA that changes its effective length based on current market conditions. How it adapts: The adaptation measures trend strength as how many standard deviations the current oscillator value is from its recent mean. When the oscillator is far from its mean — a clear, developing trend — the signal line shortens and reacts faster, following the oscillator closely. When the oscillator is near its mean — a ranging or choppy condition — the signal line lengthens, smoothing out minor oscillations and reducing false crossovers. In a strong trend: the signal is tight. Crossovers happen quickly and reflect real momentum shifts. In chop or range: the signal is loose. It takes a more significant oscillator move to produce a crossover, filtering out noise automatically. The current effective signal length is shown live on the dashboard as EMA~N — you can see exactly how tight or loose the signal is at any moment. Adaptive speed can be toggled off for a consistent fixed-length signal. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ⚡ Momentum Acceleration Histogram Behind the oscillator line, a background acceleration histogram plots the rate of change of the slope oscillator — how fast momentum is building or fading right now. Green columns — acceleration is positive. The slope oscillator is increasing. Momentum is building in the bullish direction. Red columns — acceleration is negative. The slope oscillator is decreasing. Momentum is fading or building in the bearish direction. Reading the acceleration alongside the main oscillator gives you a two-layer picture: Oscillator above zero + green acceleration = strengthening bull momentum . The best time to enter or hold long. Oscillator above zero + red acceleration = bull momentum peaking and fading . Consider reducing exposure or preparing to exit. Oscillator below zero + red acceleration = strengthening bear momentum . Best time to hold or enter short. Oscillator below zero + green acceleration = bear momentum fading . Watch for a potential reversal or crossover signal. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 📊 Statistical Regime Detection Slope Spectrum Pro automatically classifies the current market environment into one of three regimes using a rolling statistical framework built from the oscillator's own mean and standard deviation: Bull Regime — the oscillator is above the upper band (mean + N standard deviations). Background tints subtly green. Only bullish signals fire when regime filtering is enabled. Bear Regime — the oscillator is below the lower band (mean − N standard deviations). Background tints subtly red. Only bearish signals fire when regime filtering is enabled. Range Regime — the oscillator sits between the two bands. Background is a very faint neutral gray. No directional regime is confirmed. Regime-filtered signals are suppressed entirely. Thresholds are calculated as oscillator mean ± (standard deviation × sensitivity multiplier) over the configured lookback. Increasing the sensitivity multiplier raises the bar required to enter Bull or Bear regime — only the strongest trend episodes qualify. Lowering it makes transitions more frequent. This system directly controls signal quality when Regime-Filtered Signals is enabled — crossovers opposing the active regime direction are silently blocked before they ever reach the chart. Regime bands on the oscillator — Bull threshold above, Bear threshold below, background tint reflecting the current zone ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ◆ Divergence Engine — Classic and Hidden Slope Spectrum Pro detects four divergence types by comparing confirmed oscillator pivot highs and lows against confirmed price pivot highs and lows. All detections are confirmed on bar close only — no repainting. Classic Divergences — Reversal Signals: Classic Bull Divergence (DIV ▲) — price makes a lower low while the slope oscillator makes a higher low. Selling pressure is weakening even though price is still falling. A reversal upward may be building. Classic Bear Divergence (DIV ▼) — price makes a higher high while the slope oscillator makes a lower high. Buying pressure is weakening even though price is still rising. A reversal downward may be building. Hidden Divergences — Trend Continuation Signals: Hidden Bull Divergence (H ▲) — price makes a higher low while the oscillator makes a lower low. Price held higher ground during the pullback — the uptrend is intact and continuation upward is probable. Hidden Bear Divergence (H ▼) — price makes a lower high while the oscillator makes a higher high. Price failed to rally as high as before even as the oscillator rebounded — the downtrend is intact and continuation downward is probable. Classic divergences warn of potential reversals. Hidden divergences confirm that pullbacks within a trend are likely to resume. Both are marked on the oscillator at the pivot bar with compact DIV or H labels. The divergence pivot lookback is configurable. Hidden divergence can be toggled independently from classic divergence. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🎯 Entry Signals — Oscillator and Main Chart Overlay Crossover signals fire when the slope oscillator crosses above or below the adaptive signal line, confirmed on bar close: Bull Signal (●) — oscillator crossed above signal line. A small green dot appears on the oscillator. Bear Signal (●) — oscillator crossed below signal line. A small red dot appears on the oscillator. Regime filtering: When enabled, bull crossovers during a Bear Regime are blocked. Bear crossovers during a Bull Regime are blocked. Only signals aligned with the current statistical regime are displayed — this single filter eliminates a significant category of false signals. Main chart overlay: When Overlay Candle Color is enabled: A ▲ green triangle appears below the bar on the main chart at every bull signal. A ▼ red triangle appears above the bar on the main chart at every bear signal. Candles on the main chart are colored using the same gradient as the oscillator — chart candles reflect the current slope momentum state at a glance. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 📋 Live Conviction Dashboard A real-time 10-row readout of the oscillator's full internal state, updating on every bar close: SAMPLES — number of regression periods computed per bar based on Min, Max, and Step settings. MODE — INV-VAR WEIGHTED or SIMPLE AVERAGE aggregation. OSC VALUE — live slope oscillator value to six decimal places, green above zero, red below. REGIME — ▲ BULL ZONE, ▼ BEAR ZONE, or — RANGING. Row highlighted in the corresponding color. MOMENTUM — ▲ BUILDING (acceleration positive) or ▼ FADING (acceleration negative). Row highlighted accordingly. SIGNAL — ▲ BULL CROSS / ▼ BEAR CROSS when a crossover fired this bar, or ▲ ABOVE SIG / ▼ BELOW SIG for ongoing position. SIG SPEED — current effective signal length as EMA~N, showing how tight or loose the adaptive signal is in real time. DIVERGENCE — highest-priority active divergence: ▲ BULL DIV, ▼ BEAR DIV, ▲ HIDDEN BULL, ▼ HIDDEN BEAR, or — NONE. Row highlighted when active. CONVICTION — a 0–4 confluence score. Each of the following adds 1 point: regime and oscillator sign agree; regime and acceleration agree; regime and signal side agree; any divergence is active. Score labels — LOW / MIXED (0–1), MODERATE (2), HIGH CONVICTION (3), MAX — ALL ALIGNED (4). OSC (sigma) — the oscillator value expressed as standard deviations from its recent mean. Shows statistically how far momentum has moved from neutral — +2.5s means 2.5 standard deviations into bull territory. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ⚡ Key Features 🔬 Multi-period regression engine — 19 independent regressions per bar (default) synthesized into one adaptive oscillator value ⚖ Inverse-variance weighting — consistent regression periods carry more weight; noisy periods are automatically discounted 〰 Adaptive signal line — effective EMA length speeds up in trends, slows in chop; current length shown live as EMA~N ⚡ Momentum acceleration histogram — rate-of-change of the oscillator, showing whether momentum is building or fading right now 📊 Statistical regime detection — three-zone classification (Bull / Bear / Range) using rolling mean ± standard deviation bands 🔒 Regime-filtered signals — crossovers opposing the current statistical regime are automatically suppressed ◆ Classic divergence — bull and bear reversal divergence between price pivots and oscillator pivots, bar-close confirmed ◆ Hidden divergence — trend continuation signals when price and oscillator diverge in the trend direction 🎯 Main chart overlay — bull/bear triangles on price chart and gradient candle coloring reflecting live slope momentum 🎨 Dynamic gradient oscillator color — live transition from bear to bull based on rolling 200-bar normalization 📋 Live 10-row conviction dashboard — samples, mode, osc value, regime, momentum, signal, signal speed, divergence, conviction score, sigma reading 🏆 4-point conviction scoring — real-time confluence count across regime, acceleration, signal, and divergence alignment 🔔 10 alert conditions — crossovers, classic and hidden divergences, confluence long/short, zero line crosses 🎨 14 user-configurable color inputs — every visual element independently themeable with AlphaX brand defaults ✅ Confirmed on bar close — no repainting on any signal, divergence, or regime transition ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ⚙ Settings Reference Slope Engine Max Period — upper bound of the regression scan range (default: 100) Min Period — lower bound of the scan range (default: 10) Step Size — increment between scanned periods (default: 5). Smaller = more samples, smoother oscillator. Inverse-Variance Weighting — weight each period by its regression consistency (default: on) Source — price input for all regressions (default: close) Adaptive Signal Line Base Signal Length — signal EMA length in neutral conditions (default: 7) Adaptive Speed — toggle adaptive EMA alpha on or off Momentum Acceleration Show Acceleration Histogram — toggle the background column histogram Acceleration Smoothing — EMA smoothing period for acceleration (default: 3) Regime Detection Show Regime Bands — toggle threshold lines and background tinting Regime Lookback — rolling window for mean and standard deviation (default: 200) Regime Sensitivity (σ×) — standard deviation multiplier for thresholds (default: 0.5) Divergence Engine Show Divergences — toggle all divergence detection Divergence Pivot Length — bars on each side to confirm a divergence pivot (default: 5) Show Hidden Divergences — toggle hidden divergence independently Entry Signals Show Crossover Signals — toggle oscillator signal dots Regime-Filtered Signals — suppress signals opposing the current regime Overlay Candle Color — toggle main chart triangles and gradient candle coloring Dashboard Show Dashboard — toggle the dashboard panel Position — Top Right, Top Left, Bottom Right, Bottom Left Theme Bull Primary / Bright / Dim — three shades of the bullish color family Bear Primary / Bright / Dim — three shades of the bearish color family Neutral / Neutral Light — neutral and secondary text colors Accel Bull / Accel Bear — acceleration histogram column colors Divergence Bull / Divergence Bear — classic divergence marker colors Hidden Div Bull / Hidden Div Bear — hidden divergence marker colors ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🚀 How to Trade with AlphaX Slope Spectrum Pro — Step by Step Step 1 — Establish the regime and directional bias Check the REGIME row. ▲ BULL ZONE = the market is in a statistically confirmed trend upward. ▼ BEAR ZONE = confirmed trend downward. — RANGING = no directional edge. Only trade in the direction of the active regime. Check OSC (sigma). A reading above +2s means deep bull territory. Below −2s means deep bear territory. Near zero = flat momentum, no edge. Step 2 — Read acceleration for entry timing In a Bull Regime, wait for the acceleration histogram to turn green (▲ BUILDING on the dashboard). This means the slope oscillator is accelerating — momentum is growing, not just present. The ideal entry timing: Bull Regime + oscillator above zero + acceleration building + oscillator above signal line. Entering while acceleration is red (▼ FADING) in a bull regime risks entering as the current wave is losing steam. Step 3 — Enter on a signal crossover A bull signal dot (oscillator crosses above signal line) with regime filtering enabled is your entry trigger — counter-trend crossovers are already blocked automatically. If Overlay is enabled, the ▲ triangle on the main chart confirms the exact entry bar. The faster the adaptive signal (lower EMA~N), the tighter the crossover timing. In strong trends the signal shortens and reacts more quickly. Step 4 — Upgrade conviction with divergence A bull signal crossover occurring simultaneously with or just after a Classic Bull Divergence (DIV ▲) = high-probability reversal setup. A bull signal crossover during an uptrend following a Hidden Bull Divergence (H ▲) = high-probability trend continuation setup. Check CONVICTION. Score of HIGH CONVICTION (3) or MAX — ALL ALIGNED (4) means multiple independent factors agree. These are the setups to prioritize. Step 5 — Exit when momentum confirms the move is ending Acceleration histogram turning red (▼ FADING) while you are long = first sign the current wave is losing force. Begin monitoring for exit. A bear signal crossover (oscillator crosses below signal line) = exit trigger. A regime shift from Bull Zone to Ranging or Bear Zone = structural move is over. Exit and reset. A Classic Bear Divergence appearing while you are in a long position = warning. Price is printing new highs the oscillator is not confirming. Reduce size or prepare to close. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🔔 Alert Conditions SSP — Bull Crossover — oscillator crossed above the adaptive signal line SSP — Bear Crossover — oscillator crossed below the adaptive signal line SSP — Classic Bull Divergence — price lower low, oscillator higher low confirmed SSP — Classic Bear Divergence — price higher high, oscillator lower high confirmed SSP — Hidden Bull Divergence — price higher low, oscillator lower low (trend continuation) SSP — Hidden Bear Divergence — price lower high, oscillator higher high (trend continuation) SSP — CONFLUENCE LONG — bull crossover occurring with bull or hidden bull divergence simultaneously SSP — CONFLUENCE SHORT — bear crossover occurring with bear or hidden bear divergence simultaneously SSP — Zero Line Cross Up — oscillator crossed above zero (macro bull momentum shift) SSP — Zero Line Cross Down — oscillator crossed below zero (macro bear momentum shift) All alert messages include {{ticker}} and {{interval}} for webhook integration. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 👥 Who This Is For 🧠 Systematic and quantitative traders — the regression engine, inverse-variance weighting, and statistical regime framework provide a mathematically grounded, objective momentum reading with no arbitrary indicator parameters to tune 📈 Trend traders on any instrument and timeframe — the multi-period scan adapts naturally to any market's momentum characteristics without manual recalibration 🔍 Divergence traders — four divergence types covering both reversals and trend continuations, all confirmed on bar close ⚡ Momentum traders — the acceleration histogram adds a layer no standard oscillator provides: not just where momentum is, but whether it is growing or shrinking right now 🎯 Precision entry traders — regime filtering, adaptive signal speed, and the conviction score ensure signals are only shown when multiple independent conditions agree simultaneously 🎨 Traders who customize their charts — 14 fully user-configurable color inputs, compatible with any chart theme 🔔 Alert-driven traders and bot operators — 10 alert conditions including a dedicated confluence alert for maximum-conviction setups ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 📝 Notes All signals are confirmed on bar close only. Slope Spectrum Pro does not repaint. The oscillator value is in units of log-price per bar. The absolute value is very small (typically 0.000001 to 0.001 range) — what matters is the sign, the direction of change, and where it sits relative to regime thresholds and zero. Wider Min–Max scan ranges produce a smoother oscillator capturing broader trend consensus. Narrower ranges are more reactive to short-term changes. Smaller Step Size = more periods sampled per bar = smoother result. Regime Sensitivity is the most impactful setting after the scan range. At 0.5σ (default) the regime bands trigger relatively frequently. At 1.0–1.5σ, only very strong trend episodes qualify — signals become rarer but higher quality. On very low timeframes the nested regression loop may be computationally intensive. Default settings are optimized for timeframes from 1 minute upward on standard instruments. All theme color defaults are designed for dark chart backgrounds. Adjust Theme inputs if using a light background. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ⚠ Disclaimer This indicator is a technical analysis and visualization tool intended for educational and informational purposes only. It does not constitute financial advice or a recommendation to buy or sell any financial instrument. All signals are generated from historical and real-time price data using mathematical calculations — their accuracy or profitability is not guaranteed. Past performance does not guarantee future results. Always conduct your own analysis, use proper risk management, and consult a licensed financial advisor before making any trading decisions. The author accepts no responsibility for any losses incurred from the use of this indicator. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Built for traders who want to know not just where momentum is — but how it got there, how strong it is, and whether it is still building.インジケーターAlphaX-Tradeの投稿33572
Hull MA Trend Zones [AGPro Series]Hull MA Trend Zones 📌 Overview Hull MA Trend Zones is a premium HMA trend overlay built for traders who want a cleaner way to read Hull Moving Average direction, slope quality, and pullback behavior. The script is centered on one clear idea: a strong HMA trend should not only move above or below a moving average; it should show measurable slope, orderly ribbon structure, and controlled pullback behavior around the active HMA path. Instead of presenting a crowded moving average wall, the script uses a focused three-line HMA structure, a subtle pullback band, and concept-native trend zones that are tied directly to the active Hull MA state. ⚙️ How It Works The engine calculates a fast HMA, an anchor HMA, and a slow HMA. The anchor HMA is the main decision line. Its slope is normalized with ATR so the script can judge whether the current Hull MA movement is weak, transitional, or directional. The ribbon structure then checks whether the fast, anchor, and slow HMA lines are aligned. This separates clean trend movement from mixed or unstable movement. Finally, the pullback layer evaluates whether price is extending away from the HMA, testing the HMA zone, holding the HMA zone, rejecting from the HMA zone, or failing the active trend path. 🧭 What The Script Shows - HMA ribbon for clean trend direction. - ATR-based HMA pullback band around the anchor HMA. - Rectangular HMA slope zones created from active directional states. - Confirmed, quality-gated Bull Turn and Bear Turn labels. - Optional Hold and Reject labels for pullback events. - A compact AGPro panel with HMA State, Slope Strength, Pullback Status, and Quality Score. 📊 AGPro Panel The panel is designed for fast scanning without taking over the chart. HMA State shows whether the active read is bullish, bearish, transitional, or neutral. Slope Strength converts the anchor HMA slope into a clear percentage-style reading. Pullback Status explains whether price is extending, testing, holding, rejecting, or failing the HMA trend zone. Quality Score combines slope strength, ribbon alignment, and pullback behavior into a single 0-100 reading. 🎯 What Makes It Different Hull MA Trend Zones is not a generic moving average ribbon, not a ribbon compression map, and not a broad support/resistance tool. Its focus is narrower and more practical: HMA slope, HMA trend-zone behavior, and pullback-to-HMA quality. The rectangular zones are not drawn as generic support or resistance. They are HMA slope zones created from the active trend state and the ATR-sized HMA pullback area. This keeps the script visually useful while avoiding overlap with broader zone, corridor, or compression-style indicators. The default visual design is intentionally restrained. Pullback labels are optional, turn labels require confirmation and a minimum quality score, and old zones are capped so the chart keeps a cleaner premium look on both intraday and higher-timeframe charts. 🔧 Key Settings Fast HMA Length controls the responsive side of the ribbon. Anchor HMA Length controls the main trend path, slope state, pullback band, and panel logic. Slow HMA Length helps identify whether the HMA ribbon is aligned or still transitional. Slope Lookback and Trend Slope Threshold control how selective the HMA state engine is. Zone Width ATR controls the height of the HMA pullback band and slope-zone area. Zone Forward Bars controls how far the active slope zone projects while the same trend state remains valid. Turn Confirmation and Minimum Turn Label Score control how selective the default turn labels are. Label Cooldown Bars, Max Visible Labels, and Label Offset ATR keep chart density suitable for publication-quality screenshots. Panel Location, Panel Theme, Label Font Size, and Panel Font Size are adjustable. ✅ Suggested Use Use Hull MA Trend Zones to study trend continuation, Hull MA pullback quality, HMA slope transitions, and cleaner moving-average trend behavior. It is especially useful when you want an HMA-focused overlay that remains readable on active charts and avoids the clutter of large multi-average systems. The script is designed as a public-free AGPro Series tool with a clean visual identity, a focused HMA concept, and a TradingView-safe publication structure.インジケーターAGProLabsの投稿更新済 22322
Value Migration Bands [AGPro Series]Value Migration Bands Value Migration Bands is a chart-first value migration engine that visualizes where the market's accepted-value region has been drifting over time. Instead of a single moving average, it builds a three-layer band (upper / middle / lower) from a rolling percentile window of typical price, then classifies the current environment as Rising, Flat, or Falling Value using an ATR-normalized slope of the migration midline. The result is a scale-invariant, regime-aware view of how "fair value" migrates across trending and ranging conditions — on crypto, equities, indices, forex and futures alike. 🔷 OVERVIEW Most band-style indicators build their envelope from volatility (Bollinger, Keltner, Donchian). Value Migration Bands is built from acceptance — the region where price has actually spent its time during the lookback, captured as a percentile window of typical price (hlc3). The outer bands mark the edges of that accepted-value region. The midline marks its core. When the whole region drifts upward, the market is accepting higher prices (Rising Value). When it drifts downward, lower prices are being accepted (Falling Value). When it stays level, participants are agreeing on a stable range (Flat Value). This reframes the classic "trend vs range" question in terms of value migration, which is a cleaner structural signal than price slope alone. You see not just where price is going, but where the market's center of gravity is going. 🔶 UNIQUE EDGE Value Migration Bands is distinct from moving-average envelopes, volatility bands and standard channels in several structural ways: • Percentile-based construction — the band is a percentile window of typical price, not a standard deviation or ATR multiple. This directly captures acceptance, not dispersion. • Three-state migration classification — Rising / Flat / Falling Value, driven by an ATR-normalized slope of the midline. The classification is scale-invariant, so the same sensitivity works across BTC, SPX, EURUSD, gold and small-cap equities without retuning. • Regime-aware event markers — Reclaim and Lost markers are filtered by the current regime. Reclaim events are suppressed when the market is in Falling Value; Lost events are suppressed in Rising Value. You only see the events that matter for the active regime. • Strict Value Filter — during extreme compression, the indicator refuses to classify a regime until the band is meaningfully wide relative to ATR. This prevents false regime flags in low-volatility micro-bands. • Distance + cooldown gating — new event markers require a minimum ATR distance from the previous event and a minimum bar spacing, producing a clean chart even on long histories. 🔷 METHODOLOGY Band construction: 1. Typical price (hlc3) is sampled across a configurable lookback window (Band Length). 2. Two percentiles are computed — a lower percentile and an upper percentile, selected by the Band Width Mode (Tight, Balanced, Wide). 3. The midline is the mean of those two percentiles. 4. Light EMA smoothing (adaptive to Band Length) stabilizes the visual without adding structural lag. Regime classification: 1. The midline slope is measured over a rolling window (adaptive to Band Length). 2. The slope is normalized by ATR(14) to make the threshold scale-invariant. 3. A user-controlled Migration Slope Sensitivity divides the normalized slope into Rising / Flat / Falling bands. 4. A 2-bar confirmation layer prevents rapid regime flipping during transitions. Event detection: • Reclaim — price re-enters the band from below after previously being lost. • Lost — price falls out of the band after previously being inside. Both pass a regime gate, an ATR-distance gate and a bar-cooldown gate before being plotted or alerted. 🔶 SIGNALS & ALERTS Four built-in alert conditions: • Value Band Shifted Up — fires when the confirmed regime transitions into Rising Value. • Value Band Shifted Down — fires when the confirmed regime transitions into Falling Value. • Band Reclaimed — fires when price re-enters the accepted-value region (regime-gated). • Band Lost — fires when price falls out of the accepted-value region (regime-gated). Alerts and on-chart markers share identical gating, so the alert log and the chart stay in sync. 🔷 KEY INPUTS Band Engine: • Band Length (default 100) — lookback for the percentile window. • Band Width Mode — Tight, Balanced, Wide. Selects the percentile pair. • Strict Value Filter — requires a minimum band width vs ATR before classifying a regime. • Migration Slope Sensitivity (default 0.5) — threshold between Rising / Flat / Falling. Visuals: • Show Midline, Show Band Fill, Active State Label, Show Reclaim / Lost Markers, Show Info Panel. • Panel Location — six options (Top / Middle / Bottom × Right / Left). • Panel Font Size and Label Font Size — default Normal. Colors: • Rising Value Color, Falling Value Color, Flat Value Color. • Band Fill Opacity. Alerts: • Individual toggles for the four alert conditions above. 🔶 HOW TO USE Structural reading: • Rising Value — treat Reclaim events as continuation confirmations, not counter-trend signals. Expect pullbacks to the midline to be bought. • Falling Value — treat Lost events as continuation confirmations. Expect rallies back to the midline to be sold. • Flat Value — neither regime is active. The band can be used as a range reference; directional events are suppressed because they do not carry regime confirmation. Location reading: • Inside Band — price is trading within the accepted-value region. This is the default state. • Above Band — price is trading above accepted value. In Rising Value, this is constructive; in Falling Value, it is a rally to be evaluated. • Below Band — price is trading below accepted value. In Falling Value, this is the dominant state; in Rising Value, it is a dip. Timeframe guidance: • 1H–4H — best balance for swing use with the default Band Length of 100. • 15m–1H — reduce Band Length to 40–60 for intraday use. • Daily — Band Length 100 gives a structural multi-month migration view. Pairing suggestions: • Higher-timeframe VMB for bias, lower-timeframe execution tools for entry. • Combining with volume-based or anchored-VWAP tools can confirm whether value migration is participation-backed. 🔷 LIMITATIONS & TRANSPARENCY • This is an analytical visualization tool, not a strategy. It does not backtest, does not place orders and does not generate buy / sell recommendations. • Regime classification is based on historical midline slope. Like all rolling measures, it is a lagging read of structure — it describes what has been happening, not what will happen. • During abrupt regime changes, the 2-bar confirmation layer introduces a small delay by design, trading reactivity for stability. • Percentile bands are descriptive of past acceptance. Future acceptance may differ, especially around news events, regime breaks and illiquid sessions. • The Strict Value Filter can force a Flat reading during extreme compression even when a visual direction appears present; this is intentional and protects against false regime flags. 🔶 RISK DISCLOSURE This indicator is published for educational and analytical purposes. It is not financial advice, not a trading recommendation and not a guarantee of performance. Trading and investing involve substantial risk, including the risk of total loss. Past behaviour of any instrument does not guarantee future results. Users are solely responsible for their own decisions and should perform their own due diligence, including independent risk management and position sizing. Published as open-source under the Mozilla Public License 2.0. Feedback, questions and discussion are welcome in the comments. インジケーターAGProLabsの投稿更新済 24
EMA Slope - RSI Oscillator Strategy**EMA Slope Strategy** combines normalized EMA slope momentum with centered RSI to build a multi-entry system for both continuation and reversal setups. It uses a global No Trade Zone (NTZ) to block weak signals, optional divergence modules, RSI-Slope oscillator entries, and entry-type-specific trailing management. **Core Concept - Arctan Slope Normalization:** The strategy measures the change in a long moving average and normalizes it with an arctan model to a centered range that asymptotically approaches +/-50. This keeps slope and centered RSI on comparable scales without hard clipping, making momentum relationships more realistic across different volatility regimes. **Global NTZ Filter:** The NTZ acts as a full entry blocker when enabled. No new entries are allowed while normalized slope is inside the zone, including reversals. This keeps the strategy focused on stronger momentum conditions while still allowing exits inside the NTZ. **Entry Engine:** The script supports NTZ Cross, Acceleration, RSI Divergence, Slope-RSI Divergence, and RSI-Slope Oscillator entries. The oscillator now checks NTZ only on the initial cross, then waits for RSI and slope to keep moving in the same direction within a timeout window. **Trade Management Enhancements:** Same-direction stacking is blocked, but opposite-direction entries can still reverse positions cleanly. Old trailing-stop state is cleared on reversal so only the new side remains active. Standard entries can optionally exit on NTZ re-entry, while divergence and oscillator entries use their own ATR-based trailing logic and grace periods. Default values were tested in BTCUSDT 15min market. ### 🎯 Key Features ✅ **Global No Trade Zone (NTZ)** - Blocks all new entries while slope is inside the neutral zone ✅ **Momentum-Based Entries** - Requires minimum delta to filter weak signals ✅ **Stretch Filter** - Prevents entries when MAs are overextended ✅ **Trend Confirmation** - Optional filter ensures trades align with trend ✅ **Acceleration Entry** - Alternative entry on sudden slope acceleration ✅ **RSI Divergence Entries** - Detect reversals with multi-peak divergence analysis ✅ **Slope-RSI Exhaustion** - Visual warnings and optional filter using normalized momentum comparison ✅ **RSI-Slope Oscillator Entries** - Arms on a valid cross outside NTZ, then confirms with same-direction RSI and slope movement ✅ **Side-Aware Reversals** - Blocks same-direction add-ons while still allowing opposite-side reversals ✅ **RSI-Slope Cross Exit** - Optional close/reverse for any position when RSI and slope cross with same-direction momentum ✅ **Exit Confirmation** - Requires consecutive bars to filter false exit signals ✅ **Entry-Type Trailing Stops** - Separate ATR trails and grace periods for standard, divergence, and oscillator trades ✅ **Immediate Trail Reset On Flip** - Disables the old side's stop state as soon as a reversal is triggered ✅ **Individual Entry Type Controls** - Enable/disable each entry method independently ✅ **Dynamic RSI Coloring** - Visual RSI coloring based on overbought/oversold levels ✅ **Flexible Position Sizing** - Percent of Equity, Fixed Quantity, or Percent of Cash ✅ **Built-in Alerts** - Entry/exit alerts with trade details ### 📊 Technical Calculations **Slope Normalization Formula:** `maDF = longMA - longMA `, then `normalizedSlope = (100 / pi) * atan(maDF / stdev(maDF, lookback))`. This produces a centered oscillator that asymptotically approaches +/-50 and stays comparable with centered RSI. **Acceleration Detection:** Calculates the absolute change in slope between bars, multiplied by smoothing factor and scaled to 0-50 range. Values above threshold (default 38) indicate sudden momentum shifts, visualized as colored dots. **RSI Divergence:** Uses pivot high/low detection on smoothed RSI with configurable sensitivity (lookback = 16 - sensitivity). Compares price pivots against RSI pivots to identify divergences: bullish when price makes lower lows while RSI makes higher lows, bearish when price makes higher highs while RSI makes lower highs. **Slope-RSI Exhaustion:** Compares normalized EMA slope momentum against centered RSI (RSI - 50) on the same scale. When slope is accelerating in one direction but RSI is moving opposite over multiple lookback periods, it indicates trend exhaustion. The gap between slope and RSI must exceed threshold (default 10.0 points) to filter noise. **RSI-Slope Oscillator:** Detects when centered RSI crosses normalized slope outside the NTZ, then waits for both RSI and slope to continue moving in the same direction within a timeout window. This allows reversal-style entries without requiring the slope to stay outside the NTZ after the cross. **Trailing Stop (Blackflag FTS Swingarm):** Uses Wilder's moving average of true range (modified or standard) multiplied by ATR factor. Separate trailing stops for different entry types: Standard entries (NTZ Cross, Acceleration) use standard ATR factor with grace period (default 3 bars). Divergence entries use wider ATR factor (default 6.0) with grace period (default 5 bars). RSI-Slope Oscillator entries use wider ATR factor (default 6.0) with grace period (default 3 bars). Grace periods prevent immediate exits after entry. **Visual Indicators:** Green/Red = trend direction, Gray = NTZ zone, Colored dots = acceleration, Centered RSI line (RSI-50) with dynamic coloring (Red when overbought >20, Green when oversold <-20, Neutral when between -20 and 20), Purple/Lime diamonds = price-RSI divergence, Orange/Yellow triangles = slope-RSI exhaustion warnings, Information table showing Slope, cRSI, Gap, and P/L% ### ⚙️ Quick Setup **Defaults:** MA: 40/160 EMA, NTZ: 8, Delta: 3.2, Stretch: 0.38%, Position: 90% Equity, Exit Confirm: 1 bar, Trail Stop: ATR 15/Factor 5.1, Entry ATR: Period 10/Factor 4.4, RSI: Length 12/Smooth 3/Sensitivity 6, Div ATR: 6.0/Grace 5, Slope-RSI: Lookback 4/Gap 10.0 pts, Osc ATR: 6.0/Grace 3, Standard Grace: 3 bars, Max Crossing Back Period: 5 bars ### 🚀 Entry Methods and Logic **Long Entry Conditions (5 Methods):** 1. **NTZ Cross Entry:** Triggers when normalized slope crosses above +8 threshold. Requires positive delta ≥ minimum threshold (default 3.2), stretch filter allows entry (MAs not overextended), and optional trend confirmation (short MA > long MA) if enabled. This is the primary trend-following method. 2. **Acceleration Entry:** Triggers when acceleration value ≥ threshold (default 34) AND slope is already above NTZ AND delta is sufficient. This captures sudden momentum bursts during strong trends, visualized as colored dots on the indicator. 3. **RSI Divergence Entry:** Triggers when bullish divergence detected - price makes a lower low while RSI makes a higher low over the sensitivity lookback period. Optional Slope-RSI confirmation can be required. This targets reversal opportunities at potential bottoms. 4. **Slope-RSI Divergence Entry:** Triggers when slope is accelerating downward (negative delta, slope below -8) but RSI is rising over lookback periods, with gap between slope and RSI exceeding threshold. This detects bullish exhaustion reversals during downtrends. 5. **RSI-Slope Oscillator Entry:** Triggers when centered RSI crosses normalized slope outside the NTZ, then confirms when both RSI and slope keep moving in the same direction within the allowed timeout window. This targets reversal-style entries while the global NTZ filter still blocks final entries inside the zone. **Short Entry Conditions:** Mirror of long conditions with opposite directional requirements. **Exit Logic by Entry Type:** - **NTZ/Acceleration Entries:** Exit when slope re-enters NTZ, if that option is enabled, or when the standard trailing stop triggers after its grace period. - **Divergence Entries (RSI or Slope-RSI):** Exit only via divergence-specific trailing stop which uses wider ATR factor (default 6.0, adjustable 4-8) and grace period (default 5 bars) before activation. This allows reversal trades time to develop without premature exits. - **RSI-Slope Oscillator Entries:** Exit when the opposite oscillator condition triggers or when the oscillator-specific trailing stop is hit after its grace period. - **RSI-Slope Cross Exit (All Entry Types):** Optional exit/reverse condition that applies to ALL positions. When enabled, exits or reverses position when RSI crosses Slope with both indicators moving in the same direction. Bearish: RSI crosses below Slope AND both heading DOWN (exits/reverses longs). Bullish: RSI crosses above Slope AND both heading UP (exits/reverses shorts). Can be set to reverse position or close only. ### 📖 How-To Guide **Add to Chart:** Indicators → Search "EMA Slope Strategy" → Select **Parameter Configuration Guide:** - **MA Settings**: Two moving averages required. Short MA (default 40) used for stretch filter calculation. Long MA (default 160) used for slope calculation. Ratios: 20/80 (fast, more signals), 40/160 (standard, balanced), 50/200 (slow, fewer but stronger signals). EMA recommended for responsiveness. - **NTZ Threshold**: Controls minimum momentum required for entries. Lower values (5-6) generate more trades but may include weaker signals. Higher values (10-12) generate fewer but stronger momentum signals. Default 8 balances frequency with quality. - **Stretch Filter**: Percentage difference threshold between MAs (default 0.38%). For longs: blocks when long MA > short MA by threshold amount. For shorts: blocks when long MA < short MA by threshold amount. Lower (0.2-0.3%) = more conservative, higher (0.5-1.0%) = more permissive. Set to 0 to disable. - **Delta Threshold**: Minimum change in normalized slope between bars required for entry (default 3.2). Higher values (5-10) require stronger momentum, lower (1-3) are more sensitive. This filters out minor slope fluctuations. - **Exit Confirmation Bars**: Number of consecutive bars exit conditions must persist before closing (default 1). 0 = immediate exit, 1-3 = filters false exit signals during temporary pullbacks, higher = more tolerant. Only applies to NTZ re-entry exits, not trailing stops or RSI-Slope cross exits. - **Trailing Stop**: Blackflag FTS Swingarm method using ATR-based calculation. Trailing Stop ATR Period (default 15) and Factor (default 5.1) control stop distance. Entry ATR Period (default 10) and Factor (default 4.4) control initial stop loss. Separate ATR factors and grace periods for standard entries (default grace 3 bars), divergence entries (default ATR factor 6.0, grace 5 bars), and oscillator entries (default ATR factor 6.0, grace 3 bars). Grace periods prevent immediate exits after entry. - **RSI Divergence Settings**: Sensitivity (6-10, default 6) controls pivot lookback (inverse relationship - higher = more sensitive). Max Peaks to Compare (2-15, default 8) controls how many previous peaks to check. Grace bars (2-5, default 5) delay trailing stop activation. Divergence ATR Factor (4-8, default 6.0) sets stop width for reversal trades. Optional Slope-RSI confirmation can be required for higher quality signals. - **Slope-RSI Settings**: Lookback bars (2-10, default 4) determines how many periods to compare RSI direction against slope. Gap threshold (10.0 pts default) filters weak divergences - minimum distance between EMA Slope and Centered RSI. Set gap to 0 to disable threshold. Can be used as entry method (counter-trend reversals) or as confirmation filter for RSI divergence entries. - **RSI-Slope Oscillator Settings**: ATR Factor (4-8, default 6.0) for trailing stop width. Grace bars (2-5, default 3) before stop activates. Max Crossing Back Period (1-50, default 5) controls timeout window for entry after cross. Allows position reversal when opposite signal triggers. - **RSI-Slope Cross Exit**: Optional exit/reverse condition. When enabled, exits or reverses position when RSI crosses Slope with both moving in same direction. Can be set to reverse position or close only. Applies to all entry types. - **Entry Type Controls**: Individual checkboxes to enable/disable each entry method: NTZ Cross Entries, Acceleration Entry, RSI Divergence Entries, Slope-RSI Divergence Entries, RSI-Slope Oscillator Entries. Allows fine-tuning which entry methods are active. - **RSI Display**: Dynamic RSI coloring option (enabled by default). RSI line changes color based on overbought/oversold levels: Red when cRSI > 20, Green when cRSI < -20, Neutral when between -20 and 20. Customizable colors and line width. **Alerts:** Right-click chart → Add Alert → Select "EMA Slope Strategy" → Choose condition → Configure notifications **Backtest:** Strategy Tester tab → Select strategy → Set date range & capital → Review results **Panel Interpretation:** Green/Red = trend, Gray = NTZ, Dots = acceleration, Blue = Centered RSI, Purple/Lime = price-RSI divergence, Orange/Yellow = slope-RSI exhaustion **Multi-Timeframe:** Higher timeframe for trend, lower for entries. **Market Adjustments:** Crypto: 20/80 MA, NTZ 6-7 | Forex: 40/160, NTZ 8 | Stocks: 50/200, NTZ 10-12 ### 💡 Usage Guidelines **Timeframe Recommendations:** Day Trading: 5m-15m charts work well with faster MA settings (20/80). Swing Trading: 1h-4h charts with standard settings (40/160). Position Trading: 4h-Daily charts with slower settings (50/200). **Entry Method Selection:** Use individual entry type controls to enable/disable methods based on market conditions. NTZ Cross and Acceleration work best in trending markets. RSI Divergence and Slope-RSI Divergence work best at potential reversal points. RSI-Slope Oscillator works best for trend reversals when momentum indicators align. You can enable multiple methods simultaneously or use them individually. **Risk Management:** Always validate signals with price action and support/resistance levels. Use position sizing to limit risk to 1-2% of capital per trade. Exit Confirmation bars (default 6) help filter false exits during normal market volatility. Divergence and oscillator entries use wider stops (ATR factor 6.0) with grace periods (3 bars) because reversals need room to develop. Standard entries use tighter stops (ATR factor 4.7) with shorter grace period (2 bars). RSI-Slope Cross Exit provides additional exit mechanism that can reverse positions when momentum shifts. **Market-Specific Adjustments:** Crypto markets: Use faster MAs (20/80), lower NTZ (6-7), higher delta (4-5). Forex: Standard settings (40/160 MA, NTZ 8, Delta 3.2). Stocks: Slower MAs (50/200), higher NTZ (10-12), lower delta (2-3). Always backtest parameter combinations for your specific market and timeframe before live trading. ### 🔔 Alert System The strategy includes built-in alert conditions for all entry and exit events. Entry alerts include: entry method type (NTZ Cross, Acceleration, RSI Divergence, Slope-RSI Divergence, or RSI-Slope Oscillator), entry price, calculated position size, current normalized slope value, delta value, acceleration value, RSI value, trend confirmation status, Slope-RSI confirmation status (if enabled), and timestamp. Exit alerts include: exit price, original entry price, position size, profit/loss amount and percentage, exit reason (trailing stop, NTZ re-entry, RSI-Slope Cross, or position reverse), current slope and RSI values, confirmation bars count (for NTZ exits), and timestamp. Set up alerts by right-clicking the chart, selecting "Add Alert", choosing the strategy, and selecting which conditions to monitor. ### 📈 Use Cases Day Trading (5m-15m), Swing Trading (1h-4h), Position Trading (4h-Daily), Trend Following, Momentum Trading, Reversal Trading, Range Trading ### ⚠️ Important Disclaimer **THIS IS NOT FINANCIAL ADVICE** This strategy is for educational purposes only. Trading involves substantial risk of loss and is not suitable for all investors. Past performance does not guarantee future results. **Key Points:** No guarantee of profits - you may lose capital. Not professional financial advice - consult a qualified advisor. Trade only with capital you can afford to lose. Backtest results don't guarantee future performance. You are solely responsible for trading decisions and risk management. **By using this strategy, you acknowledge understanding the risks and that you use it at your own risk. Never invest more than you can afford to lose.** **Works on all markets**: Crypto, Forex, Stocks, Commodities, Futures ## Short Description (for Script Header - 200-300 chars) Multi-entry strategy combining arctan-normalized EMA slope with centered RSI. Includes a global NTZ entry filter, NTZ/acceleration/divergence/oscillator signals, side-aware reversals, optional NTZ re-entry exits, and separate trailing stops with grace periods for each entry type. ## Tags (for Publishing) EMA, Moving Average, Slope, Trend Following, Momentum, No Trade Zone, NTZ, Strategy, Trading Strategy, Technical Analysis, Trailing Stop, Position Sizing, Acceleration, Delta, Stretch Filter, Trend Confirmation, RSI, Divergence, Slope-RSI, Exhaustion, RSI-Slope Oscillator, Normalized Comparison, Exit Confirmation, Alerts, Backtesting, Crypto, Forex, Stocks, Futures, Swing Trading, Day Trading, Reversal Trading, Range Trading ## Category **Strategies** → **Trend Following** ストラテジーxvelox_の投稿更新済 44661
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)インジケーターHYPR-runの投稿更新済 23
Linear Regression [Anchored, Band, Signals]OVERVIEW This indicator is a statistical analysis tool that plots linear regression channels alongside dynamic deviation bands. It aims to provide a flexible framework for observing price distribution and momentum quality without making predictive claims. ORIGINALITY This indicator provides advanced options for linear regression-based analysis. 📌 Allows setting the calculation window length based on a fixed bar count or an anchored timeframe. 📌 Draws regression channels in either linear or logarithmic scales. 📌 Identifies historical highest and lowest limits in addition to standard deviation levels. 📌 Displays the non-repainting history of the channel via the "Historical Plots" option. 📌 Calculates Pearson's R (correlation strength) and the Theta (θ) angle (the slope of the channel). 📌 Generates Long and Short signals using two distinct filters and four different channel strategies. 📌 Generates alerts based on signals. 📌 Includes dynamic visualization options. Also displays the precise values of the calculated metrics in the Data Window. WHAT IS LINEAR REGRESSION? Linear regression is an analytical method used to calculate a dependent variable based on independent variables when a cause-and-effect relationship exists between them. In this context, the dependent variable is the price, and the independent variable is the time or bar_index. It aims to model the potential behavior of price action based on this relationship. A regression channel is calculated based on the sample deviation and its multiples. Consequently, it is widely utilized to determine dynamic support and resistance levels. REPAINTING AND THE SOLUTION Repainting can be briefly defined as the alteration of past data values in subsequent bars. Because a standard regression channel is recalculated by shifting the array with every new bar, drawings based purely on line functions inherently repaint. However, this indicator overcomes the repainting issue through its "Historical Plots" feature. This option allows users to dynamically observe the true historical states of the channel levels. The signal mechanics of the indicator are also built strictly upon this non-repainting framework to ensure execution integrity. APPLICATIONS The data provided by this tool can be applied in various observational contexts. When prices stretch significantly toward the outer deviation bands, it highlights mathematical extremes that traders often view as potential mean-reversion zones. Conversely, when the price breaks outside the primary boundaries with a high Theta angle, it signals a statistically significant momentum shift. By utilizing the built-in Pearson's R correlation, observers can quantitatively filter out sideways, low-momentum periods (choppy markets) and focus solely on established directional trends. HOW TO USE Begin by defining the calculation scope in the settings, choosing either a fixed bar count or an anchored timeframe (e.g., Daily, Weekly). Select the appropriate scale (Linear or Logarithmic) to match your chart. Toggle the visibility of the central regression line and deviation bands (Upper, Lower, Optional, Highest, Lowest) as needed. In the "Signals" section, you can select a specific channel strategy and apply minimum thresholds for Pearson's correlation and the Theta angle. Enable the "Bands (Historical Plots)" option to visually audit the past states of the channel without current-bar distortion. MECHANICS At its core, the script utilizes the least-squares method to compute the slope and intercept of the price data. To keep the code modular and efficient, the architecture relies on several user-defined functions (e.g., f_calc_dynamic for historical rolling arrays, f_calc_slope_current for real-time line states, and f_scale_converter for logarithmic adjustments). SIGNALS & EXECUTION LOGIC It is important to note that the signal structure built here is a highly subjective approach to linear regression trading. In this sense, the current methodology is merely a "search for an answer" rather than a definitive solution. It aims to provide users with as flexible and customizable a workspace as possible. Filters: This indicator utilizes a state-machine (dir) to prevent consecutive redundant signals and to manage immediate directional reversals. All entry conditions can be independently gated by two optional mathematical filters: Pearson's R (minimum correlation strength) and Theta (θ) (minimum slope angle). Channel Strategies: The script features 5 distinct channel strategy options with specific entry and exit conditions: 1. None (Pure Trend) • Logic: Ignores channel bands entirely and relies purely on trend momentum. • Entry: Triggered when the mathematical Theta (θ) angle crosses the user-defined threshold • Exit: Triggered when the Theta angle crosses the 0 line, indicating a trend exhaustion or directional shift. 2. Deviation | Break-Out • Logic: Uses the current, dynamically calculated upper and lower standard deviation bands to catch momentum breakouts. • Entry: Triggered when the close price crosses over the upper band (Long) or under the lower band (Short). • Exit (Fakeout Protection): Triggered when the close price crosses back inside the respective entry band. This acts as a trailing stop to cut losses early during false breakouts. 3. Deviation | Mean Reversion • Logic: Uses the current dynamic deviation bands to anticipate a price rebound towards the mean. • Entry: Triggered when the close price crosses over the lower band (Long) or under the upper band (Short). Upon entry, a volatility-adjusted hard stop is dynamically recorded (Entry Band ± 1 Standard Deviation). • Exit: Triggers either as a Take-Profit when the price wick (high for Longs, low for Shorts) hits the central Regression Line, OR as a Stop-Loss if the price breaches the recorded hard stop to prevent infinite drawdowns. 4. Highest & Lowest | Break-Out • Logic: Uses 1-bar delayed ( ) highest and lowest recorded deviation lines to provide stable, non-repainting levels for breakout confirmation. • Entry: Triggered when the close price crosses over the historical highest line (Long) or under the historical lowest line (Short). • Exit (Fakeout Protection): Triggered when the close price crosses back inside the respective entry line. 5. Highest & Lowest | Mean Reversion • Logic: Uses the stable 1-bar delayed highest and lowest lines to trade rebounds. • Entry: Triggered when the close price crosses over the lowest line (Long) or under the highest line (Short). Similar to Option 3, a hard stop is recorded at the exact moment of entry. • Exit: Triggers as a Take-Profit upon a wick touch to the central Regression Line, OR as a Stop-Loss upon breaching the recorded hard stop. DISCLAIMER This indicator is strictly a statistical observation tool, not a predictive financial model. Linear regression mathematically describes past price action; it does not forecast future movements. The mathematical filters and deviation bands provided are subjective interpretations of market data and should only be used as supplementary components within a broader, independent risk management framework.インジケーターdg_factorの投稿11739
LOWESS Reversal & Continuation [UAlgo]LOWESS Reversal & Continuation is a trend sensitive signal indicator built around a local LOWESS style smoothing engine that adapts to both price structure and volatility. Its core objective is to separate meaningful directional shifts from routine market noise by combining smoothed trend estimation, ATR normalized slope analysis, acceleration filtering, and disciplined signal gating. Instead of relying on a conventional moving average crossover model, the script fits a locally weighted regression over a rolling window of recent bars. This produces a smoother and more context aware estimate of price direction, while still reacting fast enough to identify emerging reversals and pullback continuation opportunities. Because the estimate is local and weighted, recent bars have greater influence than distant bars, which helps the line remain relevant to current market conditions. The indicator classifies signals into two practical categories. Reversal signals aim to identify transitions where directional pressure flips from negative to positive, or from positive to negative. Continuation signals aim to identify pullback resumption behavior inside an already established directional regime. This makes the script suitable for traders who want a single tool that can highlight both early trend change candidates and trend following re entry points. To improve robustness, the script also supports optional robust weighting passes. These passes reduce the influence of outlier bars on the LOWESS fit, which is especially useful during abnormal spikes, illiquid conditions, or isolated volatility shocks. In addition, all slope readings are normalized by ATR, allowing the trend filter to scale more consistently across instruments, timeframes, and volatility regimes. From a workflow perspective, the script is designed for clean chart usage. It colors the LOWESS line according to directional bias, draws an adaptive ATR based band around the curve, supports optional signal labels, limits on chart label clutter through an internal object manager, and provides alert conditions for all signal classes. The result is a visually compact but analytically rich framework for tracking trend reversals and continuation setups in real time. 🔹 Features 🔸 LOWESS Style Local Trend Estimation The heart of the script is a locally weighted linear regression model applied over a rolling lookback window. Each bar inside the window receives a distance based weight, meaning bars closer to the current bar have a larger impact on the estimate. This produces a smooth trend line that is more adaptive than many standard moving average techniques and better suited for identifying subtle turning points. 🔸 Optional Robust Regression Passes The indicator can apply additional robust weighting iterations after the initial fit. Residuals are measured relative to the first regression pass, and bars with unusually large residuals receive progressively lower influence in later passes. This reduces distortion from extreme candles and helps the LOWESS curve remain stable during irregular price events. 🔸 ATR Normalized Slope Filter The script does not use raw slope in isolation. Instead, the LOWESS slope is divided by ATR, creating a volatility adjusted slope metric. This makes the directional threshold more portable across markets and timeframes. A slope that may be meaningful on a slow instrument can be very different on a high volatility asset, so ATR normalization creates a more balanced regime filter. 🔸 Reversal Signal Detection Bullish and bearish reversal signals are triggered when the ATR normalized slope crosses the zero line and is confirmed by directional acceleration and price location relative to the LOWESS line. In other words, the script looks for a meaningful change in smoothed directional pressure, not simply a visual bend in the curve. This makes reversal signals more selective and better aligned with structural momentum shifts. 🔸 Continuation Signal Detection Continuation logic is designed to capture trend resumption after a pullback. The script first requires an established directional regime, then checks whether price recently interacted with the LOWESS line, and finally waits for price to reclaim the trend direction with positive confirming acceleration. This helps distinguish genuine continuation behavior from random sideways oscillation around the curve. 🔸 Pullback Validation Window A dedicated pullback lookback parameter ensures that continuation signals only occur when price has interacted with the LOWESS line within a recent number of bars. This prevents stale continuation triggers and keeps the setup focused on recent retracement behavior rather than distant historical interactions. 🔸 Close Confirmation Option Signals can be gated so they only become valid after bar close. This is useful for traders who want to avoid intrabar flicker and premature triggers on live candles. When disabled, the script can respond more aggressively in real time, which may suit faster execution styles. 🔸 Signal Cooldown Logic To reduce repetitive clustering, the indicator tracks the last occurrence of each signal type and imposes a cooldown period before another signal of the same class can be printed. Separate cooldown tracking is maintained for bullish reversals, bearish reversals, bullish continuations, and bearish continuations. 🔸 Adaptive ATR Band An optional ATR based band can be plotted around the LOWESS line. This band provides a visual sense of dynamic range around the smoothed path and can help contextualize whether price is moving in a relatively stretched or balanced position around the trend estimate. 🔸 Directional Visual Coloring The LOWESS curve changes color according to directional bias derived from the ATR normalized slope. This gives the user an immediate visual read on whether the smoothed trend pressure is currently positive, negative, or unavailable due to insufficient historical data. 🔸 Lightweight Label Management When signal labels are enabled, the script uses an internal label book to store and manage plotted objects. Older labels are automatically deleted once the configured maximum is exceeded, helping keep the chart readable and preventing uncontrolled label buildup. 🔸 Full Alert Support Alert conditions are included for all four event classes: Bullish LOWESS Reversal Bearish LOWESS Reversal Bullish LOWESS Continuation Bearish LOWESS Continuation This allows the script to be used not only as a visual analysis tool, but also as an event driven signal framework for scanning and real time notification workflows. 🔹 Calculations 1) Rolling LOWESS Window Construction For every bar, the script loads the most recent length values of the selected source into an internal rolling window. This window becomes the data sample used for the local regression fit. method loadWindow(LowessEngine this, float seriesValue) => for i = 0 to this.length - 1 array.set(this.y, i, seriesValue ) Interpretation: The regression is always fit on the latest rolling block of data. The rightmost point in the window corresponds to the current estimation point. This makes the smoothing local rather than global. 2) Distance Based LOWESS Weights The script uses a tricube kernel to assign weights based on each point’s distance from the current bar inside the regression window. Bars nearer to the most recent observation receive a larger weight, while distant bars contribute less. method buildDistanceWeights(LowessEngine this, int spanBars) => int x0 = this.length - 1 float bandwidth = math.max(spanBars, 1) for i = 0 to this.length - 1 float u = math.abs(i - x0) / bandwidth float w = u < 1 ? math.pow(1 - math.pow(u, 3), 3) : 0.0 array.set(this.baseW, i, w) Interpretation of the conditions: x0 is the current evaluation point inside the rolling window. u is normalized distance from each historical point to the current point. The tricube weight decays smoothly as distance increases. Bars outside the effective span receive zero weight. This is what gives the LOWESS fit its local character and helps it stay focused on recent structure. 3) Weighted Local Linear Regression After weights are built, the script solves a weighted linear regression over the local window. The output is a local intercept and local slope. The final LOWESS estimate is the fitted value at the most recent point in the sample. method solveWeightedLinear(LowessEngine this, array weights) => float s0 = 0.0 float s1 = 0.0 float s2 = 0.0 float t0 = 0.0 float t1 = 0.0 for i = 0 to this.length - 1 float w = array.get(weights, i) float x = array.get(this.x, i) float y = array.get(this.y, i) s0 += w s1 += w * x s2 += w * x * x t0 += w * y t1 += w * x * y float den = s0 * s2 - s1 * s1 if s0 <= 1e-10 or math.abs(den) <= 1e-10 this.slope := 0.0 this.intercept := array.get(this.y, this.length - 1) else this.slope := (s0 * t1 - s1 * t0) / den this.intercept := (t0 - this.slope * s1) / s0 float x0 = this.length - 1 this.yhat := this.intercept + this.slope * x0 Interpretation: this.slope measures the local directional gradient of the LOWESS fit. this.yhat is the current LOWESS value plotted on the chart. If the weighted regression becomes numerically unstable, the script falls back to a flat slope and uses the latest source value as intercept. 4) Robust Reweighting Passes To reduce the impact of outliers, the script can run additional robust passes after the initial fit. It first calculates the absolute residual of each point relative to the fitted line, then computes a median based scale estimate, and finally applies a bisquare style robust weighting function. method updateRobustWeights(LowessEngine this) => for i = 0 to this.length - 1 float xi = array.get(this.x, i) float yi = array.get(this.y, i) float fit = this.intercept + this.slope * xi array.set(this.residualAbs, i, math.abs(yi - fit)) float med = this.residualAbs.median() float scale = med * 6.0 if na(scale) or scale <= 1e-10 for i = 0 to this.length - 1 array.set(this.robustW, i, 1.0) else for i = 0 to this.length - 1 float u = array.get(this.residualAbs, i) / scale float rw = u < 1 ? math.pow(1 - math.pow(u, 2), 2) : 0.0 array.set(this.robustW, i, rw) Interpretation: Large residual bars are treated as less trustworthy observations. The median residual acts as a robust scale anchor. Higher residuals receive smaller robust weights in subsequent fits. This improves stability during abnormal spikes and irregular candles. 5) ATR Normalized Slope and Acceleration Once the LOWESS fit is complete, the script converts raw slope into a volatility aware slope by dividing it by ATR. It also computes a first-difference style acceleration term to measure whether directional pressure is strengthening or weakening. float slopeAtr = not na(slope) and atr > 0 ? slope / atr : na float accelAtr = slopeAtr - nz(slopeAtr ) Interpretation: slopeAtr expresses trend slope in ATR units. accelAtr measures change in normalized slope from one bar to the next. Positive acceleration supports bullish developments. Negative acceleration supports bearish developments. This combination helps the script distinguish a genuine regime shift from a weak or decaying slope condition. 6) Directional Regime Classification The script uses a user defined ATR normalized threshold to determine whether the current smoothed state qualifies as a bullish or bearish directional regime. bool upRegime = not na(slopeAtr) and slopeAtr > slopeThreshold bool downRegime = not na(slopeAtr) and slopeAtr < -slopeThreshold Interpretation: A positive but very small slope is not automatically treated as a valid uptrend. A negative but very small slope is not automatically treated as a valid downtrend. The threshold acts as a noise filter that requires the trend estimate to have enough magnitude before continuation logic becomes eligible. 7) Pullback Detection Relative to LOWESS Continuation signals depend on recent interaction with the LOWESS line. The script checks how many bars have passed since price moved through the LOWESS curve in the opposite direction of the active regime. int bullPbBars = int(nz(ta.barssince(low < lowess), 100000)) int bearPbBars = int(nz(ta.barssince(high > lowess), 100000)) bool bullPullbackRecent = bullPbBars <= pullbackLookback bool bearPullbackRecent = bearPbBars <= pullbackLookback Interpretation: In a bullish regime, price must have recently dipped below the LOWESS line to qualify as a pullback. In a bearish regime, price must have recently pushed above the LOWESS line to qualify as a pullback. The pullbackLookback parameter controls how recent that interaction must be. 8) Reversal Signal Logic Bullish and bearish reversal signals are built from zero line slope crossings, directional acceleration, and price confirmation relative to the LOWESS curve. bool slopeCrossUp = ta.crossover(slopeAtr, 0) bool slopeCrossDown = ta.crossunder(slopeAtr, 0) bool bullRevRaw = enoughBars and slopeCrossUp and accelAtr > 0 and close > lowess bool bearRevRaw = enoughBars and slopeCrossDown and accelAtr < 0 and close < lowess Interpretation of the bullish reversal conditions: slopeCrossUp means the normalized LOWESS slope has crossed from negative to positive. accelAtr > 0 means the slope is improving, not merely touching zero. close > lowess confirms that price is positioned above the smoothed trend estimate. Interpretation of the bearish reversal conditions: slopeCrossDown means the normalized LOWESS slope has crossed from positive to negative. accelAtr < 0 confirms weakening trend pressure. close < lowess confirms price is positioned below the LOWESS line. This makes reversal signals more selective than a simple moving average crossover style event. 9) Continuation Signal Logic Continuation signals are only allowed when a directional regime already exists, a recent pullback has occurred, price crosses back through the LOWESS line in trend direction, and acceleration confirms that the move is regaining strength. bool priceCrossUp = ta.crossover(close, lowess) bool priceCrossDown = ta.crossunder(close, lowess) bool bullContRaw = enoughBars and upRegime and bullPullbackRecent and priceCrossUp and accelAtr > 0 and not bullRevRaw bool bearContRaw = enoughBars and downRegime and bearPullbackRecent and priceCrossDown and accelAtr < 0 and not bearRevRaw Interpretation of the bullish continuation conditions: The LOWESS slope must already define an uptrend regime. Price must have recently pulled back below the LOWESS line. Price must cross back above the LOWESS line. Acceleration must be positive. A reversal signal takes priority, so continuation does not print if the same bar qualifies as a bullish reversal. Interpretation of the bearish continuation conditions is the exact inverse. 10) Close Confirmation and Cooldown Control The final signal is gated by an optional bar close confirmation and a per-signal cooldown filter. bool gate = confirmClose ? barstate.isconfirmed : true bool bullRev = gate and bullRevRaw and canBullRev(signalState, cooldownBars) bool bearRev = gate and bearRevRaw and canBearRev(signalState, cooldownBars) bool bullCont = gate and bullContRaw and canBullCont(signalState, cooldownBars) bool bearCont = gate and bearContRaw and canBearCont(signalState, cooldownBars) Interpretation: When close confirmation is enabled, signals only become valid after the candle is closed. Cooldown logic prevents repeated printing of the same signal class within a short number of bars. This reduces visual clutter and avoids excessive re-triggering during choppy conditions. 11) Adaptive Band Construction The script can draw an ATR-based envelope around the LOWESS line to provide volatility context. float upperBand = showBand and not na(lowess) ? lowess + atr * bandAtrMult : na float lowerBand = showBand and not na(lowess) ? lowess - atr * bandAtrMult : na Interpretation: The band expands and contracts with ATR. This creates a dynamic visual frame around the LOWESS estimate. It is not a signal by itself, but it helps contextualize the distance between current price and the smoothed trend path. 12) Visual Output and Alerts The LOWESS line changes color according to slope direction, optional labels mark reversal and continuation events, and alert conditions are available for all four signal types. alertcondition(bullRev, "Bullish LOWESS Reversal", "Bullish LOWESS reversal on {{ticker}}") alertcondition(bearRev, "Bearish LOWESS Reversal", "Bearish LOWESS reversal on {{ticker}}") alertcondition(bullCont, "Bullish LOWESS Continuation", "Bullish LOWESS continuation on {{ticker}}") alertcondition(bearCont, "Bearish LOWESS Continuation", "Bearish LOWESS continuation on {{ticker}}") In practical terms, this means the indicator can serve both as a visual discretionary analysis tool and as an alert driven framework for identifying smoothed trend reversals and pullback continuation opportunities with a volatility aware filter structure.インジケーターUAlgoの投稿127
Multi Cycles Slope-Fit System MLMulti Cycles Predictive System : A Slope-Adaptive Ensemble Executive Summary: The MCPS-Slope (Multi Cycles Slope-Fit System) represents a paradigm shift from static technical analysis to adaptive, probabilistic market modeling. Unlike traditional indicators that rely on a single algorithm with fixed settings, this system deploys a "Mixture of Experts" (MoE) ensemble comprising 13 distinct cycle and trend algorithms. Using a Gradient-Based Memory (GBM) learning engine, the system dynamically solves the "Cycle Mode" problem by real-time weighting. It aggressively curve-fits the Slope of component cycles to the Slope of the price action, rewarding algorithms that successfully predict direction while suppressing those that fail. This is a non-repainting, adaptive oscillator designed to identify market regimes, pinpoint high-probability reversals via OB/OS logic, and visualize the aggregate consensus of advanced signal processing mathematics. 1. The Core Philosophy: Why "Slope" Matters: In technical analysis, most traders focus on Levels (Price is above X) or Values (RSI is at 70). However, the primary driver of price action is Momentum, which is mathematically defined as the Rate of Change, or the Slope. This script introduces a novel approach: Slope Fitting. Instead of asking "Is the cycle high or low?", this system asks: "Is the trajectory (Slope) of this cycle matching the trajectory of the price?" The Dual-Functionality of the Normalized Oscillator The final output is a normalized oscillator bounded between -1.0 and +1.0. This structure serves two critical functions simultaneously: Directional Bias (The Slope): When the Combined Cycle line is rising (Positive Slope), the aggregate consensus of the 13 algorithms suggests bullish momentum. When falling (Negative Slope), it suggests bearish momentum. The script measures how well these slopes correlate with price action over a rolling lookback window to assign confidence weights. Overbought / Oversold (OB/OS) Identification: Because the output is mathematically clipped and normalized: Approaching +1.0 (Overbought): Indicates that the top-weighted algorithms have reached their theoretical maximum amplitude. This is a statistical extreme, often preceding a mean reversion or trend exhaustion. Approaching -1.0 (Oversold): Indicates the aggregate cycle has reached maximum bearish extension, signaling a potential accumulation zone. Zero Line (0.0): The equilibrium point. A cross of the Zero Line is the most traditional signal of a trend shift. 2. The "Mixture of Experts" (MoE) Architecture: Markets are dynamic. Sometimes they trend (Trend Following works), sometimes they chop (Mean Reversion works), and sometimes they cycle cleanly (Signal Processing works). No single indicator works in all regimes. This system solves that problem by running 13 Algorithms simultaneously and voting on the outcome. The 13 "Experts" Inside the Code: All algorithms have been engineered to be Non-Repainting. Ehlers Bandpass Filter: Extracts cycle components within a specific frequency bandwidth. Schaff Trend Cycle: A double-smoothed stochastic of the MACD, excellent for cycle turning points. Fisher Transform: Normalizes prices into a Gaussian distribution to pinpoint turning points. Zero-Lag EMA (ZLEMA): Reduces lag to track price changes faster than standard MAs. Coppock Curve: A momentum indicator originally designed for long-term market bottoms. Detrended Price Oscillator (DPO): Removes trend to isolate short-term cycles. MESA Adaptive (Sine Wave): Uses Phase accumulation to detect cycle turns. Goertzel Algorithm: Uses Digital Signal Processing (DSP) to detect the magnitude of specific frequencies. Hilbert Transform: Measures the instantaneous position of the cycle. Autocorrelation: measures the correlation of the current price series with a lagged version of itself. SSA (Simplified): Singular Spectrum Analysis approximation (Lag-compensated, non-repainting). Wavelet (Simplified): Decomposes price into approximation and detail coefficients. EMD (Simplified): Empirical Mode Decomposition approximation using envelope theory. 3. The Adaptive "GBM" Learning Engine This is the "Machine Learning" component of the script. It does not use pre-trained weights; it learns live on your chart. How it works: Fitting Window: On every bar, the system looks back 20 days (configurable). Slope Correlation: It calculates the correlation between the Slope of each of the 13 algorithms and the Slope of the Price. Directional Bonus: It checks if the algorithm is pointing in the same direction as the price. Weight Optimization: Algorithms that match the price direction and correlation receive a higher "Fit Score." Algorithms that diverge from price action are penalized. A "Softmax" style temperature function and memory decay allow the weights to shift smoothly but aggressively. The Result: If the market enters a clean sine-wave cycle, the Ehlers and Goertzel weights will spike. If the market explodes into a linear trend, ZLEMA and Schaff will take over, suppressing the cycle indicators that would otherwise call for a premature top. 4. How to Read the Interface: The visual interface is designed for maximum information density without clutter. The Dashboard (Bottom Left - GBM Stats) Combined Fit: A percentage score (0-100%). High values (>70%) mean the system is "Locked In" and tracking price accurately. Low values suggest market chaos/noise. Entropy: A measure of disorder. High entropy means the algorithms disagree (Neutral/Chop). Low entropy means the algorithms are unanimous (Strong Trend). Top 1 / Top 3 Weight: Shows how concentrated the decision is. If Top 1 Weight is 50%, one algorithm is dominating the decision. The Matrix (Bottom Right - Weight Table) This table lifts the hood on the engine. Fit Score: How well this specific algo is performing right now. Corr/Dir: Raw correlation and Direction Match stats. Weight: The actual percentage influence this algorithm has on the final line. Cycle: The current value of that specific algorithm. Regime: Identifies if the consensus is Bullish, Bearish, or Neutral. The Chart Overlay The Line: The Gradient-Colored line is the Weighted Ensemble Prediction. Green: Bullish Slope. Red: Bearish Slope. Triangles: Zero-Cross signals (Bullish/Bearish). "STRONG" Labels: Appears when the cycle sustains a value above +0.5 or below -0.5, indicating strong momentum. Background Color: Changes subtly to reflect the aggregate Regime (Strong Up, Bullish, Neutral, Bearish, Strong Down). 5. Trading Strategies: A. The Slope Reversal (OB/OS Fade) Concept: Catching tops and bottoms using the -1/+1 normalization. Signal: Wait for the Combined Cycle to reach extreme values (>0.8 or <-0.8). Trigger: The entry is taken not when it hits the level, but when the Slope flips. Short: Cycle hits +0.9, color turns from Green to Red (Slope becomes negative). Long: Cycle hits -0.9, color turns from Red to Green (Slope becomes positive). B. The Zero-Line Trend Join Concept: Joining an established trend after a correction. Signal: Price is trending, but the Cycle pulls back to the Zero line. Trigger: A "Triangle" signal appears as the cycle crosses Zero in the direction of the higher timeframe trend. C. Divergence Analysis Concept: Using the "Fit Score" to identify weak moves. Signal: Price makes a Higher High, but the Combined Cycle makes a Lower High. Confirmation: Check the GBM Stats table. If "Combined Fit" is dropping while price is rising, the trend is decoupling from the cycle logic. This is a high-probability reversal warning. 6. Technical Configuration: Fitting Window (Default: 20): The number of bars the ML engine looks back to judge algorithm performance. Lower (10-15) for scalping/quick adaptation. Higher (30-50) for swing trading and stability. GBM Learning Rate (Default: 0.25): Controls how fast weights change. High (>0.3): The system reacts instantly to new behaviors but may be "jumpy." Low (<0.15): The system is very smooth but may lag in regime changes. Max Single Weight (Default: 0.55): Prevents one single algorithm from completely hijacking the system, ensuring an ensemble effect remains. Slope Lookback: The period over which the slope (velocity) is calculated. 7. Disclaimer & Notes: Repainting: This indicator utilizes closed bar data for calculations and employs non-repainting approximations of SSA, EMD, and Wavelets. It does not repaint historical signals. Calculations: The "ML" label refers to the adaptive weighting algorithm (Gradient-based optimization), not a neural network black box. Risk: No indicator guarantees future performance. The "Fit Score" is a backward-looking metric of recent performance; market regimes can shift instantly. Always use proper risk management. Author's Note The MCPS-Slope was built to solve the frustration of "indicator shopping." Instead of switching between an RSI, a MACD, and a Stochastic depending on the day, this system mathematically determines which one is working best right now and presents you with a single, synthesized data stream. If you find this tool useful, please leave a Boost and a Comment below! インジケーターjaydesaiguの投稿60
EMA Percent Angle & Slope VisualizerEMA Percent Angle & Slope Visualizer is a powerful trend-strength tool that measures the true geometric slope of an EMA using percent-normalized angle calculations. Unlike raw angle or ATR-based angle methods, this indicator uses the formula: angle = atan( (EMA_t - EMA_(t-1)) / EMA_(t-1) ) * (180 / pi) This gives you a universal slope measurement that works across stocks, indices, currencies, and crypto — regardless of price scale. 🔍 Features Percent-normalized EMA angle for accurate trend strength Auto-detected slope segments Dynamic EMA color 🟢 Bullish slope 🔴 Bearish slope ⚪ Neutral (angle below threshold) Dashed slope lines drawn only during valid slope runs Angle label displayed at slope end Works on any timeframe Designed for momentum traders, trend followers, breakout traders, and algo developers 📌 Why Percent-Normalized Angle? Raw price angle is meaningless because angles depend on chart scaling. Percent-normalized angle gives a true slope, equal across all instruments. ✔ Tip Slopes above +0.15° and below –0.15° represent strong trend phases for Nifty. Adjust threshold for your timeframe according to your scriptインジケーターRamesh_Gの投稿1190
Slope Rank ReversalThis tool is designed to solve the fundamental problem of "buying low and selling high" by providing objective entry/exit signals based on momentum extremes and inflection points. The System employs three core components: Trend Detection (PSAR): The Parabolic SAR is used as a filter to confirm that a trend reversal or transition is currently underway, isolating actionable trade setups. Dynamic Momentum Ranking: The indicator continuously measures the slope of the price action. This slope is then ranked against historical data to objectively identify when an asset is in an extreme state (overbought or oversold). Signal Generation (Inflection Points): Oversold/Buy: A 🟢 Green X is generated only when the slope ranking indicates the market is steeply negative (oversold), and the slope value begins to tick upwards (the inflection point), signaling potential mean reversion. Overbought/Sell: A 🔴 Red X is generated only when the slope ranking indicates the market is steeply positive (overbought), and the slope value begins to tick downwards, signaling momentum exhaustion. The core philosophy is simple: Enter only when the market is exhausted and has started to turn.インジケーターaccutrades_netの投稿63
MA SMART Angle ### 📊 WHAT IS MA SMART ANGLE? **MA SMART Angle** is an advanced momentum and trend detection indicator that analyzes the angles (slopes) of multiple moving averages to generate clear, non-repainting BUY and SELL signals. **Original Concept Credit:** This indicator builds upon the "MA Angles" concept originally created by **JD** (also known as Duyck). The core angle calculation methodology and Jurik Moving Average (JMA) implementation by **Everget** are preserved from the original open-source work. The angle calculation formula was contributed by **KyJ**. This enhanced version is published with respect to the open-source nature of the original indicator. Original indicator reference: "ma angles - JD" by Duyck --- ## 🎯 ORIGINALITY & VALUE PROPOSITION ### **What Makes This Different from the Original:** While the original "MA Angles" by **JD** provided excellent angle visualization, it lacked actionable entry signals. **MA SMART Angle** addresses this by adding: **1. Clear Entry/Exit Signals** - Explicit BUY/SELL arrows based on angle crossovers, momentum confirmation, and MA alignment - No guessing when to enter trades - the indicator tells you exactly when conditions align **2. Non-Repainting Logic** - All signals use confirmed historical data (shifted by 2 bars minimum) - Critical for backtesting reliability and live trading confidence - Original indicator could repaint signals on current bar **3. Dual Signal System** - **Simple Mode:** More frequent signals based on angle crossovers + momentum (for active traders) - **Strict Mode:** Requires full multi-MA alignment + momentum confirmation (for conservative traders) - Adaptable to different trading styles and risk tolerances **4. Smart Signal Filtering** - **Anti-spam cooldown:** Prevents duplicate signals within configurable bar count - **No-trade zone detection:** Filters out low-conviction sideways markets automatically - **Multi-timeframe MA alignment:** Ensures all moving averages agree on direction before signaling **5. Enhanced Visualization** - Large, clear BUY/SELL arrows with descriptive labels - Color-coded backgrounds for market states (trending vs. ranging) - Momentum histogram showing acceleration/deceleration in real-time - Live status table displaying trend strength, angle value, momentum, and MA alignment **6. Professional Alert System** - Four distinct alert conditions: BUY Signal, SELL Signal, Strong BUY, Strong SELL - Enables automated trade notifications and strategy integration **7. Modified MA Periods** - Original used EMA(27), EMA(83), EMA(278) - Enhanced version uses faster EMA(3), EMA(8), EMA(13) for more responsive signals - Better suited for modern volatile markets and shorter timeframes --- ## 📐 HOW IT WORKS - TECHNICAL EXPLANATION ### **Core Methodology:** The indicator calculates angles (slopes) for five key moving averages: - **JMA (Jurik Moving Average)** - Smooth, lag-reduced trend line (original implementation by **Everget**) - **JMA Fast** - Responsive momentum indicator with higher power parameter - **MA27 (EMA 3)** - Primary fast-moving average for signal generation - **MA83 (EMA 8)** - Medium-term trend confirmation - **MA278 (EMA 13)** - Slower trend filter ### **Angle Calculation Formula (by KyJ):** ``` angle = arctan((MA - MA ) / ATR(14)) × (180 / π) ``` **Why ATR normalization?** - Makes angles comparable across different instruments (forex, stocks, crypto) - Makes angles comparable across different timeframes - Accounts for volatility - a 10-point move in different assets has different significance **Angle Interpretation:** - **> 15°** = Strong trend (momentum accelerating) - **0° to 15°** = Weak trend (momentum present but moderate) - **-2° to +2°** = No-trade zone (sideways/choppy market) - **< -15°** = Strong downtrend ### **Signal Generation Logic:** #### **BUY Signal Conditions:** 1. MA27 angle crosses above 0° (upward momentum initiates) 2. All three EMAs (3, 8, 13) pointing upward (trend alignment confirmed) 3. Momentum is positive for 2+ bars (acceleration, not deceleration) 4. Angle exceeds minimum threshold (not in no-trade zone) 5. Cooldown period passed (prevents signal spam) #### **SELL Signal Conditions:** 1. MA27 angle crosses below 0° (downward momentum initiates) 2. All three EMAs pointing downward (downtrend alignment) 3. Momentum is negative for 2+ bars 4. Angle below negative threshold (not in no-trade zone) 5. Cooldown period passed #### **Strong BUY+ / SELL+ Signals:** Additional entry opportunities when JMA Fast crosses JMA Slow while maintaining strong directional angle - indicates momentum acceleration within established trend. --- ## 🔧 HOW TO USE ### **Recommended Settings by Trading Style:** **Scalpers / Day Traders:** - Signal Type: **Simple** - Minimum Angle: **3-5°** - Cooldown Bars: **3-5 bars** - Timeframes: 1m, 5m, 15m **Swing Traders:** - Signal Type: **Strict** - Minimum Angle: **7-10°** - Cooldown Bars: **8-12 bars** - Timeframes: 1H, 4H, Daily **Position Traders:** - Signal Type: **Strict** - Minimum Angle: **10-15°** - Cooldown Bars: **15-20 bars** - Timeframes: Daily, Weekly ### **Parameter Descriptions:** **1. Source** (default: OHLC4) - Price data used for MA calculations - OHLC4 provides smoothest angles - Close is more responsive but noisier **2. Threshold for No-Trade Zones** (default: 2°) - Angles below this are considered sideways/ranging - Increase for stricter filtering of choppy markets - Decrease to allow signals in quieter trending periods **3. Signal Type** (Simple vs. Strict) - **Simple:** Angle crossover OR (trend + momentum) - **Strict:** Angle crossover AND all MAs aligned AND momentum confirmed - Start with Simple, switch to Strict if too many false signals **4. Minimum Angle for Signal** (default: 5°) - Only generate signals when angle exceeds this threshold - Higher values = stronger trends required - Lower values = more sensitive to momentum changes **5. Cooldown Bars** (default: 5) - Minimum bars between consecutive signals - Prevents spam during volatile chop - Scale with your timeframe (higher TF = more bars) **6. Color Bars** (default: true) - Colors chart bars based on signal state - Green = bullish conditions, Red = bearish conditions - Can disable if you prefer clean price bars **7. Background Colors** - **Yellow background** = No-trade zone (low angle, ranging market) - **Green flash** = BUY signal generated - **Red flash** = SELL signal generated - All customizable or can be disabled --- ## 📊 INTERPRETING THE INDICATOR ### **Visual Elements:** **Main Chart Window:** - **Thick Lime/Fuchsia Line** = MA27 angle (primary signal line) - **Medium Green/Red Line** = MA83 angle (trend confirmation) - **Thin Green/Red Line** = MA278 angle (slow trend filter) - **Aqua/Orange Line** = JMA Fast (momentum detector) - **Green/Red Area** = JMA slope (overall trend context) - **Blue/Purple Histogram** = Momentum (angle acceleration/deceleration) **Signal Arrows:** - **Large Green ▲ "BUY"** = Primary buy signal (all conditions met) - **Small Green ▲ "BUY+"** = Strong momentum buy (JMA fast cross) - **Large Red ▼ "SELL"** = Primary sell signal (all conditions met) - **Small Red ▼ "SELL+"** = Strong momentum sell (JMA fast cross) **Status Table (Top Right):** - **Angle:** Current MA27 angle in degrees - **Trend:** Classification (STRONG UP/DOWN, UP/DOWN, FLAT) - **Momentum:** Acceleration state (ACCEL UP/DN, Up/Down) - **MAs:** Alignment status (ALL UP/DOWN, Mixed) - **Zone:** Trading zone status (ACTIVE vs. NO TRADE) - **Last:** Bars since last signal ### **Trading Strategies:** **Strategy 1: Pure Signal Following** - Enter LONG on BUY signal - Exit on SELL signal - Use stop-loss at recent swing low/high - Works best on trending instruments **Strategy 2: Confirmation with Price Action** - Wait for BUY signal + bullish candlestick pattern - Wait for SELL signal + bearish candlestick pattern - Increases win rate by filtering premature signals - Recommended for beginners **Strategy 3: Momentum Acceleration** - Use BUY+/SELL+ signals for adding to positions - Only take these in direction of primary signal - Scalp quick moves during momentum spikes - For experienced traders **Strategy 4: Mean Reversion in No-Trade Zones** - When status shows "NO TRADE", fade extremes - Wait for angle to exit no-trade zone for reversal - Contrarian approach for range-bound markets - Requires tight stops --- ## ⚠️ LIMITATIONS & DISCLAIMERS **What This Indicator DOES:** ✅ Measures momentum direction and strength via angle analysis ✅ Generates signals when multiple conditions align ✅ Filters out low-conviction sideways markets ✅ Provides visual clarity on trend state **What This Indicator DOES NOT:** ❌ Predict future price movements with certainty ❌ Guarantee profitable trades (no indicator can) ❌ Work equally well on all instruments/timeframes ❌ Replace proper risk management and position sizing **Known Limitations:** - **Lagging Nature:** Like all moving averages, signals occur after momentum begins - **Whipsaw Risk:** Can generate false signals in volatile, directionless markets - **Optimization Required:** Parameters need adjustment for different assets - **Not a Complete System:** Should be combined with risk management, position sizing, and other analysis **Best Performance Conditions:** - Strong trending markets (crypto bull runs, stock breakouts) - Liquid instruments (major forex pairs, large-cap stocks) - Appropriate timeframe selection (match to trading style) - Used alongside support/resistance and volume analysis --- ## 🔔 ALERT SETUP The indicator includes four alert conditions: **1. BUY SIGNAL** - Message: "MA SMART Angle: BUY SIGNAL! Angle crossed up with momentum" - Use for: Primary long entries **2. SELL SIGNAL** - Message: "MA SMART Angle: SELL SIGNAL! Angle crossed down with momentum" - Use for: Primary short entries or long exits **3. Strong BUY** - Message: "MA SMART Angle: Strong BUY momentum - JMA fast crossed up" - Use for: Adding to longs or aggressive entries **4. Strong SELL** - Message: "MA SMART Angle: Strong SELL momentum - JMA fast crossed down" - Use for: Adding to shorts or aggressive exits **Setting Up Alerts:** 1. Right-click indicator → "Add Alert on MA SMART Angle" 2. Select desired condition from dropdown 3. Choose notification method (popup, email, webhook) 4. Set alert expiration (typically "Once Per Bar Close") --- ## 📚 EDUCATIONAL VALUE This indicator serves as an excellent learning tool for understanding: **1. Angle-Based Momentum Analysis** - Traditional indicators show MA crossovers - This shows the *rate of change* (velocity) of MAs - Teaches traders to think in terms of momentum acceleration **2. Multi-Timeframe Confirmation** - Shows how fast, medium, and slow MAs interact - Demonstrates importance of trend alignment - Helps develop patience for high-probability setups **3. Signal Quality vs. Quantity Tradeoff** - Simple mode = more signals, more noise - Strict mode = fewer signals, higher quality - Teaches discretionary filtering skills **4. Market State Recognition** - Visual distinction between trending and ranging markets - Helps traders avoid trading choppy conditions - Develops "market context" awareness --- ## 🔄 DIFFERENCES FROM OTHER MA INDICATORS **vs. Traditional MA Crossovers:** - Measures momentum (angle) rather than just price crossing MA - Provides earlier signals as angles change before price crosses - Filters better for sideways markets using no-trade zones **vs. MACD:** - Uses multiple MAs instead of just two - ATR normalization makes it universal across instruments - Visual angle representation more intuitive than histogram **vs. Supertrend:** - Not based on ATR bands but on MA slope analysis - Provides graduated strength indication (not just binary trend) - Less prone to whipsaw in low volatility **vs. Original "MA Angles" by JD:** - Adds explicit entry/exit signals (original had none) - Implements no-repaint logic for reliability - Includes signal filtering and quality controls - Provides dual signal systems (Simple/Strict) - Enhanced visualization and status monitoring - Uses faster MA periods (3/8/13 vs 27/83/278) for modern markets --- ## 📖 CODE STRUCTURE (for Pine Script learners) This indicator demonstrates: **Advanced Pine Script Techniques:** - Custom function implementation (JMA, angle calculation) - Var declarations for stateful tracking - Table creation for HUD display - Multi-condition signal logic - Alert system integration - Proper use of historical references for no-repaint **Code Organization:** - Modular function definitions (JMA, angle) - Clear separation of concerns (inputs, calculations, plotting, alerts) - Extensive commenting for maintainability - Best practices for Pine Script v5 **Learning Resources:** - Study the JMA function to understand adaptive smoothing - Examine angle calculation for ATR normalization technique - Review signal logic for multi-condition confirmation patterns - Analyze anti-spam filtering for state management The code is open-source - feel free to study, modify, and improve upon it! --- ## 🙏 CREDITS & ATTRIBUTION **Original Concepts:** - **"ma angles - JD" by JD (Duyck)** - Core angle calculation methodology and indicator concept Original open-source indicator on TradingView Community Scripts - **JMA (Jurik Moving Average) implementation by Everget** - Smooth, low-lag moving average function Acknowledged in original JD indicator code - **Angle Calculation formula by KyJ** - Mathematical formula for converting MA slope to degrees using ATR normalization Acknowledged in original JD indicator code comments **Enhancements in This Version:** - Signal generation logic - Original implementation for this indicator - No-repaint confirmation system - Original implementation - Dual signal modes (Simple/Strict) - Original implementation - Visual enhancements and status table - Original implementation - Alert system and signal filtering - Original implementation - Modified MA periods (3/8/13 instead of 27/83/278) - Optimization for modern markets **Open Source Philosophy:** This indicator follows the open-source spirit of TradingView and the Pine Script community. The original "ma angles - JD" by JD (Duyck) was published as open-source, enabling this enhanced version. Similarly, this code is published as open-source to allow further community improvements. --- ## ⚡ QUICK START GUIDE **For New Users:** 1. Add indicator to chart 2. Start with default settings (Simple mode) 3. Wait for BUY signal (green arrow) 4. Observe how price behaves after signal 5. Check status table to understand market state 6. Adjust parameters based on your instrument/timeframe **For Experienced Traders:** 1. Switch to Strict mode for higher quality signals 2. Increase cooldown bars to reduce frequency 3. Raise minimum angle threshold for stronger trends 4. Combine with your existing strategy for confirmation 5. Set up alerts for desired signal types 6. Backtest on your preferred instruments --- ## 🎓 RECOMMENDED COMBINATIONS **Works Well With:** - **Volume Analysis:** Confirm signals with volume spikes - **Support/Resistance:** Take signals near key levels - **RSI/Stochastic:** Avoid overbought/oversold extremes - **ATR:** Size positions based on volatility - **Price Action:** Wait for candlestick confirmation **Complementary Indicators:** - Order Flow / Footprint (for institutional confirmation) - Volume Profile (for identifying value areas) - VWAP (for intraday mean reversion reference) - Fibonacci Retracements (for target setting) --- ## 📈 PERFORMANCE EXPECTATIONS **Realistic Win Rates:** - Simple Mode: 45-55% (higher frequency, moderate accuracy) - Strict Mode: 55-65% (lower frequency, higher accuracy) - Combined with price action: 60-70% **Best Asset Classes:** 1. **Cryptocurrencies** (strong trends, clear signals) 2. **Forex Major Pairs** (smooth price action, good angles) 3. **Large-Cap Stocks** (trending behavior, liquid) 4. **Index Futures** (trending instruments) **Challenging Conditions:** - Low volatility consolidation periods - News-driven erratic movements - Thin/illiquid instruments - Counter-trending markets --- ## 🛡️ RISK DISCLAIMER **IMPORTANT LEGAL NOTICE:** This indicator is for **educational and informational purposes only**. It is **NOT financial advice** and does not constitute a recommendation to buy or sell any financial instrument. **Trading Risks:** - Trading carries substantial risk of loss - Past performance does not guarantee future results - No indicator can predict market movements with certainty - You can lose more than your initial investment (especially with leverage) **User Responsibilities:** - Conduct your own research and due diligence - Understand the instruments you trade - Never risk more than you can afford to lose - Use proper position sizing and risk management - Consider consulting a licensed financial advisor **Indicator Limitations:** - Signals are based on historical data only - No guarantee of accuracy or profitability - Parameters must be optimized for your specific use case - Results vary significantly by market conditions By using this indicator, you acknowledge and accept all trading risks. The author is not responsible for any financial losses incurred through use of this indicator. --- ## 📧 SUPPORT & FEEDBACK **Found a bug?** Please report it in the comments with: - Chart symbol and timeframe - Parameter settings used - Description of unexpected behavior - Screenshot if possible **Have suggestions?** Share your ideas for improvements! **Enjoying the indicator?** Leave a like and follow for updates! インジケーターSmart-Day-Traderの投稿22201
Momentum Regression [BackQuant]Momentum Regression The Momentum Regression is an advanced statistical indicator built to empower quants, strategists, and technically inclined traders with a robust visual and quantitative framework for analyzing momentum effects in financial markets. Unlike traditional momentum indicators that rely on raw price movements or moving averages, this tool leverages a volatility-adjusted linear regression model (y ~ x) to uncover and validate momentum behavior over a user-defined lookback window. Purpose & Design Philosophy Momentum is a core anomaly in quantitative finance — an effect where assets that have performed well (or poorly) continue to do so over short to medium-term horizons. However, this effect can be noisy, regime-dependent, and sometimes spurious. The Momentum Regression is designed as a pre-strategy analytical tool to help you filter and verify whether statistically meaningful and tradable momentum exists in a given asset. Its architecture includes: Volatility normalization to account for differences in scale and distribution. Regression analysis to model the relationship between past and present standardized returns. Deviation bands to highlight overbought/oversold zones around the predicted trendline. Statistical summary tables to assess the reliability of the detected momentum. Core Concepts and Calculations The model uses the following: Independent variable (x): The volatility-adjusted return over the chosen momentum period. Dependent variable (y): The 1-bar lagged log return, also adjusted for volatility. A simple linear regression is performed over a large lookback window (default: 1000 bars), which reveals the slope and intercept of the momentum line. These values are then used to construct: A predicted momentum trendline across time. Upper and lower deviation bands , representing ±n standard deviations of the regression residuals (errors). These visual elements help traders judge how far current returns deviate from the modeled momentum trend, similar to Bollinger Bands but derived from a regression model rather than a moving average. Key Metrics Provided On each update, the indicator dynamically displays: Momentum Slope (β₁): Indicates trend direction and strength. A higher absolute value implies a stronger effect. Intercept (β₀): The predicted return when x = 0. Pearson’s R: Correlation coefficient between x and y. R² (Coefficient of Determination): Indicates how well the regression line explains the variance in y. Standard Error of Residuals: Measures dispersion around the trendline. t-Statistic of β₁: Used to evaluate statistical significance of the momentum slope. These statistics are presented in a top-right summary table for immediate interpretation. A bottom-right signal table also summarizes key takeaways with visual indicators. Features and Inputs ✅ Volatility-Adjusted Momentum : Reduces distortions from noisy price spikes. ✅ Custom Lookback Control : Set the number of bars to analyze regression. ✅ Extendable Trendlines : For continuous visualization into the future. ✅ Deviation Bands : Optional ±σ multipliers to detect abnormal price action. ✅ Contextual Tables : Help determine strength, direction, and significance of momentum. ✅ Separate Pane Design : Cleanly isolates statistical momentum from price chart. How It Helps Traders 📉 Quantitative Strategy Validation: Use the regression results to confirm whether a momentum-based strategy is worth pursuing on a specific asset or timeframe. 🔍 Regime Detection: Track when momentum breaks down or reverses. Slope changes, drops in R², or weak t-stats can signal regime shifts. 📊 Trade Filtering: Avoid false positives by entering trades only when momentum is both statistically significant and directionally favorable. 📈 Backtest Preparation: Before running costly simulations, use this tool to pre-screen assets for exploitable return structures. When to Use It Before building or deploying a momentum strategy : Test if momentum exists and is statistically reliable. During market transitions : Detect early signs of fading strength or reversal. As part of an edge-stacking framework : Combine with other filters such as volatility compression, volume surges, or macro filters. Conclusion The Momentum Regression indicator offers a powerful fusion of statistical analysis and visual interpretation. By combining volatility-adjusted returns with real-time linear regression modeling, it helps quantify and qualify one of the most studied and traded anomalies in finance: momentum.インジケーターBackQuantの投稿33222
Volume Weighted Average Price Dynamic Slope [sgbpulse]VWAP Dynamic Slope: A Comprehensive Indicator for Trend Identification and Smart Trading Introducing VWAP Dynamic Slope, an innovative TradingView indicator that harnesses the power of Volume Weighted Average Price (VWAP) and enhances it with immediate visual feedback. The indicator colors the VWAP line based on its slope, allowing you to quickly and easily identify the direction and strength of the current trend for the asset, providing advanced tools for in-depth analysis. What is VWAP and Why is it so Important? VWAP (Volume Weighted Average Price) is an indicator that represents the average price at which an asset has traded, weighted by the volume traded at each price level. Unlike a simple moving average, VWAP gives greater weight to trades executed with high volume, making it a reliable measure of the asset's "true" or "fair" price within a given period. Many institutional traders use VWAP as a central reference point for evaluating the effectiveness of entries and exits. An asset trading above its VWAP is considered to have bullish momentum, and below it – bearish momentum. How it Works: Dynamic VWAP Slope Analysis VWAP Dynamic Slope analyzes the inclination of the VWAP line and displays it using an intuitive color scheme: Positive Slope (Uptrend): When the VWAP points upwards, signaling positive momentum, the default color will be green. Negative Slope (Downtrend): When the VWAP points downwards, signaling negative momentum, the default color will be orange. Trend Change (CHG): When a change in the VWAP's trend direction occurs, a "CHG" label will be displayed. The label's color will be green if the change is to an uptrend, and orange if the change is to a downtrend. Identifying Steep Slopes for Increased Momentum: The indicator's uniqueness lies in its ability to identify "steep" slopes – rapid and particularly strong changes in the VWAP's direction. This indicates exceptionally strong momentum: Steep Positive Slope: The VWAP color will change to dark green, indicating significant buying pressure. Steep Negative Slope: The VWAP color will change to dark red, indicating significant selling pressure. Dynamic Momentum Strength Label: In situations of steep slope (positive or negative), a dynamic label will be displayed with the change value of the VWAP at that point. This label allows you to monitor momentum strength, intensification, or weakening in real-time. Advanced Analytical Tools for Complete Control VWAP Dynamic Slope provides you with unprecedented flexibility through a variety of customizable tools: Multiple VWAP Anchors and Visual Marking: Common Time Anchors: Choose whether the VWAP resets at the beginning of each Session (daily), Week, Month, Quarter, Year, Decade, or Century. Advanced Intraday Anchors: Within the Session, you can choose to calculate VWAP specifically for Pre-Market, Regular Hours, and Post-Market hours. This option is particularly crucial for intraday traders. Important Event Anchors: The indicator allows for VWAP resets at significant milestones such as Earnings, Dividends, and Splits, for analyzing the market's immediate reaction. Visual Anchor Marking: To enhance clarity and orientation, a Label ⚓ can be displayed at each selected anchor point, helping to immediately identify the start point of the VWAP calculation in the chosen context. Customizable Bands (Up to Three on Each Side): Add up to three Bands above and below the VWAP to identify areas of deviation and excursion from the average price. You have two calculation options: Standard Deviation: Based on volatility and statistical distance from the VWAP. Percentage: Defines fixed percentage-based bands from the VWAP. Key Pre-Market Levels (Pre-Market High/Low): Display the Pre-Market High and Low levels as separate lines on the chart. These lines often serve as important psychological support and resistance zones, allowing you to see how the VWAP behaves near them. Full Customization and Precise Control: VWAP Source Selection: Determine which price data type will be used for the VWAP calculation. The default is HLC3 (average of High, Low, and Close), but any other relevant data source available in TradingView can be selected. Offset: Set an offset for the VWAP line, allowing you to shift it left or right on the time axis by a chosen number of bars. Customizable Colors: Choose your preferred colors for each slope state, Pre-Market High/Low lines, and Bands. Setting the "Steepness" Threshold (Per-mille Price Change Per Minute ‱/min with Auto-Adjustment): Determine the sensitivity for identifying a steep slope by setting the required change threshold in VWAP in terms of per-mille price change per minute (‱/min). The indicator performs smart adjustment for any timeframe you select on the chart (e.g., 30 seconds, 1 minute, 5 minutes, 10 minutes, etc.), ensuring that the "steepness" setting maintains consistency and relevance. Examples for Setting the Steepness Threshold: Suppose you set the steepness threshold to 0.3‱/min (per-mille price change per minute). On a 30-second chart: The indicator will check if the VWAP changed by 0.15 ‱/min (half of the per-minute threshold) within a single bar. If so, the slope will be considered steep. Explanation: Since 30 seconds is half a minute, the indicator looks for a change that is half of the threshold set for a full minute. On a 1-minute chart: The indicator will check if the VWAP changed by 0.3 ‱/min (the full per-minute threshold) within a single bar. If so, the slope will be considered steep. Explanation: Here, the bar represents a full minute, so we check the full threshold. On a 5-minute chart: The indicator will check if the VWAP changed by 1.5 ‱/min (5 times the per-minute threshold) within a single bar. If so, the slope will be considered steep. Explanation: A 5-minute bar contains 5 minutes, so the cumulative change in VWAP needs to be 5 times greater to be considered "steep" on the same scale. In summary, this setting allows you to precisely and uniformly control the sensitivity of steep slope detection across all timeframes, providing immense flexibility in analyzing the asset's momentum. Advantages of Using Per-mille Price Change Per Minute (‱/min) Using per-mille price change per minute (‱/min) offers several key advantages for your indicator: Normalized and Objective Measurement: It provides a uniform scale for the VWAP's rate of change, regardless of the asset's price or nominal value. A 0.1 per-mille change per minute always carries the same relative significance. Comparison Across Different Asset Prices: Using per-mille allows for direct comparison of VWAP movement strength between assets trading at very different prices (e.g., a $100 asset versus a $1 asset), enabling an understanding of true momentum without bias from the nominal price. Smart Timeframe Agnostic Adjustment: This is a critical capability. The indicator automatically adjusts the per-mille per minute threshold you set to any chart timeframe (30 seconds, 1 minute, 5 minutes, etc.), maintaining consistency in "steepness" detection without manual recalibration. Precise Momentum Identification: This measurement precisely identifies when the VWAP's rate of change becomes significant, and when momentum strengthens or weakens, contributing to more informed trading decisions. In short, per-mille change per minute (‱/min) provides accuracy, consistency, and flexibility in identifying VWAP momentum changes, with smart adaptation across all timeframes. Who is this Indicator For? VWAP Dynamic Slope is a powerful tool for: Intraday Traders: For quick identification of intraday trend directions and momentum across any timeframe, with specific consideration for Pre-Market, Regular Hours, or Post-Market VWAP, and incorporating key pre-market levels. Swing Traders and Long-Term Investors: For analyzing longer-term trends based on periodic and event-driven VWAP anchors. Beginner Traders: As an excellent visual aid for understanding the relationship between price, volume, and trend direction, and how different anchor points, pre-market levels, and data sources influence price behavior. Experienced Traders: For integration with existing strategies, gaining additional confirmation for trend strength identification, and highly precise and flexible parameter calibration. VWAP Dynamic Slope provides a rich, multi-dimensional layer of information about the VWAP, helping you make more informed trading decisions in real-time, within the context of your chosen asset. インジケーターsgbpulseの投稿66216
TrendLibrary "Trend" calculateSlopeTrend(source, length, thresholdMultiplier) Parameters: source (float) length (int) thresholdMultiplier (float) Purpose: The primary goal of this function is to determine the short-term trend direction of a given data series (like closing prices). It does this by calculating the slope of the data over a specified period and then comparing that slope against a dynamic threshold based on the data's recent volatility. It classifies the trend into one of three states: Upward, Downward, or Flat. Parameters: `source` (Type: `series float`): This is the input data series you want to analyze. It expects a series of floating-point numbers, typically price data like `close`, `open`, `hl2` (high+low)/2, etc. `length` (Type: `int`): This integer defines the lookback period. The function will analyze the `source` data over the last `length` bars to calculate the slope and standard deviation. `thresholdMultiplier` (Type: `float`, Default: `0.1`): This is a sensitivity factor. It's multiplied by the standard deviation to determine how steep the slope needs to be before it's considered a true upward or downward trend. A smaller value makes it more sensitive (detects trends earlier, potentially more false signals), while a larger value makes it less sensitive (requires a stronger move to confirm a trend). Calculation Steps: Linear Regression: It first calculates the value of a linear regression line fitted to the `source` data over the specified `length` (`ta.linreg(source, length, 0)`). Linear regression finds the "best fit" straight line through the data points. Slope Calculation: It then determines the slope of this linear regression line. Since `ta.linreg` gives the *value* of the line on the current bar, the slope is calculated as the difference between the current bar's linear regression value (`linRegValue`) and the previous bar's value (`linRegValue `). A positive difference means an upward slope, negative means downward. Volatility Measurement: It calculates the standard deviation (`ta.stdev(source, length)`) of the `source` data over the same `length`. Standard deviation is a measure of how spread out the data is, essentially quantifying its recent volatility. Adaptive Threshold: An adaptive threshold (`threshold`) is calculated by multiplying the standard deviation (`stdDev`) by the `thresholdMultiplier`. This is crucial because it means the definition of a "flat" trend adapts to the market's volatility. In volatile times, the threshold will be wider, requiring a larger slope to signal a trend. In quiet times, the threshold will be narrower. Trend Determination: Finally, it compares the calculated `slope` to the adaptive `threshold`: If the `slope` is greater than the positive `threshold`, the trend is considered **Upward**, and the function returns `1`. If the `slope` is less than the negative `threshold` (`-threshold`), the trend is considered **Downward**, and the function returns `-1`. If the `slope` falls between `-threshold` and `+threshold` (inclusive of 0), the trend is considered **Flat**, and the function returns `0`. Return Value: The function returns an integer representing the determined trend direction: `1`: Upward trend `-1`: Downward trend `0`: Flat trend In essence, this library function provides a way to gauge trend direction using linear regression, but with a smart filter (the adaptive threshold) to avoid classifying minor noise or low-volatility periods as significant trends.ライブラリjabez4jcの投稿0
Uptrick: Z-Score FlowOverview Uptrick: Z-Score Flow is a technical indicator that integrates trend-sensitive momentum analysi s with mean-reversion logic derived from Z-Score calculations. Its primary objective is to identify market conditions where price has either stretched too far from its mean (overbought or oversold) or sits at a statistically “normal” range, and then cross-reference this observation with trend direction and RSI-based momentum signals. The result is a more contextual approach to trade entry and exit, emphasizing precision, clarity, and adaptability across varying market regimes. Introduction Financial instruments frequently transition between trending modes, where price extends strongly in one direction, and ranging modes, where price oscillates around a central value. A simple statistical measure like Z-Score can highlight price extremes by comparing the current price against its historical mean and standard deviation. However, such extremes alone can be misleading if the broader market structure is trending forcefully. Uptrick: Z-Score Flow aims to solve this gap by combining Z-Score with an exponential moving average (EMA) trend filter and a smoothed RSI momentum check, thus filtering out signals that contradict the prevailing market environment. Purpose The purpose of this script is to help traders pinpoint both mean-reversion opportunities and trend-based pullbacks in a way that is statistically grounded yet still mindful of overarching price action. By pairing Z-Score thresholds with supportive conditions, the script reduces the likelihood of acting on random price spikes or dips and instead focuses on movements that are significant within both historical and current contextual frameworks. Originality and Uniquness Layered Signal Verification: Signals require the fulfillment of multiple layers (Z-Score extreme, EMA trend bias, and RSI momentum posture) rather than merely breaching a statistical threshold. RSI Zone Lockout: Once RSI enters an overbought/oversold zone and triggers a signal, the script locks out subsequent signals until RSI recovers above or below those zones, limiting back-to-back triggers. Controlled Cooldown: A dedicated cooldown mechanic ensures that the script waits a specified number of bars before issuing a new signal in the opposite direction. Gradient-Based Visualization: Distinct gradient fills between price and the Z-Mean line enhance readability, showing at a glance whether price is trading above or below its statistical average. Comprehensive Metrics Panel: An optional on-chart table summarizes the Z-Score’s key metrics, streamlining the process of verifying current statistical extremes, mean levels, and momentum directions. Why these indicators were merged Z-Score measurements excel at identifying when price deviates from its mean, but they do not intrinsically reveal whether the market’s trajectory supports a reversion or if price might continue along its trend. The EMA, commonly used for spotting trend directions, offers valuable insight into whether price is predominantly ascending or descending. However, relying solely on a trend filter overlooks the intensity of price moves. RSI then adds a dedicated measure of momentum, helping confirm if the market’s energy aligns with a potential reversal (for example, price is statistically low but RSI suggests looming upward momentum). By uniting these three lenses—Z-Score for statistical context, EMA for trend direction, and RSI for momentum force—the script offers a more comprehensive and adaptable system, aiming to avoid false positives caused by focusing on just one aspect of price behavior. Calculations The core calculation begins with a simple moving average (SMA) of price over zLen bars, referred to as the basis. Next, the script computes the standard deviation of price over the same window. Dividing the difference between the current price and the basis by this standard deviation produces the Z-Score, indicating how many standard deviations the price is from its mean. A positive Z-Score reveals price is above its average; a negative reading indicates the opposite. To detect overall market direction, the script calculates an exponential moving average (emaTrend) over emaTrendLen bars. If price is above this EMA, the script deems the market bullish; if below, it’s considered bearish. For momentum confirmation, the script computes a standard RSI over rsiLen bars, then applies a smoothing EMA over rsiEmaLen bars. This smoothed RSI (rsiEma) is monitored for both its absolute level (oversold or overbought) and its slope (the difference between the current and previous value). Finally, slopeIndex determines how many bars back the script compares the basis to check whether the Z-Mean line is generally rising, falling, or flat, which then informs the coloring scheme on the chart. Calculations and Rational Simple Moving Average for Baseline: An SMA is used for the core mean because it places equal weight on each bar in the lookback period. This helps maintain a straightforward interpretation of overbought or oversold conditions in the context of a uniform historical average. Standard Deviation for Volatility: Standard deviation measures the variability of the data around the mean. By dividing price’s difference from the mean by this value, the Z-Score can highlight whether price is unusually stretched given typical volatility. Exponential Moving Average for Trend: Unlike an SMA, an EMA places more emphasis on recent data, reacting quicker to new price developments. This quicker response helps the script promptly identify trend shifts, which can be crucial for filtering out signals that go against a strong directional move. RSI for Momentum Confirmation: RSI is an oscillator that gauges price movement strength by comparing average gains to average losses over a set period. By further smoothing this RSI with another EMA, short-lived oscillations become less influential, making signals more robust. SlopeIndex for Slope-Based Coloring: To clarify whether the market’s central tendency is rising or falling, the script compares the basis now to its level slopeIndex bars ago. A higher current reading indicates an upward slope; a lower reading, a downward slope; and similar readings, a flat slope. This is visually represented on the chart, providing an immediate sense of the directionality. Inputs zLen (Z-Score Period) Specifies how many bars to include for computing the SMA and standard deviation that form the basis of the Z-Score calculation. Larger values produce smoother but slower signals; smaller values catch quick changes but may generate noise. emaTrendLen (EMA Trend Filter) Sets the length of the EMA used to detect the market’s primary direction. This is pivotal for distinguishing whether signals should be considered (price aligning with an uptrend or downtrend) or filtered out. rsiLen (RSI Length) Defines the window for the initial RSI calculation. This RSI, when combined with the subsequent smoothing EMA, forms the foundation for momentum-based signal confirmations. rsiEmaLen (EMA of RSI Period) Applies an exponential moving average over the RSI readings for additional smoothing. This step helps mitigate rapid RSI fluctuations that might otherwise produce whipsaw signals. zBuyLevel (Z-Score Buy Threshold) Determines how negative the Z-Score must be for the script to consider a potential oversold signal. If the Z-Score dives below this threshold (and other criteria are met), a buy signal is generated. zSellLevel (Z-Score Sell Threshold) Determines how positive the Z-Score must be for a potential overbought signal. If the Z-Score surpasses this threshold (and other checks are satisfied), a sell signal is generated. cooldownBars (Cooldown (Bars)) Enforces a bar-based delay between opposite signals. Once a buy signal has fired, the script must wait the specified number of bars before registering a new sell signal, and vice versa. slopeIndex (Slope Sensitivity (Bars)) Specifies how many bars back the script compares the current basis for slope coloration. A bigger slopeIndex highlights larger directional trends, while a smaller number emphasizes shorter-term shifts. showMeanLine (Show Z-Score Mean Line) Enables or disables the plotting of the Z-Mean and its slope-based coloring. Traders who prefer minimal chart clutter may turn this off while still retaining signals. Features Statistical Core (Z-Score Detection): This feature computes the Z-Score by taking the difference between the current price and the basis (SMA) and dividing by the standard deviation. In effect, it translates price fluctuations into a standardized measure that reveals how significant a move is relative to the typical variation seen over the lookback. When the Z-Score crosses predefined thresholds (zBuyLevel for oversold and zSellLevel for overbought), it signals that price could be at an extreme. How It Works: On each bar, the script updates the SMA and standard deviation. The Z-Score is then refreshed accordingly. Traders can interpret particularly large negative or positive Z-Score values as scenarios where price is abnormally low or high. EMA Trend Filter: An EMA over emaTrendLen bars is used to classify the market as bullish if the price is above it and bearish if the price is below it. This classification is applied to the Z-Score signals, accepting them only when they align with the broader price direction. How It Works: If the script detects a Z-Score below zBuyLevel, it further checks if price is actually in a downtrend (below EMA) before issuing a buy signal. This might seem counterintuitive, but a “downtrend” environment plus an oversold reading often signals a potential bounce or a mean-reversion play. Conversely, for sell signals, the script checks if the market is in an uptrend first. If it is, an overbought reading aligns with potential profit-taking. RSI Momentum Confirmation with Oversold/Overbought Lockout: RSI is calculated over rsiLen, then smoothed by an EMA over rsiEmaLen. If this smoothed RSI dips below a certain threshold (for example, 30) and then begins to slope upward, the indicator treats it as a potential sign of recovering momentum. Similarly, if RSI climbs above a certain threshold (for instance, 70) and starts to slope downward, that suggests dwindling momentum. Additionally, once RSI is in these zones, the indicator locks out repetitive signals until RSI fully exits and re-enters those extreme territories. How It Works: Each bar, the script measures whether RSI has dropped below the oversold threshold (like 30) and has a positive slope. If it does, the buy side is considered “unlocked.” For sell signals, RSI must exceed an overbought threshold (70) and slope downward. The combination of threshold and slope helps confirm that a reversal is genuinely in progress instead of issuing signals while momentum remains weak or stuck in extremes. Cooldown Mechanism: The script features a custom bar-based cooldown that prevents issuing new signals in the opposite direction immediately after one is triggered. This helps avoid whipsaw situations where the market quickly flips from oversold to overbought or vice versa. How It Works: When a buy signal fires, the indicator notes the bar index. If the Z-Score and RSI conditions later suggest a sell, the script compares the current bar index to the last buy signal’s bar index. If the difference is within cooldownBars, the signal is disallowed. This ensures a predefined “quiet period” before switching signals. Slope-Based Coloring (Z-Mean Line and Shadow): The script compares the current basis value to its value slopeIndex bars ago. A higher reading now indicates a generally upward slope, while a lower reading indicates a downward slope. The script then shades the Z-Mean line in a corresponding bullish or bearish color, or remains neutral if little change is detected. How It Works: This slope calculation is refreshingly straightforward: basis – basis . If the result is positive, the line is colored bullish; if negative, it is colored bearish; if approximately zero, it remains neutral. This provides a quick visual cue of the medium-term directional bias. Gradient Overlays: With gradient fills, the script highlights where price stands in relation to the Z-Mean. When price is above the basis, a purple-shaded region is painted, visually indicating a “bearish zone” for potential overbought conditions. When price is below, a teal-like overlay is used, suggesting a “bullish zone” for potential oversold conditions. How It Works: Each bar, the script checks if price is above or below the basis. It then applies a fill between close and basis, using distinct colors to show whether the market is trading above or below its mean. This creates an immediate sense of how extended the market might be. Buy and Sell Labels (with Alerts): When a legitimate buy or sell condition passes every check (Z-Score threshold, EMA trend alignment, RSI gating, and cooldown clearance), the script plots a corresponding label directly on the chart. It also fires an alert (if alerts are set up), making it convenient for traders who want timely notifications. How It Works: If rawBuy or rawSell conditions are met (refined by RSI, EMA trend, and cooldown constraints), the script calls the respective plot function to paint an arrow label on the chart. Alerts are triggered simultaneously, carrying easily recognizable messages. Metrics Table: The optional on-chart table (activated by showMetrics) presents real-time Z-Score data, including the current Z-Score, its rolling mean, the maximum and minimum Z-Score values observed over the last zLen bars, a percentile position, and a short-term directional note (rising, falling, or flat). Current – The present Z-Score reading Mean – Average Z-Score over the zLen period Min/Max – Lowest and highest Z-Score values within zLen Position – Where the current Z-Score sits between the min and max (as a percentile) Trend – Whether the Z-Score is increasing, decreasing, or flat Conclusion Uptrick: Z-Score Flow offers a versatile solution for traders who need a statistically informed perspective on price extremes combined with practical checks for overall trend and momentum. By leveraging a well-defined combination of Z-Score, EMA trend classification, RSI-based momentum gating, slope-based visualization, and a cooldown mechanic, the script reduces the occurrence of false or premature signals. Its gradient fills and optional metrics table contribute further clarity, ensuring that users can quickly assess market posture and make more confident trading decisions in real time. Disclaimer This script is intended solely for informational and educational purposes. Trading in any financial market comes with substantial risk, and there is no guarantee of success or the avoidance of loss. Historical performance does not ensure future results. Always conduct thorough research and consider professional guidance prior to making any investment or trading decisions. インジケーターUptrickの投稿33 1.7 K
Multi-Anchored Linear Regression Channels [TANHEF]█ Overview: The 'Multi-Anchored Linear Regression Channels ' plots multiple dynamic regression channels (or bands) with unique selectable calculation types for both regression and deviation. It leverages a variety of techniques, customizable anchor sources to determine regression lengths, and user-defined criteria to highlight potential opportunities. Before getting started, it's worth exploring all sections, but make sure to review the Setup & Configuration section in particular. It covers key parameters like anchor type, regression length, bias, and signal criteria—essential for aligning the tool with your trading strategy. █ Key Features: ⯁ Multi-Regression Capability: Plot up to three distinct regression channels and/or bands simultaneously, each with customizable anchor types to define their length. ⯁ Regression & Deviation Methods: Regressions Types: Standard: Uses ordinary least squares to compute a simple linear trend by averaging the data and deriving a slope and endpoints over the lookback period. Ridge: Introduces L2 regularization to stabilize the slope by penalizing large coefficients, which helps mitigate multicollinearity in the data. Lasso: Uses L1 regularization through soft-thresholding to shrink less important coefficients, yielding a simpler model that highlights key trends. Elastic Net: Combines L1 and L2 penalties to balance coefficient shrinkage and selection, producing a robust weighted slope that handles redundant predictors. Huber: Implements the Huber loss with iteratively reweighted least squares (IRLS) and EMA-style weights to reduce the impact of outliers while estimating the slope. Least Absolute Deviations (LAD): Reduces absolute errors using iteratively reweighted least squares (IRLS), yielding a slope less sensitive to outliers than squared-error methods. Bayesian Linear: Merges prior beliefs with weighted data through Bayesian updating, balancing the prior slope with data evidence to derive a probabilistic trend. Deviation Types: Regressive Linear (Reverse): In reverse order (recent to oldest), compute weighted squared differences between the data and a line defined by a starting value and slope. Progressive Linear (Forward): In forward order (oldest to recent), compute weighted squared differences between the data and a line defined by a starting value and slope. Balanced Linear: In forward order (oldest to newest), compute regression, then pair to source data in reverse order (newest to oldest) to compute weighted squared differences. Mean Absolute: Compute weighted absolute differences between each data point and its regression line value, then aggregate them to yield an average deviation. Median Absolute: Determine the weighted median of the absolute differences between each data point and its regression line value to capture the central tendency of deviations. Percent: Compute deviation as a percentage of a base value by multiplying that base by the specified percentage, yielding symmetric positive and negative deviations. Fitted: Compare a regression line with high and low series values by computing weighted differences to determine the maximum upward and downward deviations. Average True Range: Iteratively compute the weighted average of absolute differences between the data and its regression line to yield an ATR-style deviation measure. Bias: Bias: Applies EMA or inverse-EMA style weighting to both Regression and/or Deviation, emphasizing either recent or older data. ⯁ Customizable Regression Length via Anchors: Anchor Types: Fixed: Length. Bar-Based: Bar Highest/Lowest, Volume Highest/Lowest, Spread Highest/Lowest. Correlation: R Zero, R Highest, R Lowest, R Absolute. Slope: Slope Zero, Slope Highest, Slope Lowest, Slope Absolute. Indicator-Based: Indicators Highest/Lowest (ADX, ATR, BBW, CCI, MACD, RSI, Stoch). Time-Based: Time (Day, Week, Month, Quarter, Year, Decade, Custom). Session-Based: Session (Tokyo, London, New York, Sydney, Custom). Event-Based: Earnings, Dividends, Splits. External: Input Source Highest/Lowest. Length Selection: Maximum: The highest allowed regression length (also fixed value of “Length” anchor). Minimum: The shortest allowed length, ensuring enough bars for a valid regression. Step: The sampling interval (e.g., 1 checks every bar, 2 checks every other bar, etc.). Increasing the step reduces the loading time, most applicable to “Slope” and “R” anchors. Adaptive lookback: Adaptive Lookback: Enable to display regression regardless of too few historical bars. ⯁ Selecting Bias: Bias applies separately to regression and deviation. Positive values emphasize recent data (EMA-style), negative invert, and near-zero maintains balance. (e.g., a length 100, bias +1 gives the newest price ~7× more weight than the oldest). It's best to apply bias to both (regression and deviation) or just the deviation. Biasing only regression may distort deviation visually, while biasing both keeps their relationship intuitive. Using bias only for deviation scales it without altering regression, offering unique analysis. ⯁ Scale Awareness: Supports linear and logarithmic price scaling, the regression and deviations adjust accordingly. ⯁ Signal Generation & Alerts: Customizable entry/exit signals and alerts, detailed in the dedicated section below. ⯁ Visual Enhancements & Real-World Examples: Optional on-chart table display summarizing regression input criteria (display type, anchor type, source, regression type, regression bias, deviation type, deviation bias, deviation multiplier) and key calculated metrics (regression length, slope, Pearson’s R, percentage position within deviations, etc.) for quick reference. █ Understanding R (Pearson Correlation Coefficient): Pearson’s R gauges data alignment to a straight-line trend within the regression length: Range: R varies between –1 and +1. R = +1 → Perfect positive correlation (strong uptrend). R = 0 → No linear relationship detected. R = –1 → Perfect negative correlation (strong downtrend). This script uses Pearson’s R as an anchor, adjusting regression length to target specific R traits. Strong R (±1) follows the regression channel, while weak R (0) shows inconsistency. █ Understanding the Slope: The slope is the direction and rate at which the regression line rises or falls per bar: Positive Slope (>0): Uptrend – Steeper means faster increase. Negative Slope (<0): Downtrend – Steeper means sharper drop. Zero or Near-Zero Slope: Sideways – Indicating range-bound conditions. This script uses highest and lowest slope as an anchor, where extremes highlight strong moves and trend lines, while values near zero indicate sideways action and possible support/resistance. █ Setup & Configuration: Whether you’re new to this script or want to quickly adjust all critical parameters, the panel below shows the main settings available. You can customize everything from the anchor type and maximum length to the bias, signal conditions, and more. Scale (select Log Scale for logarithmic, otherwise linear scale). Display (regression channel and/or bands). Anchor (how regression length is determined). Length (control bars analyzed): • Max – Upper limit. • Min – Prevents regression from becoming too short. • Step – Controls scanning precision; increasing Step reduces load time. Regression: • Type – Calculation method. • Bias – EMA-style emphasis (>0=new bars weighted more; <0=old bars weighted more). Deviation: • Type – Calculation method. • Bias – EMA-style emphasis (>0=new bars weighted more; <0=old bars weighted more). • Multiplier - Adjusts Upper and Lower Deviation. Signal Criteria: • % (Price vs Deviation) – (0% = lower deviation, 50% = regression, 100% = upper deviation). • R – (0 = no correlation, ±1 = perfect correlation; >0 = +slope, <0 = -slope). Table (analyze table of input settings, calculated results, and signal criteria). Adaptive Lookback (display regression while too few historical bars). Multiple Regressions (steps 2 to 7 apply to #1, #2, and #3 regressions). █ Signal Generation & Alerts: The script offers customizable entry and exit signals with flexible criteria and visual cues (background color, dots, or triangles). Alerts can also be triggered for these opportunities. Percent Direction Criteria: (0% = lower deviation, 50% = regression line, 100% = upper deviation) Above %: Triggers if price is above a specified percent of the deviation channel. Below %: Triggers if price is below a specified percent of the deviation channel. (Blank): Ignores the percent‐based condition. Pearson's R (Correlation) Direction Criteria: (0 = no correlation, ±1 = perfect correlation; >0 = positive slope, <0 = negative slope) Above R / Below R: Compares the correlation to a threshold. Above│R│ / Below│R│: Uses absolute correlation to focus on strength, ignoring direction. Zero to R: Checks if R is in the 0-to-threshold range. (Blank): Ignores correlation-based conditions. █ User Tips & Best Practices: Choose an anchor type that suits your strategy, “Bar Highest/Lowest” automatically spots commonly used regression zones, while “│R│ Highest” targets strong linear trends. Consider enabling or disabling the Adaptive Lookback feature to ensure you always have a plotted regression if your chart doesn’t meet the maximum-length requirement. Use a small Step size (1) unless relying on R-correlation or slope-based anchors as the are time-consuming to calculate. Larger steps speed up calculations but reduce precision. Fine-tune settings such as lookback periods, regression bias, and deviation multipliers, or trend strength. Small adjustments can significantly affect how channels and signals behave. To reduce loading time , show only channels (not bands) and disable signals, this limits calculations to the last bar and supports more extreme criteria. Use the table display to monitor anchor type, calculated length, slope, R value, and percent location at a glance—especially if you have multiple regressions visible simultaneously. █ Conclusion: With its blend of advanced regression techniques, flexible deviation options, and a wide range of anchor types, this indicator offers a highly adaptable linear regression channeling system. Whether you're anchoring to time, price extremes, correlation, slope, or external events, the tool can be shaped to fit a variety of strategies. Combined with customizable signals and alerts, it may help highlight areas of confluence and support a more structured approach to identifying potential opportunities.インジケーターTanHefの投稿更新済 1616 1.9 K
LinearRegressionLibrary "LinearRegression" Calculates a variety of linear regression and deviation types, with optional emphasis weighting. Additionally, multiple of slope and Pearson’s R calculations. calcSlope(_src, _len, _condition) Calculates the slope of a linear regression over the specified length. Parameters: _src (float) : (float) The source data. _len (int) : (int) The length of the lookback period for the linear regression. _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast for efficiency. Returns: (float) The slope of the linear regression. calcReg(_src, _len, _condition) Calculates a basic linear regression, returning y1, y2, slope, and average. Parameters: _src (float) : (float) The source data series. _len (int) : (int) The length of the lookback period. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: (float ) An array of 4 values: . calcRegStandard(_src, _len, _emphasis, _condition) Calculates an Standard linear regression with optional emphasis. Parameters: _src (float) : (series float) The source data series. _len (int) : (int) The length of the lookback period. _emphasis (float) : (float) The emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: (float ) . calcRegRidge(_src, _len, lambda, _emphasis, _condition) Calculates a ridge regression with optional emphasis. Parameters: _src (float) : (float) The source data series. _len (int) : (int) The length of the lookback period. lambda (float) : (float) The ridge regularization parameter. _emphasis (float) : (float) The emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: (float ) . calcRegLasso(_src, _len, lambda, _emphasis, _condition) Calculates a Lasso regression with optional emphasis. Parameters: _src (float) : (float) The source data series. _len (int) : (int) The length of the lookback period. lambda (float) : (float) The Lasso regularization parameter. _emphasis (float) : (float) The emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: (float ) . calcElasticNetLinReg(_src, _len, lambda1, lambda2, _emphasis, _condition) Calculates an Elastic Net regression with optional emphasis. Parameters: _src (float) : (float) The source data series. _len (int) : (int) The length of the lookback period. lambda1 (float) : (float) L1 regularization parameter (Lasso). lambda2 (float) : (float) L2 regularization parameter (Ridge). _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: (float ) . calcRegHuber(_src, _len, delta, iterations, _emphasis, _condition) Calculates a Huber regression using Iteratively Reweighted Least Squares (IRLS). Parameters: _src (float) : (float) The source data series. _len (int) : (int) The length of the lookback period. delta (float) : (float) Huber threshold parameter. iterations (int) : (int) Number of IRLS iterations. _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: (float ) . calcRegLAD(_src, _len, iterations, _emphasis, _condition) Calculates a Least Absolute Deviations (LAD) regression via IRLS. Parameters: _src (float) : (float) The source data series. _len (int) : (int) The length of the lookback period. iterations (int) : (int) Number of IRLS iterations for LAD. _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: (float ) . calcRegBayesian(_src, _len, priorMean, priorSpan, sigma, _emphasis, _condition) Calculates a Bayesian linear regression with optional emphasis. Parameters: _src (float) : (float) The source data series. _len (int) : (int) The length of the lookback period. priorMean (float) : (float) The prior mean for the slope. priorSpan (float) : (float) The prior variance (or span) for the slope. sigma (float) : (float) The assumed standard deviation of residuals. _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: (float ) . calcRFromLinReg(_src, _len, _slope, _average, _y1, _condition) Calculates the Pearson correlation coefficient (R) based on linear regression parameters. Parameters: _src (float) : (float) The source data. _len (int) : (int) The length of the lookback period. _slope (float) : (float) The slope of the linear regression. _average (float) : (float) The average value of the source data series. _y1 (float) : (float) The starting point (y-intercept of the oldest bar) for the linear regression. _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast for efficiency. Returns: (float) The Pearson correlation coefficient (R) adjusted for the direction of the slope. calcRFromSource(_src, _len, _condition) Calculates the correlation coefficient (R) using a specified length and source data. Parameters: _src (float) : (float) The source data. _len (int) : (int) The length of the lookback period. _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast for efficiency. Returns: (float) The correlation coefficient (R). calcSlopeLengthZero(_src, _len, _minLen, _step, _condition) Identifies the length at which the slope is flattest (closest to zero). Parameters: _src (float) : (float) The source data. _len (int) : (int) The maximum lookback length to consider (minimum of 2). _minLen (int) : (int) The minimum length to start from (cannot exceed the max length). _step (int) : (int) The increment step for lengths. _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast. Returns: (int) The length at which the slope is flattest. calcSlopeLengthHighest(_src, _len, _minLen, _step, _condition) Identifies the length at which the slope is highest. Parameters: _src (float) : (float) The source data. _len (int) : (int) The maximum lookback length (minimum of 2). _minLen (int) : (int) The minimum length to start from. _step (int) : (int) The step for incrementing lengths. _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast. Returns: (int) The length at which the slope is highest. calcSlopeLengthLowest(_src, _len, _minLen, _step, _condition) Identifies the length at which the slope is lowest. Parameters: _src (float) : (float) The source data. _len (int) : (int) The maximum lookback length (minimum of 2). _minLen (int) : (int) The minimum length to start from. _step (int) : (int) The step for incrementing lengths. _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast. Returns: (int) The length at which the slope is lowest. calcSlopeLengthAbsolute(_src, _len, _minLen, _step, _condition) Identifies the length at which the absolute slope value is highest. Parameters: _src (float) : (float) The source data. _len (int) : (int) The maximum lookback length (minimum of 2). _minLen (int) : (int) The minimum length to start from. _step (int) : (int) The step for incrementing lengths. _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast. Returns: (int) The length at which the absolute slope value is highest. calcRLengthZero(_src, _len, _minLen, _step, _condition) Identifies the length with the lowest absolute R value. Parameters: _src (float) : (float) The source data. _len (int) : (int) The maximum lookback length (minimum of 2). _minLen (int) : (int) The minimum length to start from. _step (int) : (int) The step for incrementing lengths. _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast. Returns: (int) The length with the lowest absolute R value. calcRLengthHighest(_src, _len, _minLen, _step, _condition) Identifies the length with the highest R value. Parameters: _src (float) : (float) The source data. _len (int) : (int) The maximum lookback length (minimum of 2). _minLen (int) : (int) The minimum length to start from. _step (int) : (int) The step for incrementing lengths. _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast. Returns: (int) The length with the highest R value. calcRLengthLowest(_src, _len, _minLen, _step, _condition) Identifies the length with the lowest R value. Parameters: _src (float) : (float) The source data. _len (int) : (int) The maximum lookback length (minimum of 2). _minLen (int) : (int) The minimum length to start from. _step (int) : (int) The step for incrementing lengths. _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast. Returns: (int) The length with the lowest R value. calcRLengthAbsolute(_src, _len, _minLen, _step, _condition) Identifies the length with the highest absolute R value. Parameters: _src (float) : (float) The source data. _len (int) : (int) The maximum lookback length (minimum of 2). _minLen (int) : (int) The minimum length to start from. _step (int) : (int) The step for incrementing lengths. _condition (bool) : (bool) Flag to enable calculation. Set to true to calculate on every bar; otherwise, set to barstate.islast. Returns: (int) The length with the highest absolute R value. calcDevReverse(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition) Calculates the regressive linear deviation in reverse order, with optional emphasis on recent data. Parameters: _src (float) : (float) The source data. _len (int) : (int) The length of the lookback period. _slope (float) : (float) The slope of the linear regression. _y1 (float) : (float) The y-intercept (oldest bar) of the linear regression. _inputDev (float) : (float) The input deviation multiplier. _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: A 2-element tuple: . calcDevForward(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition) Calculates the progressive linear deviation in forward order (oldest to most recent bar), with optional emphasis. Parameters: _src (float) : (float) The source data array, where _src is oldest and _src is most recent. _len (int) : (int) The length of the lookback period. _slope (float) : (float) The slope of the linear regression. _y1 (float) : (float) The y-intercept of the linear regression (value at the most recent bar, adjusted by slope). _inputDev (float) : (float) The input deviation multiplier. _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: A 2-element tuple: . calcDevBalanced(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition) Calculates the balanced linear deviation with optional emphasis on recent or older data. Parameters: _src (float) : (float) Source data array, where _src is the most recent and _src is the oldest. _len (int) : (int) The length of the lookback period. _slope (float) : (float) The slope of the linear regression. _y1 (float) : (float) The y-intercept of the linear regression (value at the oldest bar). _inputDev (float) : (float) The input deviation multiplier. _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: A 2-element tuple: . calcDevMean(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition) Calculates the mean absolute deviation from a forward-applied linear trend (oldest to most recent), with optional emphasis. Parameters: _src (float) : (float) The source data array, where _src is the most recent and _src is the oldest. _len (int) : (int) The length of the lookback period. _slope (float) : (float) The slope of the linear regression. _y1 (float) : (float) The y-intercept (oldest bar) of the linear regression. _inputDev (float) : (float) The input deviation multiplier. _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: A 2-element tuple: . calcDevMedian(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition) Calculates the median absolute deviation with optional emphasis on recent data. Parameters: _src (float) : (float) The source data array (index 0 = oldest, index _len - 1 = most recent). _len (int) : (int) The length of the lookback period. _slope (float) : (float) The slope of the linear regression. _y1 (float) : (float) The y-intercept (oldest bar) of the linear regression. _inputDev (float) : (float) The deviation multiplier. _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: calcDevPercent(_y1, _inputDev, _condition) Calculates the percent deviation from a given value and a specified percentage. Parameters: _y1 (float) : (float) The base value from which to calculate deviation. _inputDev (float) : (float) The deviation percentage. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: A 2-element tuple: . calcDevFitted(_len, _slope, _y1, _emphasis, _condition) Calculates the weighted fitted deviation based on high and low series data, showing max deviation, with optional emphasis. Parameters: _len (int) : (int) The length of the lookback period. _slope (float) : (float) The slope of the linear regression. _y1 (float) : (float) The Y-intercept (oldest bar) of the linear regression. _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: A 2-element tuple: . calcDevATR(_src, _len, _slope, _y1, _inputDev, _emphasis, _condition) Calculates an ATR-style deviation with optional emphasis on recent data. Parameters: _src (float) : (float) The source data (typically close). _len (int) : (int) The length of the lookback period. _slope (float) : (float) The slope of the linear regression. _y1 (float) : (float) The Y-intercept (oldest bar) of the linear regression. _inputDev (float) : (float) The input deviation multiplier. _emphasis (float) : (float) Emphasis factor: 0 for equal weight; >0 emphasizes recent bars; <0 emphasizes older bars. _condition (bool) : (bool) Flag to enable calculation (true = calculate). Returns: A 2-element tuple: . calcPricePositionPercent(_top, _bot, _src) Calculates the percent position of a price within a linear regression channel. Top=100%, Bottom=0%. Parameters: _top (float) : (float) The top (positive) deviation, corresponding to 100%. _bot (float) : (float) The bottom (negative) deviation, corresponding to 0%. _src (float) : (float) The source price. Returns: (float) The percent position within the channel. plotLinReg(_len, _y1, _y2, _slope, _devTop, _devBot, _scaleTypeLog, _lineWidth, _extendLines, _channelStyle, _colorFill, _colUpLine, _colDnLine, _colUpFill, _colDnFill) Plots the linear regression line and its deviations, with configurable styles and fill. Parameters: _len (int) : (int) The lookback period for the linear regression. _y1 (float) : (float) The starting y-value of the regression line. _y2 (float) : (float) The ending y-value of the regression line. _slope (float) : (float) The slope of the regression line (used to determine line color). _devTop (float) : (float) The top deviation to add to the line. _devBot (float) : (float) The bottom deviation to subtract from the line. _scaleTypeLog (bool) : (bool) Use a log scale if true; otherwise, linear scale. _lineWidth (int) : (int) The width of the plotted lines. _extendLines (string) : (string) How lines should extend (none, left, right, both). _channelStyle (string) : (string) The style of the channel lines (solid, dashed, dotted). _colorFill (bool) : (bool) Whether to fill the space between the top and bottom deviation lines. _colUpLine (color) : (color) Line color when slope is positive. _colDnLine (color) : (color) Line color when slope is negative. _colUpFill (color) : (color) Fill color when slope is positive. _colDnFill (color) : (color) Fill color when slope is negative.ライブラリTanHefの投稿2214
VIDYA ProTrend Multi-Tier ProfitHello! This time is about a trend-following system. VIDYA is quite an interesting indicator that adjusts dynamically to market volatility, making it more responsive to price changes compared to traditional moving averages. Balancing adaptability and precision, especially with the more aggressive short trade settings, challenged me to fine-tune the strategy for a variety of market conditions. █ Introduction and How it is Different The "VIDYA ProTrend Multi-Tier Profit" strategy is a trend-following system that combines the VIDYA (Variable Index Dynamic Average) indicator with Bollinger Bands and a multi-step take-profit mechanism. Unlike traditional trend strategies, this system allows for more adaptive profit-taking, adjusting for long and short positions through distinct ATR-based and percentage-based targets. The innovation lies in its dynamic multi-tier approach to profit-taking, especially for short trades, where more aggressive percentages are applied using a multiplier. This flexibility helps adapt to various market conditions by optimizing trade management and profit allocation based on market volatility and trend strength. BTCUSD 6hr performance █ Strategy, How it Works: Detailed Explanation The core of the "VIDYA ProTrend Multi-Tier Profit" strategy lies in the dual VIDYA indicators (fast and slow) that analyze price trends while accounting for market volatility. These indicators work alongside Bollinger Bands to filter trade entries and exits. 🔶 VIDYA Calculation The VIDYA indicator is calculated using the following formula: Smoothing factor (𝛼): alpha = 2 / (Length + 1) VIDYA formula: VIDYA(t) = alpha * k * Price(t) + (1 - alpha * k) * VIDYA(t-1) Where: k = |Chande Momentum Oscillator (MO)| / 100 🔶 Bollinger Bands as a Volatility Filter Bollinger Bands are calculated using a rolling mean and standard deviation of price over a specified period: Upper Band: BB_upper = MA + (K * stddev) Lower Band: BB_lower = MA - (K * stddev) Where: MA is the moving average, K is the multiplier (typically 2), and stddev is the standard deviation of price over the Bollinger Bands length. These bands serve as volatility filters to identify potential overbought or oversold conditions, aiding in the entry and exit logic. 🔶 Slope Calculation for VIDYA The slopes of both fast and slow VIDYAs are computed to assess the momentum and direction of the trend. The slope for a given VIDYA over its length is: Slope = (VIDYA(t) - VIDYA(t-n)) / n Where: n is the length of the lookback period. Positive slope indicates bullish momentum, while negative slope signals bearish momentum. LOCAL picture 🔶 Entry and Exit Conditions - Long Entry: Occurs when the price moves above the slow VIDYA and the fast VIDYA is trending upward. Bollinger Bands confirm the signal when the price crosses the upper band, indicating bullish strength. - Short Entry: Happens when the price drops below the slow VIDYA and the fast VIDYA trends downward. The signal is confirmed when the price crosses the lower Bollinger Band, showing bearish momentum. - Exit: Based on VIDYA slopes flattening or reversing, or when the price hits specific ATR or percentage-based profit targets. 🔶 Multi-Step Take Profit Mechanism The strategy incorporates three levels of take profit for both long and short trades: - ATR-based Take Profit: Each step applies a multiple of the ATR (Average True Range) to the entry price to define the exit point. The first level of take profit (long): TP_ATR1_long = Entry Price + (2.618 * ATR) etc. █ Trade Direction The strategy offers flexibility in defining the trading direction: - Long: Only long trades are considered based on the criteria for upward trends. - Short: Only short trades are initiated in bearish trends. - Both: The strategy can take both long and short trades depending on the market conditions. █ Usage To use the strategy effectively: - Adjust the VIDYA lengths (fast and slow) based on your preference for trend sensitivity. - Use Bollinger Bands as a filter for identifying potential breakout or reversal scenarios. - Enable the multi-step take profit feature to manage positions dynamically, allowing for partial exits as the price reaches specified ATR or percentage levels. - Leverage the short trade multiplier for more aggressive take profit levels in bearish markets. This strategy can be applied to different asset classes, including equities, forex, and cryptocurrencies. Adjust the input parameters to suit the volatility and characteristics of the asset being traded. █ Default Settings The default settings for this strategy have been designed for moderate to trending markets: - Fast VIDYA Length (10): A shorter length for quick responsiveness to price changes. Increasing this length will reduce noise but may delay signals. - Slow VIDYA Length (30): The slow VIDYA is set longer to capture broader market trends. Shortening this value will make the system more reactive to smaller price swings. - Minimum Slope Threshold (0.05): This threshold helps filter out weak trends. Lowering the threshold will result in more trades, while raising it will restrict trades to stronger trends. Multi-Step Take Profit Settings - ATR Multipliers (2.618, 5.0, 10.0): These values define how far the price should move before taking profit. Larger multipliers widen the profit-taking levels, aiming for larger trend moves. In higher volatility markets, these values might be adjusted downwards. - Percentage Levels (3%, 8%, 17%): These percentage levels define how much the price must move before taking profit. Increasing the percentages will capture larger moves, while smaller percentages offer quicker exits. - Short TP Multiplier (1.5): This multiplier applies more aggressive take profit levels for short trades. Adjust this value based on the aggressiveness of your short trade management. Each of these settings directly impacts the performance and risk profile of the strategy. Shorter VIDYA lengths and lower slope thresholds will generate more trades but may result in more whipsaws. Higher ATR multipliers or percentage levels can delay profit-taking, aiming for larger trends but risking partial gains if the trend reverses too early.ストラテジーPresentTradingの投稿66610
RSI Slope Filtered Signals [UAlgo]The "RSI Slope Filtered Signals " is a technical analysis tool designed to enhance the accuracy of RSI (Relative Strength Index) signals by incorporating slope analysis. This indicator not only considers the RSI value but also analyzes the slope of the RSI over a specified number of bars, providing a more refined signal that accounts for the momentum and trend strength. By utilizing both positive and negative slope arrays, the indicator dynamically adjusts its thresholds, ensuring that signals are responsive to changing market conditions. This tool is particularly useful for traders looking to identify overbought and oversold conditions with a higher degree of precision, filtering out noise and providing clear visual cues for potential market reversals. 🔶 Key Features Dynamic Slope Analysis: Measures the slope of RSI over a customizable number of bars, offering insights into the momentum and trend direction. Adaptive Thresholds: Uses historical slope data to calculate dynamic thresholds, adjusting signal sensitivity based on market conditions. Normalized Slope Calculation: Normalizes the slope values to provide a consistent measure across different market conditions, making the indicator more versatile. Clear Signal Visualization: The indicator plots both positive and negative normalized slopes with color gradients, visually representing the strength of the trend. Overbought and Oversold Signals: Plots overbought and oversold signals directly on the chart when the calculated value reaches the user-specified threshold, helping traders identify potential reversal points. Customizable Settings: Allows users to adjust the RSI length, slope measurement bars, and lookback periods, providing flexibility to tailor the indicator to different trading strategies. 🔶 Interpreting the Indicator The "RSI Slope Filtered Signals " indicator is designed to be easy to interpret. Here's how you can use it: Normalized Slope: The indicator plots the normalized slope of the RSI, with values above zero indicating positive momentum and values below zero indicating negative momentum. A higher positive slope suggests a strong upward trend, while a deeper negative slope indicates a strong downward trend. Reversal Signals: The indicator plots several horizontal lines at different thresholds (+3, +2, +1, 0, -1, -2, -3). These levels are used to gauge the strength of the momentum based on the normalized slope. For example, a normalized slope crossing above the +2 threshold may indicate a strong bullish trend, while crossing below the -2 threshold may suggest a strong bearish trend. These thresholds help in understanding the intensity of the current trend and provide context for interpreting the indicator's signals. This indicator generates overbought and oversold signals not solely based on the RSI entering extreme levels (above 70 for overbought and below 30 for oversold), but also by considering the behavior of the normalized slope relative to specific thresholds. Specifically, the Overbought Signal (🔽) is triggered when the RSI is above 70 and the normalized slope from the previous bar is greater than or equal to the upper threshold, with the current slope being lower than the previous slope, indicating a potential bearish reversal as momentum may be slowing down. Similarly, the Oversold Signal (🔼) is generated when the RSI is below 30 and the normalized slope from the previous bar is less than or equal to the lower threshold, with the current slope being higher than the previous slope, signaling a potential bullish reversal as the downward momentum may be weakening. Area Plots: The indicator also plots the positive and negative slopes as filled areas, providing a quick visual cue for the strength and direction of the trend. Green areas represent positive slopes (upward momentum), while red areas represent negative slopes (downward momentum). By combining these elements, the "RSI Slope Filtered Signals " provides a comprehensive view of the market's momentum, helping traders make more informed decisions by filtering out false signals and focusing on the significant trends. 🔶 Disclaimer Use with Caution: This indicator is provided for educational and informational purposes only and should not be considered as financial advice. Users should exercise caution and perform their own analysis before making trading decisions based on the indicator's signals. Not Financial Advice: The information provided by this indicator does not constitute financial advice, and the creator (UAlgo) shall not be held responsible for any trading losses incurred as a result of using this indicator. Backtesting Recommended: Traders are encouraged to backtest the indicator thoroughly on historical data before using it in live trading to assess its performance and suitability for their trading strategies. Risk Management: Trading involves inherent risks, and users should implement proper risk management strategies, including but not limited to stop-loss orders and position sizing, to mitigate potential losses. No Guarantees: The accuracy and reliability of the indicator's signals cannot be guaranteed, as they are based on historical price data and past performance may not be indicative of future results.インジケーターUAlgoの投稿更新済 22315