Iterative Periodic EnvelopeThe Iterative Periodic Envelope is a phase-conditioned kernel estimator with endogenous dispersion modeling, implemented as a Nadaraya–Watson estimator under a canonical periodic kernel.
The periodic kernel defines similarity through cyclical phase alignment rather than temporal proximity or multi-scale distance decay. Observations contribute to the estimator based on their position within a repeating cycle structure, emphasizing structural recurrence over linear time dependence.
The indicator computes a latent equilibrium using a kernel-weighted mean and a dispersion measure using kernel-weighted variance under the same weighting structure. The resulting envelope reflects cycle-consistent deviation, rather than a conventional volatility band. All values are computed exclusively on closed historical bars using a bounded lookback window, ensuring non-repainting behavior.
This indicator belongs to a broader class of iterative kernel-based envelopes that includes Gaussian and Rational Quadratic variants. All share a common Nadaraya–Watson estimation framework, differentiated by their kernel.
TRADING USES
The Iterative Periodic Envelope is best interpreted as a cycle-aware structural estimator rather than a volatility-based band.
Equilibrium Tracking
The latent equilibrium represents the phase-conditioned central tendency of price under periodic similarity weighting. Oscillations around this level reflect movement within a repeating structural cycle rather than directional drift.
Cycle Regime Structure
The envelope emphasizes repeating structural behavior through phase recurrence weighting. Changes in symmetry, amplitude, or persistence of oscillation around the latent equilibrium may indicate transitions between cyclical regimes.
Mean Reversion Within Cycles
When a stable periodic structure is present, deviations from the latent equilibrium may revert toward phase-consistent levels. This supports mean-reversion behavior that is conditioned on cycle structure rather than purely statistical dispersion.
Structural Extremes
Extreme deviations relative to the envelope correspond to phase-inconsistent states where cyclical structure becomes stretched or destabilized. These conditions often precede transitions such as cycle inversion, expansion, or compression.
State Estimation
The system defines a latent equilibrium as the inferred central cyclical state, with dispersion derived from kernel-weighted variance under identical periodic similarity constraints. This produces a structurally consistent representation of market state.
PERIODIC ENVELOPE CONSTRUCTION
The envelope is constructed using kernel-weighted variance under the same periodic similarity measure used to estimate the latent equilibrium. The latent equilibrium defines the central state estimate and kernel-weighted variance defines dispersion under identical weighting, producing an endogenously determined envelope. The band width is fixed at ±1 kernel standard deviation with no multiplier, ensuring dispersion remains an intrinsic property of the periodic similarity structure rather than an externally imposed scaling parameter.
THEORY
The periodic kernel defines similarity in terms of cyclical phase recurrence rather than linear temporal distance. Observations contribute to the estimator based on alignment within a repeating cycle structure.
The estimator is formulated as a Nadaraya–Watson kernel regression under a canonical periodic kernel, where weights are defined as:
k(i) = exp( -2 · sin²(πi / p) / L² )
Where:
p = period (cycle length)
L = lookback window (bandwidth parameter; effective smoothing scales with L²)
In this MacKay consistent formulation, the lookback window acts as a bandwidth control parameter, governing phase selectivity and structural smoothing. As L increases, the kernel becomes broader, producing stronger smoothing and reduced phase sensitivity. As L decreases, phase selectivity increases and the estimator becomes more locally sensitive to cyclical alignment.
This induces a cyclical similarity structure in which influence concentrates at recurring phase intervals. The resulting estimator defines a latent equilibrium governed by phase alignment rather than temporal proximity. This formulation can be interpreted as a periodic extension of kernel regression on a circular phase manifold.
CALIBRATION
Length (Lookback / Bandwidth)
Controls structural depth of the estimator and acts as the primary kernel bandwidth parameter.
- 50–100: high responsiveness, short-cycle sensitivity
- 150–250: balanced regime stability
- 300+: strong structural smoothing, reduced sensitivity to phase noise
Period (Cycle Length)
Defines the recurrence interval of the kernel and governs phase alignment and cyclical structure. Commonly aligns with dominant market rhythms such as intraday or macro-cycle structure.
- Lower values: faster cycle sensitivity
- Higher values: slower, broader structural cycles
Start At Bar
Offsets the kernel window backward from the most recent bars and excludes newer observations from the estimator. This ensures all calculations are based strictly on closed historical data and preserves non-repainting behavior.
MARKET USAGE
Stock, Forex, Crypto, Commodities, and Indices.
Performance is dependent on the presence of stable cyclical structure; in regimes lacking periodic coherence, the estimator converges toward a smoother, low-information state. Indicator

MESA Adaptive Cycle Engine [MarkitTick]💡 The MESA Adaptive Cycle Engine is an advanced, dynamic trend-following overlay designed to adapt to market volatility and cyclical phases. Unlike traditional moving averages that suffer from significant lag during range-bound periods, this tool leverages digital signal processing to stay aligned with the market's dominant cycle. It features an integrated webhook automation system and a real-time risk management dashboard.
✨ Originality and Utility
Standard exponential or simple moving averages rely on fixed lookback periods, making them inherently flawed when market conditions shift from trending to cycling. This indicator utilizes the MESA (Maximum Entropy Spectral Analysis) Adaptive Moving Average (MAMA) and Following Adaptive Moving Average (FAMA) concepts. By measuring the phase rate of change via a Hilbert Transform, the moving averages mathematically adapt their alpha speeds. Furthermore, this script is uniquely engineered for modern automated trading, featuring a self-cleaning dashboard and dynamically constructed JSON payloads for external execution engines.
🔬 Methodology and Concepts
● The Hilbert Transform
At its core, the script applies a Hilbert Transform to the price source (defaulting to hl2) to extract the real and imaginary components of the market cycle.
● Phase and Period Calculation
By calculating the arctangent of the quadrature and in-phase components, it determines the current phase and dominant cycle period.
● Adaptive Alpha
The phase's rate of change dictates the alpha variable. In trending markets, the phase changes slowly, allowing the alpha to remain near the Fast Limit. In choppy markets, the phase changes rapidly, dropping the alpha toward the Slow Limit to prevent whipsaws.
● Risk Engine
The script establishes automated Stop Loss and Take Profit levels based on an ATR multiplier, updating dynamically upon regime shifts.
🎨 Visual Guide
● MAMA and FAMA Lines
The indicator plots two primary lines: the MAMA line (default Green) and the FAMA line (default Red).
● Regime Fill
The space between MAMA and FAMA is filled with a semi-transparent Bullish color when MAMA is above FAMA, and a Bearish color when MAMA is below FAMA.
● Entry Signals
A small upward triangle is plotted below the bar upon a Golden Cross (Buy Signal), and a downward triangle is plotted above the bar upon a Death Cross (Sell Signal).
● Analytics Dashboard
A table in the bottom-right corner displays the current Market Regime, Phase Volatility (ATR), and the active JSON Payload status.
📖 How to Use
Wait for a confirmed crossover. A Golden Cross (MAMA crossing above FAMA) initiates a Bullish regime, while a Death Cross initiates a Bearish regime.
Use the Regime Fill to hold positions; stay in a long position as long as the fill remains bullish.
Monitor the Dashboard for real-time ATR values to assist with manual trailing stops, or rely on the automated Risk Manager's calculated Take Profit (2x ATR) and Stop Loss (1x ATR).
Non-standard charts (like Heikin Ashi or Renko) will trigger a runtime warning, as cycle measurements rely on standard time-based OHLC data.
⚙️ Inputs and Settings
● MESA DSP Parameters
Price Source: Determines the input data (default hl2).
Fast Limit: The maximum alpha speed, usually set to 0.5.
Slow Limit: The minimum alpha speed, usually set to 0.05.
● Automation & JSON Payload
ATR Multiplier: Controls the width of the Stop Loss and Take Profit levels.
Webhook Action (Long/Short): Defines the string action injected into the outgoing JSON payload.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
The indicator is deeply rooted in digital signal processing (DSP), specifically pioneered for trading by John Ehlers. The framework models market data as a complex waveform. By passing the data through a 4-bar WMA smoother and then applying a Hilbert Transform, the algorithm isolates the in-phase (I) and quadrature (Q) components. This orthogonal relationship allows the script to map the market's analytic signal onto a complex plane, solving for the instantaneous phase angle. The fundamental academic breakthrough here is using the derivative of this phase (the rate of phase change) to govern the exponential smoothing constant (alpha) of the moving average. This ensures the filter's bandwidth dynamically conforms to the signal's spectral density, offering high-fidelity smoothing without the commensurate group delay found in static linear filters.
⚠️ Disclaimer
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. I expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion. Indicator

Market Time Cycle (Machine Learning: K-Means Clustering)🕰️Market Time Cycle (Machine Learning: K-Means Clustering)
▶️Overview
The Market Time Cycle Oscillator is a sophisticated predictive analysis tool designed to decode the "temporal DNA" of financial markets. While conventional oscillators (like RSI or Stochastics) measure price momentum and overbought/oversold levels, this indicator focuses on the Time Domain .
It identifies recurring intervals between market pivots to estimate the mathematical probability of the next reversal point.
By leveraging K-Means Clustering, it doesn't just look for a single cycle but identifies multiple dominant frequencies simultaneously, providing a probabilistic "heat map" for future Pivot Highs and Pivot Lows.
▶️Technical Core: The K-Means Advantage
1. From Rigid Cycles to Dynamic Clusters
Traditional cycle analysis (like Fourier Transforms) often struggles with "noise" and the non-stationary nature of market data. Market cycles are rarely fixed; they expand and contract.
This indicator uses K-Means Clustering, an unsupervised machine learning algorithm, to solve this:
Observation: It measures the bar-index distance between historical pivots.
Clustering: Instead of averaging these distances, K-Means groups them into K distinct clusters (centroids).
Result: It can identify, for example, a short-term 20-bar cycle and a mid-term 60-bar cycle existing at the same time, without them cancelling each other out.
2. Gaussian Probability Waves
Once the dominant cycle lengths (centroids) are identified, the engine doesn't just plot a single line at a fixed future date. It recognizes that "history rhymes but doesn't repeat perfectly."
Mathematical Projection: Each cycle is projected forward from the most recent pivots.
Gaussian Distribution: A Normal (Gaussian) distribution curve is applied to each projection. The peak represents the most likely timing, while the "wings" represent the statistical margin of error.
Aggregation: All probability waves are summed to create the final "Total Probability" cloud seen on the oscillator.
▶️The Bipolar Logic: A Dual-Force Perspective
The indicator is split into two halves to provide a clear view of opposing market forces:
Positive Side (Upper Cloud): Summation of probabilities for a Pivot High. When this cloud peaks, the market is entering a "Time Window" where price historically finds a ceiling and begins to move downward.
Negative Side (Lower Cloud): Summation of probabilities for a Pivot Low. A peak here indicates a high statistical likelihood of a market floor and an upward reversal.
▶️Key Features
ML-Driven Adaptability: The engine retrains its K-Means centroids every time a new pivot is confirmed, allowing it to adapt to "Cycle Compression" or "Cycle Expansion" in real-time.
Multi-Layered Analysis: It distinguishes between "Standard" (trend-aligned) and "Inverse" (counter-trend) patterns, capturing the nuances of complex market structures.
Visibility Scaling: The intensity of the clouds dynamically adjusts based on the current price's position within its recent range, highlighting setups that have both time and price confluence.
Optimized Performance: Features a high-speed caching logic that limits heavy ML calculations to pivot confirmation events, ensuring a lag-free experience even on high-frequency charts.
▶️Settings Explained
Pivot Settings (Left/Right): Determines the "strength" of the pivots used for training. Higher values focus on major macro cycles; lower values focus on micro noise.
Number of Clusters (K): How many different "Cycle Identities" the machine should find. Usually, 2 or 3 is optimal for capturing both short and medium terms.
Distribution Width (Sigma): Controls the "Focus." A lower Sigma makes the peaks very sharp (precise timing), while a higher Sigma provides a broader, safer window.Memory Window: The depth of history used to train the K-Means engine.
Disclaimer
Cycle analysis is a study of mathematical probability. While history provides a map, external fundamental shocks ("Black Swans") can break any cycle. Always utilize rigorous risk management. If you find this ML-based approach valuable, please support the script with a like! Indicator

Indicator

Momentum Cycle Sentry [LuxAlgo]The Momentum Cycle Sentry indicator is a comprehensive momentum visualization tool designed to identify trend cycles, measure volatility extremes, and precisely track retracement phases through a unique multi-layered symmetric architecture.
🔶 USAGE
The indicator provides a high-fidelity view of market "flow" by mirroring price momentum across a zero line, creating a symmetric "cloud" whose width represents the intensity of the current move. It is primarily used to distinguish between strong trending expansion and temporary pullback cycles.
🔹 Trend Identification
Bullish Momentum: The oscillator cloud appears above and below the zero line in a teal (bullish) color.
Bearish Momentum: The oscillator cloud appears in a coral (bearish) color.
Width: An expanding cloud indicates increasing velocity, while a thinning cloud suggests a squeeze or waning interest.
🔹 Momentum Cycle Tracing
One of the core features of this tool is the Neon Path logic. When the indicator detects that momentum is cooling off against the prevailing trend (a retracement cycle):
The background cloud and candle colors dim to signify a "resting" phase in the market.
A Triple-Layer Glow activates directly on the oscillator's curve, making the retracement segments "light up" in a high-intensity version of the trend color.
This glow uses graduated transparency to create a neon-like halo, visualizing the exact path of the pullback as it moves toward the zero line.
Cross (X) markers appear on the zero line to provide a horizontal anchor for the duration of the retracement period.
🔹 Extreme Zones
The indicator features dynamic Overbought (OB) and Oversold (OS) corridors. When the oscillator enters these shaded gradient zones, the trend cycle is considered overextended. Traders can look for the oscillator to curve back toward the zero line as a sign of potential exhaustion or mean reversion.
🔶 DETAILS
🔹 Layered Oscillator Architecture
The script utilizes five distinct layers of Exponential Moving Average (EMA) smoothing applied to a base momentum calculation. This creates a "glow" effect where the inner core reacts to immediate price action while the outer layers represent the broader trend. The symmetric mirroring ensures that the visual weight of the momentum is balanced, making it easier to perceive the total "volume" of the move regardless of direction.
🔹 Dynamic Volatility Corridors
Unlike traditional oscillators with fixed levels (e.g., 70/30), the Momentum Cycle Sentry uses standard deviation-based bands that adapt to current market volatility. This ensures that the overbought and oversold thresholds are relevant to the specific asset and timeframe being traded.
🔶 SETTINGS
🔹 Settings
Base Length: Sets the lookback period for the underlying momentum calculation.
Smoothing: Determines the base EMA smoothing for the multi-layered layers.
Magnitude: A multiplier to scale the vertical height of the oscillator.
Retracement Sensitivity: Adjusts how quickly the script detects a pullback/retracement cycle on the curve.
🔹 Extreme Zones
OB/OS Lookback: The period used for the standard deviation calculation of the volatility bands.
Inner Multiplier: Sets the threshold for the start of the OB/OS corridor.
Outer Multiplier: Sets the threshold for the outer edge of the OB/OS corridor (historical extreme).
🔹 Visuals
Bullish/Bearish Color: Customizes the colors for uptrends and downtrends.
Base Transparency: Adjusts the transparency of the layered cloud effect.
Color Candles: Toggles the synchronization of price chart candles with the oscillator's momentum state.
Indicator

Variable Sine Wave Fit [LuxAlgo]The Variable Sine Wave Fit indicator uses Ordinary Least Squares (OLS) to fit a dynamic, damped, or expanding sine wave with an underlying linear trend to recent price action. This tool aims to identify cyclical patterns and project their potential continuation into the future, providing a mathematical framework for understanding market regimes and turning points. This indicator is subject to repainting and is displayed retrospectively.
🔶 USAGE
The indicator fits a complex trigonometric model to the price data within a user-defined window. The resulting fit is displayed as a solid line over historical bars and transitions into a dashed extrapolation for the forecasted period.
To use the indicator effectively, traders should observe the relationship between the price and the RMSE bands. If the price remains within these bands, the current cyclical model is considered to be tracking the price action effectively. If the price breaks significantly outside, the cycle may be shifting or breaking down.
🔹 Extrema Markers
Small dot markers are placed at the local maxima and minima of the dashed forecast line. These serve as visual guides for the timing of potential future turning points based on the current mathematical fit.
🔹 Market Regime Dashboard
The dashboard provides a real-time summary of the fitted model's characteristics:
State: Classified based on the amplitude behavior (Damped, Expanding, or Constant) and the linear component (Trending or Ranging).
Best Period: The cycle length (in bars) that currently provides the best fit to the data.
RMSE: The Root Mean Square Error, representing the average deviation of price from the fit.
🔶 DETAILS
The script solves for the best parameters of the following equation:
y = e^(λ * t) * (a * sin(ω * t) + b * cos(ω * t)) + m * t + c
Where:
e^(λ * t): The damping/expansion factor. If λ > 0, the cycle is expanding; if λ < 0, it is damping.
a, b: Coefficients determining the phase and initial amplitude of the sine wave.
m * t + c: A linear regression component that accounts for the underlying price trend.
The "Best Period" is determined through a grid search that minimizes the Sum of Squared Errors (SSE), ensuring the frequency (ω) matches the most dominant local cycle within the search range.
🔶 SETTINGS
🔹 Settings
Window Size (N): The number of historical bars used to calculate the fit.
Auto Period: When enabled, the script searches for the best period within the specified min/max range.
Fixed Period (P): The period used if Auto Period is disabled.
Min/Max Search Period: Defines the boundaries for the automatic cycle search.
Forecast Length: The number of bars to project the fit into the future.
RMSE Band Multiplier: Determines the width of the bands surrounding the fit based on the fit error.
🔹 Visuals
Bullish/Bearish Color: Colors used for the fit line and extrema markers based on the final slope.
Band Color: The color of the RMSE-based envelope.
🔹 Dashboard
Dashboard: Toggles the visibility of the data table.
Position: Moves the dashboard to different corners of the chart.
Size: Adjusts the text and table scale.
Indicator

Stochastic Adaptive %D [LuxAlgo]The Stochastic Adaptive %D Difference Oscillator indicator provides a sophisticated alternative to classic momentum oscillators, prioritizing a balance between high-grade smoothing and adaptive reactivity. By calculating the divergence between a pre-smoothed Stochastic %D and a specialized Adaptive %D signal line, this tool highlights momentum shifts with significantly reduced noise while maintaining the ability to react quickly to trend accelerations.
🔶 USAGE
This indicator is designed for traders who require the clarity of a smooth oscillator without the lag typically associated with heavy filtering. The "Difference Oscillator" component serves as the primary visual guide, representing the spread between momentum and its adaptive average.
🔹 Signal Generation
The indicator features three main visual components:
Standard %D Line: A dual-smoothed stochastic calculation that acts as the core momentum measure, plotted as a dotted line.
Adaptive %D Line: A reactive signal line that adjusts its smoothing alpha based on market intensity, plotted as a dashed line.
Difference Oscillator: A histogram-style fill centered at the 50 midline. This represents the momentum "delta"—when price velocity accelerates away from the adaptive baseline, the oscillator expands, providing earlier warning of trend strength or exhaustion.
When the Standard %D leads the Adaptive %D, the oscillator fills green, suggesting bullish momentum. When it lags, it fills red, suggesting bearish momentum. The expansion and contraction of this fill help identify whether a trend is gaining or losing "torque" relative to its adaptive mean.
🔶 DETAILS
The script achieves its unique balance through a specialized architectural approach that focuses on conserving smoothness while remaining reactive to volatile shifts.
🔹 Smoothness Conservation
To eliminate the "jaggedness" often found in standard Stochastics, the indicator applies a pre-smoothing filter (SMA) to the High, Low, and Close sources. This ensures that the foundation of the calculation is filtered for noise before the Stochastic formula is even applied, resulting in much cleaner oscillations.
🔹 Adaptive Reactivity
The Adaptive %D signal line employs a variable alpha smoothing mechanism. The "speed" of the signal line is dynamically linked to the position of the %D relative to the 50 midline.
Trend Extremes: As momentum reaches overbought (80) or oversold (20) zones, the alpha increases. This allows the signal line to track the %D more aggressively, capturing the peak of the move.
Mean Reversion/Ranging: Near the 50 midline, the alpha decreases, making the signal line more "stubborn" and less prone to whipsaws during low-conviction market phases.
🔶 SETTINGS
🔹 Stochastic Settings
Stochastic Length: The lookback period used for the raw stochastic range calculation.
%K Smoothing: Determines the internal smoothing applied to produce the standard %D line.
Price Pre-Smoothing: The length of the SMA applied to price sources before the oscillator is calculated to ensure foundational smoothness.
🔹 Adaptive Smoothing Settings
Attenuation Factor: A sensitivity multiplier that controls the reactivity of the Adaptive %D. Higher values increase the "inertia" of the adaptive calculation, making the signal line more conservative.
🔹 Colors
Standard %D Color: Sets the color for the core momentum dotted line.
Adaptive %D Color: Sets the color for the reactive signal dashed line.
Bullish/Bearish Color: Defines the colors used for the Difference Oscillator's gradient fill.
Indicator

Rolling SSA Oscillator [LuxAlgo]The Rolling SSA Oscillator indicator is a cycle-analysis tool that utilizes Singular Spectrum Analysis (SSA) to decompose price action into its most significant periodic components, providing a real-time view of underlying market rhythms. Unlike traditional lagging oscillators, this script uses eigendecomposition to isolate dominant trends and noise-reduced oscillations for better market timing.
🔶 USAGE
The indicator provides two primary components derived from the price's spectral signature: a Long-Term Periodic component and a Short-Term Periodic component. These can be used to identify trend direction, cyclical reversals, and momentum exhaustion.
🔹 Trading Signals
Trend Direction: When the Long-Term Periodic component (solid line) is above the zero level and colored green, the primary underlying cycle is in an upward phase. Conversely, a red line below zero indicates a downward phase.
Cycle Crosses: Traders can look for the Short-Term Periodic component (dotted line) crossing the Long-Term component or the zero line to anticipate shorter-term shifts in momentum.
Normalization: When the "Normalize" setting is enabled, the components are scaled relative to their combined absolute magnitude. This is particularly useful for identifying extreme cycle peaks regardless of absolute price volatility.
🔶 DETAILS
Singular Spectrum Analysis (SSA) is a powerful non-parametric technique used in time-series analysis. This indicator implements a rolling version of SSA through the following mathematical steps:
Embedding: The price data is mapped into a trajectory matrix using the "Window" length defined in the settings.
Decomposition: A covariance matrix is computed, followed by eigendecomposition to find the eigenvalues and eigenvectors.
Grouping & Reconstruction: The eigenvectors are sorted by their energy (eigenvalues). The script specifically reconstructs the first two components to form the Long-Term trend/cycle and the subsequent two components to form the Short-Term cycle.
Because this script uses matrix.eigenvalues() and matrix.eigenvectors() , it requires significant computation. The "Window" input determines the "resolution" of the cycles; a larger window can capture longer-term rhythms but increases the lag and computational load.
🔶 SETTINGS
Window: Controls the embedding dimension (L). This defines the maximum cycle length the indicator can effectively resolve.
Long Term Periodic: Toggles the visibility of the primary trend-following cycle (Components 1 & 2).
Short Term Periodic: Toggles the visibility of the faster, more reactive cycle (Components 3 & 4).
Normalize: If enabled, adjusts the output so that the combined amplitude of both components stays within a consistent range, making it easier to spot cyclical extremes.
🔹 Dashboard
Dashboard: Toggles the on-screen statistics table.
Position: Determines where the dashboard is displayed (Top Right, Bottom Right, or Bottom Left).
Size: Adjusts the text size within the dashboard.
Indicator

Correlated Sine Oscillator [LuxAlgo]The Correlated Sine Oscillator indicator identifies and isolates cyclical components within price action to generate a normalized, phase-aligned sinusoid that fluctuates between -1 and 1.
🔶 USAGE
The Correlated Sine Oscillator is designed to help traders visualize the underlying rhythm of the market by projecting price data onto a mathematical sine wave. Unlike standard momentum oscillators, this tool uses quadrature components to determine the current "phase" of the market cycle, allowing the oscillator to stay synced with price swings.
🔹 Identifying Cycle Direction
The oscillator fluctuates within a fixed range of -1 to 1, centered around a zero line. Signals are generated based on the crossing of this midpoint to identify shifts in the dominant cycle.
Bullish Signals: When the oscillator crosses above the zero line, a bullish triangle (▲) appears below the price bar, signaling the start of a rising phase in the cycle. Bearish Signals: When the oscillator crosses below the zero line, a bearish triangle (▼) appears above the price bar, signaling the start of a falling phase in the cycle. Cycle Extremes: While signals occur at the midline, values approaching 1 or -1 represent the peak and trough of the identified cycle, respectively.
🔹 The Phase Multiplier
The Phase Multiplier setting is a unique feature that controls how responsively the oscillator adapts to changes in price direction. Since the indicator uses an average of the real and imaginary components to find the phase, increasing this multiplier will result in a smoother, more stable oscillator that is less prone to noise but slightly more lagging. Lowering the multiplier makes the oscillator react faster to price shifts, which can be useful for identifying quick reversals.
🔶 DETAILS
The construction of the Correlated Sine Oscillator follows a sophisticated signal processing workflow:
Detrending: The script first removes the trend by subtracting a Simple Moving Average (SMA) from the closing price. This isolates the high-frequency fluctuations (cycles) around a mean of zero. Quadrature Projection: The detrended price is projected onto both a Sine and Cosine wave (real and imaginary components) based on the user-defined Cycle Period . Phase Estimation: By calculating the arctangent of these components, the script derives the "Dynamic Phase." This tells us exactly where the current price sits within the theoretical cycle. Correlation: Finally, the script generates a synthetic sine wave that is shifted by the calculated phase, ensuring the output is perfectly correlated with the dominant frequency of the price action.
🔶 SETTINGS
Cycle Period: Determines the primary wavelength (in bars) that the indicator looks for in the price data. Setting this to 20 means the oscillator is tuned to find cycles that repeat every 20 bars. Phase Multiplier: A multiplier applied to the Cycle Period to determine the smoothing length of the internal phase components. A higher value leads to a "cleaner" wave, while a lower value follows price more aggressively. Bullish Color: Controls the color of the oscillator and gradient fill when the value is above zero. Bearish Color: Controls the color of the oscillator and gradient fill when the value is below zero. Indicator

Phase Regression Oscillator [LuxAlgo]The Phase Regression Oscillator indicator is a cycle analysis tool that uses an analytical linear least squares fit to extract the instantaneous phase of a specified frequency relative to price action. By solving a system of normal equations on every bar, the script determines the "best fit" sine wave for a rolling window, providing a high-resolution view of the market's cyclical state.
🔶 USAGE
The indicator is designed to identify the current stage of a market cycle by fitting a theoretical sine wave to the most recent price data. Unlike traditional oscillators that rely on simple averages or price extremes, this tool uses regression to find the mathematical phase of the trend.
🔹 Interpreting the Components
Sine Oscillator (Solid Line): This is the primary signal. When the line is positive and green, the cycle is in its ascending or peaking phase. When negative and red, the cycle is in its descending or troughing phase.
Cosine Component (Dotted Line): This represents the "quadrature" or in-phase component. In cycle analysis, the lead/lag relationship between the sine and cosine lines can help traders identify when a cycle is losing momentum or reaching a turning point.
Overbought/Oversold Levels: Dashed horizontal lines indicate levels where the cycle fit has reached extreme mathematical synchronization, often preceding a phase shift or reversal.
🔶 DETAILS
The script employs a Linear Least Squares approach to model price as:
y = a·sin(ωx) + b·cos(ωx) + c
Instead of using a computationally expensive "grid search" to guess the phase, the indicator uses a 3x3 matrix solver (Cramer's Rule) to analytically find the coefficients a , b , and c that minimize the squared error. The phase (φ) is then extracted using the arctangent of the coefficients.
By defining the period as a percentage of the window size, the tool ensures that the regression always looks for a cycle length that is proportional to the observed lookback, making it adaptable across different timeframes and asset classes.
🔶 SETTINGS
🔹 Main Settings
Window Size (N): The rolling lookback period (in bars) used to calculate the regression fit.
Period % of Window: Defines the fixed period (P) of the sine wave as a percentage of the Window Size. A value of 100% means the regression looks for a cycle equal to the window length.
🔹 Levels
Overbought Level: The upper threshold used to identify cycle peaks.
Oversold Level: The lower threshold used to identify cycle troughs.
🔹 Style
Bullish Color: Color for the oscillator when positive, the oversold level, and the upward gradient fill.
Bearish Color: Color for the oscillator when negative, the overbought level, and the downward gradient fill.
Cosine Color: The color of the dotted quadrature reference line.
Zero Line Color: The color of the center baseline.
Indicator

Market Force Oscillator Elite ProMarket Force Oscillator Elite Pro is a single-pane oscillator that combines acceleration, volume-weighted force, trend alignment, divergence logic, and multi-method cycle diagnostics.
How components work together:
- Force engine estimates buy/sell pressure from candle position, relative volume weighting, and optional momentum factor.
- Oscillator core combines acceleration with force and normalizes using robust scale logic (stdev with MAD fallback when stdev is unstable).
- Dynamic levels compute adaptive OB/OS using ATR percent with timeframe-aware auto calibration and a soft-cap transform.
- Trend filter compares LTF and HTF EMA direction before allowing directional signals.
- Signal quality gate combines oscillator magnitude, relative volume, and optional alignment weighting.
- Divergence module uses confirmed pivots with one-shot/cooldown modes.
- Cycle module computes Original Ehlers, Zero-Crossing, Peak-to-Peak, Autocorrelation, and Composite estimates.
What is new/original in this version (from current code):
- Multi-method cycle detector with Composite mode.
- Timeframe-aware ATR auto calibration for dynamic OB/OS behavior.
- ATR soft-cap compression to avoid overly wide bands on higher timeframes.
- Robust oscillator normalization with MAD fallback when stdev becomes outlier-like.
- Oscillator-pane marker anchoring (`location.absolute`) to prevent autoscale distortion from price-anchored shapes.
How to Use quickstart
1. Add the script to chart and start with `Preset = Balanced`.
2. Set `Cycle Detector Mode = Composite` for combined cycle diagnostics.
3. Enable `Show Detected Cycle (data window)` to inspect cycle outputs.
4. Enable advanced settings only if you need to tune quality gates, trend filter, and cooldowns.
5. Configure alerts from the 5 built-in alert conditions after threshold tuning.
Indicator

Cycle Spectrogram [LuxAlgo]The Cycle Spectrogram indicator is a spectral analysis tool that visualizes the power of various price cycles to identify dominant periodicities and market rhythms.
🔶 USAGE
The indicator provides a technical visualization of spectral density over time by decomposing price action into multiple cycle bands. This allows traders to identify whether the market is currently influenced by short-term noise or long-term structural cycles.
🔹 Spectrogram Interpretation
The spectrogram consists of 30 rows, each representing a specific cycle period. The vertical axis is logarithmically scaled between the "Minimum Period" and "Maximum Period" settings.
Color Intensity: Brighter or more saturated colors (depending on the selected theme) indicate higher spectral power or "energy" at that specific cycle length. Vertical Position: Higher rows represent longer cycle periods (slower cycles), while lower rows represent shorter periods (faster cycles).
🔹 Dominant Period Tracking
To help identify the most significant cycle at any given time, the script includes a Dominant Period Marker (red cross). This marker tracks the row with the highest energy, providing a real-time estimate of the current market cycle length in bars.
🔹 Dashboard Metrics
A real-time dashboard provides key analytical data:
Current DP: The period (in bars) of the most powerful cycle found in the current bar. Average DP: A 20-period moving average of the dominant period, useful for identifying stable, persistent cycles versus erratic shifts. Lowest Period: A reference for the minimum boundary of the spectral analysis.
🔶 DETAILS
A spectrogram is a visual representation of the spectrum of a signal as it varies with time. This script utilizes a series of Bandpass filters to isolate specific cycle lengths. Each filter is tuned to a period calculated using a logarithmic distribution, ensuring that the analysis covers a wide range of market periodicities without bias toward specific scales.
The "Power" of each cycle is calculated by squaring the output of the bandpass filter and applying a smoothing factor. This process helps filter out transient spikes and provides a cleaner "heat" signature for more reliable cycle identification.
🔶 SETTINGS
🔹 Aesthetics
Theme: Select from several high-contrast color maps, including Viridis, Inferno, Magma, Plasma, Cividis, and Turbo.
🔹 Settings
Minimum Period: The shortest cycle length (in bars) to include in the analysis. Maximum Period: The longest cycle length (in bars) to include in the analysis. Bandwidth: Controls the "focus" or resonance of each cycle band. Lower values result in narrower, more precise detection, while higher values allow for more overlap. Power Smoothing: Determines the amount of smoothing applied to the amplitude. Higher values reduce visual noise but may increase lag in detecting cycle shifts.
🔹 Dashboard
Dashboard: Toggles the visibility of the data table. Position: Moves the dashboard to different corners of the pane. Size: Adjusts the text and cell size of the dashboard. Indicator

Normalized Resonator [LuxAlgo]The Normalized Resonator indicator provides a specialized bandpass oscillator designed to isolate specific market cycles while maintaining a normalized scale for overbought and oversold analysis.
🔶 USAGE
The indicator can be used to identify cyclical turns in the market by isolating a specific frequency (period) and filtering out noise. Traders can use the oscillator to spot potential reversals when the price reaches extreme levels or when the main line crosses its signal line.
🔹 Trend Identification
Beyond reversal signals, the oscillator serves as a momentum and trend filter. When the oscillator is sustained above the zero line, it indicates a bullish cycle where the isolated frequency is currently in an upward phase. Conversely, values below zero indicate a bearish cycle. The distance from the zero line represents the strength of the cycle relative to its recent historical peaks.
🔹 Filtering and Momentum
The "Bandwidth" setting is crucial for practical application. A lower bandwidth (e.g., 0.1 - 0.3) creates a sharper filter that is highly selective of the central period, which is useful for identifying very specific recurring cycles but may increase lag. A wider bandwidth (e.g., 0.5 - 0.8) allows more price movement through, making the oscillator more reactive to momentum shifts and broader market swings.
🔹 Trading Signals
The script features built-in signals that appear on the main chart to highlight potential exhaustion points:
Bullish Reversal: Indicated by a green "▲" label below the price. This occurs when the oscillator crosses above the signal line while below the oversold threshold.
Bearish Reversal: Indicated by a red "▼" label above the price. This occurs when the oscillator crosses below the signal line while above the overbought threshold.
🔹 Combining with Price Action
For the best results, traders should look for confluence between the resonator signals and price action structures. For example, a bullish crossover occurring at a major horizontal support level or a trendline adds significant weight to the signal.
In trending markets, the resonator can be used to "buy the dip" by looking for bullish signals that occur when the higher-timeframe trend is up, rather than attempting to catch every reversal in both directions.
🔶 DETAILS
The script is built upon a digital resonator filter, which is a type of second-order bandpass filter. Unlike standard oscillators that use moving average differences, a resonator is mathematically tuned to "vibrate" at a specific frequency (the Center Period).
🔹 Normalization
Standard bandpass filters often have varying amplitudes depending on market volatility, which makes static levels difficult to use. This script solves this by implementing a normalization process. It calculates the highest absolute peak of the filter output over a rolling lookback period.
By dividing the raw filter output by this peak, the oscillator is squeezed into a range typically between -1 and +1, allowing for consistent Overbought (OB) and Oversold (OS) levels regardless of the asset's price scale or volatility.
🔶 SETTINGS
Center Period: The primary cycle length (in bars) the filter aims to isolate.
Bandwidth: Determines the width of the passband. Lower values result in a very sharp, selective filter. Higher values allow more frequencies to pass.
Lookback Multiplier: Sets the normalization window as a multiple of the Center Period. A value of 1.0 means the peak is searched for over a window equal to the Center Period.
Signal Line Period: The smoothing length for the Signal Line (EMA).
Overbought/Oversold: The threshold levels used to trigger the chart signals.
Signal Size: Adjusts the visual size of the "▲" and "▼" labels on the chart.
Indicator

Singular Spectrum Decomposition [LuxAlgo]The Singular Spectrum Decomposition indicator is a powerful analytical tool that decomposes price action into distinct, interpretable components—Trend, Periodic cycles, and Noise—using the Singular Spectrum Analysis (SSA) methodology.
It provides traders with a clear view of underlying market structures and offers a jump-free, extrapolated trend forecast based on Linear Recurrence Relations (LRR).
Warning: This decomposition is displayed retrospectively ; historical values observed are subject to repainting .
🔶 USAGE
The indicator operates by analyzing a specific window of recent price data to extract its most significant internal dynamics. It splits the "messy" raw price into four visual layers:
Trend (Overlay): The primary low-frequency component, plotted directly on the price chart. This represents the core directional bias of the asset.
Long Term Periodic (P1): The most dominant cyclical component, typically representing major swings or seasonalities.
Short Term Periodic (P2): The second most dominant cycle, capturing faster oscillations and intermediate pullbacks.
Noise: The high-frequency residual data that lacks a consistent pattern, useful for identifying market volatility or "washout" periods.
🔹 Cycle Exhaustion (P1/P2 Extremes)
Traders can monitor the separate indicator pane to identify when cyclical components (P1 and P2) reach historical extremes. When the Long Term Periodic (P1) line begins to curve back toward the zero line after a prolonged extension, it often signals "cycle exhaustion," suggesting that the current swing is losing momentum and a reversal or consolidation may be imminent.
🔹 Trend-Forecast Confluence & Mean Reversion
The dashed Trend extrapolation acts as a projected path for the market's core bias. If the current market price is significantly far from the solid Trend line while the forecast indicates a flattening or reversal, traders can look for mean-reversion opportunities. A price returning to a rising Trend forecast confirms the trend's strength, while a price crossing through a flat Trend forecast suggests a structural shift.
🔹 Timing Entries with Dashboard Metrics
The "Average Period" displayed on the dashboard provides a mathematical blueprint for entry timing. For example, if the Short Term (P2) Average Period is 20 bars, a trader might look for long entries approximately 10 bars after a peak (the expected trough). By aligning these peak-to-trough measurements with the Trend's direction, users can improve the precision of their entries within a trending market.
🔹 Filtering Fakeouts with the Noise Component
The Noise component helps distinguish between high-conviction moves and market "static." A sharp price breakout accompanied by a relatively flat Noise component suggests a sustainable, structurally supported move. Conversely, if a breakout occurs while the Noise component is spiking aggressively, it may indicate a "washout" or a liquidity-driven fakeout that lacks a fundamental trend shift.
🔶 DETAILS
The script implements a full SSA pipeline: Embedding (creating a trajectory matrix), Singular Value Decomposition (via eigendecomposition of the covariance matrix), and Diagonal Averaging (reconstructed the time series).
🔹 Jump-Free Extrapolation
A common issue with LRR-based forecasts is a vertical "jump" at the connection point between historical data and the forecast. This tool solves this by calculating the relative deltas of the LRR projection and anchoring them to the final value of the smoothed SSA reconstruction. This ensures a seamless visual transition while maintaining the mathematical integrity of the projected trajectory.
🔹 Dashboard Metrics
The indicator includes a real-time dashboard that calculates the "Average Period" of the periodic components using zero-crossing detection. This allows traders to quantify the frequency of cycles (e.g., a 40-bar cycle vs. a 15-bar cycle) without manual measurement.
🔶 SETTINGS
Window Length (L): The embedding window. Larger values capture longer cycles and provide a smoother trend, but may increase lag in the decomposition.
Buffer Length (N): The number of recent bars used for the static decomposition.
Forecast Length: The number of bars to extrapolate the Trend component into the future.
Show Trend on Price: Toggles the visibility of the reconstructed trend line on the main chart.
Show Periodic/Noise: Toggles the visibility of the individual sub-components in the indicator pane.
Show Extrapolation: Enables or disables the dashed forecast line for the trend.
Dashboard Settings: Controls the visibility, position, and size of the metrics table.
Indicator

Harmonic Resonance Oscillator [LuxAlgo]The Harmonic Resonance Oscillator indicator provides a specialized oscillator that decomposes price action into multiple harmonic cycles to identify confluence in market rotations.
By isolating short, medium, and long-term frequencies, the tool aims to pinpoint exhausted price movements and potential reversal zones through the concept of cyclic resonance.
🔶 USAGE
The Harmonic Resonance Oscillator can be used to identify market turning points by observing when the aggregate cycle resonance reaches extreme levels. Unlike standard oscillators that rely on a single lookback period, this tool aggregates multiple filtered cycles to provide a more robust view of market momentum and exhaustion.
When the oscillator enters the dynamic overbought (upper) or oversold (lower) zones, it indicates that the various price cycles are aligning at an extreme, often preceding a corrective move or a trend reversal.
🔹 Harmonic Multipliers
The script uses a Reference Period combined with three multipliers to define the cycles:
The Short Multiplier captures fast, intraday-style fluctuations.
The Medium Multiplier focuses on the primary trend rhythm.
The Long Multiplier tracks broader market cycles.
When all three cycles reach peak or trough levels simultaneously, the oscillator displays a "resonance" peak, which is highlighted by background coloring if the signal exceeds the dynamic thresholds.
🔶 DETAILS
The indicator is built upon three primary technical pillars:
🔹 Ehlers' Bandpass Filter
At its core, the indicator uses John Ehlers' Cycle decomposition method. The bandpass filter is designed to pass only price components within a specific frequency range while attenuating everything else. This allows the script to "tune in" to specific market rhythms without the lag typically associated with moving averages.
🔹 Normalization & Resonance
Each isolated cycle is normalized onto a scale of 0 to 100 using a specific lookback length. The final "Harmonic Resonance" signal is the arithmetic mean of these three normalized cycles. A value of 50 represents a neutral state, while values approaching 0 or 100 represent extreme harmonic alignment.
🔹 Dynamic Volatility-Adjusted Zones
The Overbought and Oversold thresholds are not static. They adjust dynamically based on the standard deviation of the resonance signal. During periods of high cyclic volatility, the bands expand to require stronger confluence for a signal; during low volatility, the bands contract to stay sensitive to smaller market rotations.
🔶 SETTINGS
🔹 Harmonic Settings
Reference Period: The base period used to calculate the harmonic cycles.
Short Multiplier: Multiplier applied to the reference period for the short-term cycle.
Medium Multiplier: Multiplier applied to the reference period for the medium-term cycle.
Long Multiplier: Multiplier applied to the reference period for the long-term cycle.
Bandwidth: Controls the "tightness" of the bandpass filter. Lower values isolate specific cycles more precisely.
🔹 Normalization Settings
Normalization Lookback: The window used to scale the cycles and calculate the volatility of the resonance signal.
🔹 Overbought / Oversold Control
Overbought Threshold: The base level for the upper dynamic zone (default 80).
Oversold Threshold: The base level for the lower dynamic zone (default 20).
🔹 Style
Bullish Color: Color of the oscillator when above the 50 midpoint.
Bearish Color: Color of the oscillator when below the 50 midpoint.
Overbought Color: Color of the upper dynamic threshold.
Oversold Color: Color of the lower dynamic threshold.
Show Background Highlighting: Toggles the background coloring when resonance reaches extreme levels.
Indicator

blueprint_ephemeris_lib🔭 Library blueprint_ephemeris_lib
Consolidated planetary ephemeris library with improved accuracy. Supersedes previous individual planet libraries (lib_vsop_core, lib_vsop_mercury, lib_vsop_venus, etc.). One import gives you geocentric/heliocentric positions for all 10 solar system bodies.
█ ACCURACY — VALIDATED AGAINST JPL DE440
Every planetary body was validated against NASA's DE440 ephemeris (via Skyfield). Using only 1.6% of the full VSOP87D theory (511 of 31,577 terms), this library achieves sub-arcminute accuracy for all planets:
Sun 0.004° (14 arcseconds)
Mercury 0.005° (18")
Venus 0.006° (22")
Mars 0.010° (36")
Jupiter 0.007° (25")
Saturn 0.009° (32")
Uranus 0.013° (47")
Neptune 0.017° (61")
Moon 0.062° (3.7')
Pluto 0.059° (3.5')
All bodies under 0.1° RMS — more than sufficient for aspect calculations, ingress timing, and planetary line work. The Sun is accurate to 14 arcseconds using a truncated series that fits entirely inside Pine Script's token limits.
█ WHAT'S NEW (V2)
The original ephemeris required 11 chained library imports. A full validation audit uncovered critical coefficient errors and motivated this rewrite:
• L1 Precession Fix — All 8 VSOP87 planets had incorrect longitude rate coefficients (VSOP87B values instead of VSOP87D). Each was missing +0.24382 rad/millennium of general precession. This single correction reduced error from ~0.75° to < 0.1° across the board.
• 28% Smaller — 4,300 lines across 11 files → ~3,100 lines in 1 file.
• Single Import — No dependency chain. Faster execution.
• Moon Improvements — Functions accept raw `time` directly. Node functions renamed with explicit north/south designation.
█ THEORIES
VSOP87D (Bretagnon & Francou, 1988) — Mercury through Neptune
511 truncated terms out of 31,577 total (1.6%). Heliocentric spherical
coordinates in the ecliptic of date.
ELP2000-82 (Chapront-Touzé & Chapront, 1983) — Moon
91 terms (48 longitude + 43 latitude) from Meeus Chapter 47.
Meeus Series (Meeus, 1998) — Pluto
Analytical series from "Astronomical Algorithms" Ch. 37.
Valid ±1 century from J2000.
█ HOW TO USE
Import the library:
import BlueprintResearch/blueprint_ephemeris_lib/1 as eph
Basic — plot a planet's geocentric longitude and declination:
float jupiter_lon = eph.get_longitude(eph.Planet.Jupiter, time, true)
float jupiter_decl = eph.get_declination(eph.Planet.Jupiter, time)
plot(jupiter_lon, "Jupiter Geo Lon", color.yellow)
plot(jupiter_decl, "Jupiter Decl", color.red)
Retrograde detection:
bool mercury_retro = eph.is_retrograde(eph.Planet.Mercury, time)
bgcolor(mercury_retro ? color.new(color.red, 90) : na)
Moon nodes and declination:
float north_node = eph.get_mean_north_node_lon(time)
float south_node = eph.get_mean_south_node_lon(time)
float moon_decl = eph.get_declination(time)
plot(north_node, "North Node", color.green)
plot(south_node, "South Node", color.purple)
plot(moon_decl, "Moon Declination", color.orange)
Dynamic planet selection from input:
string planet_str = input.string("Sun", "Planet", options= )
eph.Planet p = eph.string_to_planet(planet_str)
float geo = eph.get_longitude(p, time, true)
float helio = eph.get_longitude(p, time, false)
float speed = eph.get_speed(p, time)
plot(geo, "Geocentric", color.yellow)
plot(helio, "Heliocentric", color.blue)
plot(speed * 100, "Speed x100", color.white)
All functions accept PulseWire's `time` variable directly.
█ FUNCTIONS
Unified API (all planets):
`get_longitude(Planet, time, preferGeo)` — geo or heliocentric longitude
`get_declination(Planet, time)` — equatorial declination
`get_speed(Planet, time)` — longitude speed (°/day)
`is_retrograde(Planet, time)` — true when retrograde
`string_to_planet(string)` — name to enum
Averages :
`get_avg6_geo_lon` / `get_avg6_helio_lon` — Mercury–Saturn
`get_avg8_geo_lon` / `get_avg8_helio_lon` — Mercury–Neptune
Moon (direct access):
`get_geo_ecl_lon(time)` · `get_geo_ecl_lat(time)` · `get_declination(time)`
`get_mean_north_node_lon(time)` · `get_mean_south_node_lon(time)`
`get_true_north_node_lon(time)` · `get_true_south_node_lon(time)`
`get_north_node_declination(time)` · `get_south_node_declination(time)`
█ LIMITATIONS
• Truncated series — sub-degree accuracy, not sub-arcsecond. More than sufficient for ingress timing and aspect work.
• Validated against DE440 across 250 years (1850–2100). Over this full span, the worst-case VSOP87 planet (Uranus) is 0.017° RMS / 0.043° max error. Ingress dates manually verified back to the late 1800s with consistent accuracy.
• Pluto uses Meeus series, limited to ±1 century from J2000.
• Moon has no speed function.
█ ACKNOWLEDGMENTS
Coefficient validation was made possible by Greg Miller's VSOP87 multi-language project, which provides the complete VSOP87D coefficient tables in accessible formats. His work converting the original Fortran data files into CSV/JSON for multiple languages was essential for identifying the L1 precession errors in the original libraries. Miller released this work into the public domain.
github.com/gmiller123456/vsop87-multilang
References :
• Meeus, Jean. Astronomical Algorithms (2nd Ed., 1998)
• Bretagnon & Francou. VSOP87 Solutions (Astronomy & Astrophysics, 1988)
• Chapront-Touzé & Chapront. ELP2000-82 (1983)
█ OPEN SOURCE
MIT License — part of the Blueprint Research open-source toolkit.
Source code on GitHub
get_geo_ecl_lon(time_)
Returns geocentric ecliptic longitude of the Moon.
Parameters:
time_ (float)
Returns: (float) Longitude in degrees, range [0, 360).
get_geo_ecl_lat(time_)
Returns geocentric ecliptic latitude of the Moon.
Parameters:
time_ (float)
Returns: (float) Latitude in degrees.
get_obliquity_j(time_)
Returns mean obliquity of the ecliptic.
Parameters:
time_ (float)
Returns: (float) Obliquity in degrees.
get_declination(time_)
Returns geocentric equatorial declination of the Moon.
Parameters:
time_ (float)
Returns: (float) Declination in degrees, range where positive is north.
get_declination(p, t)
Returns planetary geocentric equatorial declination.
Parameters:
p (series Planet) : (Planet) Planet to query.
t (float) : (float) Unix timestamp in milliseconds (use built-in 'time' variable).
Returns: (float) Geocentric declination in degrees, range where positive is north.
@note Declination is always geocentric (no heliocentric equivalent in library).
get_mean_north_node_lon(time_)
Returns mean longitude of the Moon's North Node (ascending node).
Parameters:
time_ (float)
Returns: (float) Longitude in degrees, range [0, 360).
@note Mean node is a simple averaged calculation, reducing computational error. Used for declination calculations.
get_mean_south_node_lon(time_)
Returns mean longitude of the Moon's South Node (descending node).
Parameters:
time_ (float)
Returns: (float) Longitude in degrees, range [0, 360). Equals North Node + 180°.
get_true_north_node_lon(time_)
Returns true longitude of the Moon's North Node with perturbation corrections.
Parameters:
time_ (float)
Returns: (float) Longitude in degrees, range [0, 360).
@note True node includes periodic perturbations but formula is low precision. Consider using mean node for consistency.
get_true_south_node_lon(time_)
Returns true longitude of the Moon's South Node with perturbation corrections.
Parameters:
time_ (float)
Returns: (float) Longitude in degrees, range [0, 360). Equals True North Node + 180°.
get_north_node_declination(time_)
Returns declination of the Moon's North Node.
Parameters:
time_ (float)
Returns: (float) Declination in degrees, range (bounded by obliquity).
@note Uses mean node for calculation (more consistent than true node).
get_south_node_declination(time_)
Returns declination of the Moon's South Node.
Parameters:
time_ (float)
Returns: (float) Declination in degrees. Inverse of North Node declination.
normalizeLongitude(lon)
Normalizes any longitude value to the range [0, 360) degrees.
Parameters:
lon (float) : (float) Longitude in degrees (can be any value, including negative or >360).
Returns: (float) Normalized longitude in range [0, 360).
string_to_planet(planetStr)
Converts a planet string identifier to Planet enum value.
Parameters:
planetStr (string) : (string) Planet name (case-insensitive). Supports formats: "Sun", "☉︎ Sun", "sun", "SUN"
Returns: (Planet) Corresponding Planet enum. Returns Planet.Sun if string not recognized.
@note Supported planet strings: Sun, Moon, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto
get_longitude(p, t, preferGeo)
Returns planetary longitude with automatic coordinate system selection.
Parameters:
p (series Planet) : (Planet) Planet to query.
t (float) : (float) Unix timestamp in milliseconds (use built-in 'time' variable).
preferGeo (bool) : (bool) If true, return geocentric; if false, return heliocentric.
Returns: (float) Longitude in degrees, normalized to range [0, 360).
@note Sun and Moon always return geocentric regardless of preference (heliocentric not applicable).
get_speed(p, t)
Returns planetary geocentric longitude speed (rate of change).
Parameters:
p (series Planet) : (Planet) Planet to query.
t (float) : (float) Unix timestamp in milliseconds (use built-in 'time' variable).
Returns: (float) Geocentric longitude speed in degrees per day. Negative values indicate retrograde motion. Returns na for Moon.
@note Speed is always geocentric (no heliocentric equivalent in library). Moon speed calculation not implemented.
get_avg6_geo_lon(t)
get_avg6_geo_lon
@description Returns the arithmetic average of the geocentric longitudes for the six outer planets: Mars, Jupiter, Saturn, Uranus, Neptune, and Pluto.
Parameters:
t (float) : (float) Time in Unix timestamp (milliseconds).
Returns: (float) Average geocentric longitude of the six outer planets in degrees, range [0, 360).
get_avg6_helio_lon(t)
get_avg6_helio_lon
@description Returns the arithmetic average of the heliocentric longitudes for the six outer planets: Mars, Jupiter, Saturn, Uranus, Neptune, and Pluto.
Parameters:
t (float) : (float) Time in Unix timestamp (milliseconds).
Returns: (float) Average heliocentric longitude of the six outer planets in degrees, range [0, 360).
get_avg8_geo_lon(t)
get_avg8_geo_lon
@description Returns the arithmetic average of the geocentric longitudes for all eight classical planets: Mercury, Venus, Mars, Jupiter, Saturn, Uranus, Neptune, and Pluto.
Parameters:
t (float) : (float) Time in Unix timestamp (milliseconds).
Returns: (float) Average geocentric longitude of all eight classical planets in degrees, range [0, 360).
get_avg8_helio_lon(t)
get_avg8_helio_lon
@description Returns the arithmetic average of the heliocentric longitudes for all eight classical planets: Mercury, Venus, Mars, Jupiter, Saturn, Uranus, Neptune, and Pluto.
Parameters:
t (float) : (float) Time in Unix timestamp (milliseconds).
Returns: (float) Average heliocentric longitude of all eight classical planets in degrees, range [0, 360).
is_retrograde(p, t)
Returns true if the planet is currently in retrograde motion (geocentric speed < 0) == 0 = stationary.
Parameters:
p (series Planet) : The planet to check.
t (float) : Time in Unix timestamp (milliseconds).
Returns: true if the planet is in retrograde, false otherwise. Library

Indicator

[COG] NautilusOverview
This indicator combines multiple technical analysis tools to identify high-probability entry points in trending markets. It uses moving average crossovers for trend direction, Bollinger Bands for mean reversion opportunities, and optional filters to reduce false signals and avoid choppy market conditions.
What Makes This Indicator Unique
Heiken Ashi Toggle:
All calculations can be performed on either regular or Heiken Ashi candles with a single click
Multi-Layer Filtering System: Four independent filters work together to improve signal quality
First Entry Detection: Automatically identifies and labels the first signal after a trend change
Anti-Overtrading Protection: Built-in cooldown mechanism prevents signal spam
Core Components
1. Trend Detection (EMA/SMA Crossover)
The indicator uses a 15-period EMA and 50-period SMA to determine market direction. Buy signals only occur when EMA > SMA, and sell signals only when EMA < SMA.
// Trend Detection
bullishTrend = ema15 > sma50
bearishTrend = ema15 < sma50
2. Bollinger Bands Mean Reversion
Entry signals trigger when price touches or penetrates the Bollinger Bands, indicating potential reversal or pullback opportunities within the established trend.
//Bollinger Band Touch Detection
lowerBandTouch = selectedLow <= bbLower
upperBandTouch = selectedHigh >= bbUpper
// Base Entry Conditions
baseBuySignal = bullishTrend and lowerBandTouch and bullishClose
baseSellSignal = bearishTrend and upperBandTouch and bearishClose
3. Candle Confirmation
Signals require a bullish candle close (close > open) for buy signals and bearish candle close (close < open) for sell signals, ensuring momentum alignment.
// Candle Close Type
bullishClose = selectedClose > selectedOpen
bearishClose = selectedClose < selectedOpen
Optional Filters (All Toggleable)
Filter 1: StochRSI Momentum
Ensures entries occur during oversold/overbought conditions. Buy signals require StochRSI < 20, sell signals require StochRSI > 80.
// StochRSI Calculation
rsi = ta.rsi(stochRSISource, rsiLength)
stochRSI_K = ta.sma(ta.stoch(rsi, rsi, rsi, stochRSILength), stochKSmooth)
// Filter Conditions
stochRSIOversoldCondition = stochRSI_K < stochRSIOversold
stochRSIOverboughtCondition = stochRSI_K > stochRSIOverbought
Filter 2: MA Separation (Anti-Chop)
Blocks signals when moving averages are too close together, indicating sideways/choppy market conditions. Default threshold is 1% separation.
// Calculate percentage separation between EMA and SMA
maSeparationPct = (math.abs(ema15 - sma50) / sma50) * 100
// MA separation filter condition
maSeparationValid = maSeparationPct >= maSeparationThreshold
Why this matters: When the 15 EMA and 50 SMA are very close (< 1% apart), the market is typically consolidating. Signals in these conditions have lower win rates.
Filter 3: Cooldown Period
Prevents over-trading by blocking new signals for a specified number of bars (default: 10) after a signal occurs. Buy and sell cooldowns are tracked separately.
// Variables to track the bar index of the last signal
var int lastBuySignalBar = na
var int lastSellSignalBar = na
// Calculate bars since last signal
barsSinceLastBuy = na(lastBuySignalBar) ? 999999 : bar_index - lastBuySignalBar
// Cooldown filter condition
buyCooldownValid = barsSinceLastBuy >= cooldownBars
// Update tracking when signal fires
if buySignal
lastBuySignalBar := bar_index
Advanced Features
Heiken Ashi Mode
Toggle between regular candles and Heiken Ashi candles for all calculations. Heiken Ashi candles smooth price action and can reduce false signals in volatile markets.
// Fetch Heiken Ashi OHLC values
= request.security(
ticker.heikinashi(syminfo.tickerid),
timeframe.period,
)
// Select which OHLC to use based on toggle
selectedClose = useHeikenAshi ? haClose : close
First Entry Detection
Automatically identifies and labels the first signal after a trend change with "1. Trend Cycle Entry" text. This helps traders distinguish between fresh trend entries and continuation signals.
// Detect trend changes
trendChangedToBullish = bullishTrend and not bullishTrend
// Reset tracking when trend changes
if trendChangedToBullish
hadBuySignalInCurrentBullTrend := false
// Identify first signal in new trend
isFirstBuyInTrendCycle = buySignal and not hadBuySignalInCurrentBullTrend
How Signals Are Generated
The indicator uses a layered approach where each condition must be satisfied:
// Apply all filters
buySignal = enableBuySignals and baseBuySignal and
(not enableStochRSIFilter or stochRSIOversoldCondition) and
(not enableMASeparationFilter or maSeparationValid) and
(not enableCooldownFilter or buyCooldownValid)
Buy Signal Requirements:
✅ 15 EMA above 50 SMA (bullish trend)
✅ Candle low touches or goes below lower Bollinger Band
✅ Candle closes bullish (green)
✅ (Optional) StochRSI < 20
✅ (Optional) MA separation > threshold %
✅ (Optional) Cooldown period expired
Sell Signal Requirements:
✅ 15 EMA below 50 SMA (bearish trend)
✅ Candle high touches or goes above upper Bollinger Band
✅ Candle closes bearish (red)
✅ (Optional) StochRSI > 80
✅ (Optional) MA separation > threshold %
✅ (Optional) Cooldown period expired
Customization Options
Moving Averages:
Adjustable EMA length (default: 15)
Adjustable SMA length (default: 50)
Source selection (Close, Open, High, Low, HL2, HLC3, OHLC4)
Bollinger Bands:
Adjustable length (default: 20)
MA type selection (SMA, EMA, SMMA, WMA, VWMA)
Adjustable standard deviation multiplier (default: 2.0)
StochRSI Filter:
Adjustable RSI length (default: 14)
Adjustable Stochastic length (default: 14)
Customizable oversold/overbought levels (default: 20/80)
MA Separation Filter:
Adjustable minimum separation percentage (default: 1.0%)
Cooldown Filter:
Adjustable cooldown period in bars (default: 10)
Visual Settings:
Customizable colors for all elements
Adjustable line widths
Toggle first entry labels on/off
How to Use
Basic Setup: Apply the indicator to your chart. By default, it shows moving averages, Bollinger Bands, and entry signals.
Choose Your Mode: Enable Heiken Ashi mode if you prefer smoother signals and are willing to accept some lag.
Enable Filters: Start with all filters disabled to see raw signals. Then enable filters one by one:
Start with MA Separation filter to avoid choppy markets
Add StochRSI filter to catch better momentum conditions
Add Cooldown filter to prevent over-trading
Adjust Parameters: Tune the parameters based on your timeframe and trading style:
Lower timeframes: Consider shorter cooldown periods
Higher timeframes: May want tighter MA separation requirements
Watch for First Entry Labels: The "1. Trend Cycle Entry" label highlights the highest-probability signals occurring right after trend changes.
Important Notes
⚠️ This indicator does not repaint. All signals appear on closed candles only.
⚠️ Past performance is not indicative of future results. This indicator should be used as part of a complete trading strategy with proper risk management.
⚠️ Filters reduce signal frequency: Enabling multiple filters will significantly reduce the number of signals. This is intentional to improve quality over quantity.
⚠️ Heiken Ashi mode considerations: While HA mode smooths signals, it can also introduce lag. Test both modes on your preferred timeframe.
Best Practices
Always backtest on your preferred timeframe before live trading
Start conservative with tighter filters, then loosen if needed
Pay special attention to "First Entry" signals for highest probability setups
Use appropriate position sizing and stop losses
Consider market conditions: trending vs ranging
Disclaimer
This indicator is for educational purposes only and should not be considered financial advice. Trading involves substantial risk of loss. Always do your own research and consider your risk tolerance before trading. Indicator

Indicator

Indicator

Cyclical Phases of the Market🧭 Overview
“Cyclical Phases of the Market” automatically detects major market cycles by connecting swing lows and measuring the average number of bars between them.
Once it learns the rhythm of past cycles, it projects the next expected cycle (in time and price) using a dashed orange line and a forecast label.
In simple terms:
The indicator shows where the next potential low is statistically expected to occur, based on the timing and depth of previous cycles.
⚙️ Core Logic – Step by Step
1️⃣ Pivot Detection
The script uses the built-in ta.pivotlow() and ta.pivothigh() functions to find local turning points:
pivotLow marks a local swing low, defined by pivotLeft and pivotRight bars on each side.
Only confirmed lows are used to define the major cycle points.
Each new pivot low is stored in two arrays:
cycleLows → price level of the low
cycleBars → bar index where the low occurred
2️⃣ Cycle Identification and Drawing
Every time two consecutive swing lows are found, the indicator:
Calculates the number of bars between them (cycle length).
If that distance is greater than or equal to minCycleBars, it draws a teal line connecting the two lows — visually representing one complete cycle.
These teal lines form the historical cycle structure of the market.
3️⃣ Average Cycle Length
Once there are at least three completed cycles, the script calculates the average duration (mean number of bars between lows).
This value — avgCycleLength — represents the dominant periodicity or cycle rhythm of the market.
4️⃣ Forecasting the Next Cycle
When a valid average cycle length exists, the model projects the next expected cycle:
Time projection:
Adds avgCycleLength to the last cycle’s ending bar index to find where the next low should occur.
Price projection:
Estimates the vertical amplitude by taking the difference between the last two cycle lows (priceDiff).
Adds this same difference to the last low price to forecast the next probable low level.
The result is drawn as an orange dashed line extending into the future, representing the Next Expected Cycle.
5️⃣ Forecast Label
An orange label 🔮 appears at the projected future point showing:
Text:
🔮 Upcoming Cycle Forecast
Price:
The label marks the probable area and timing of the next cyclical low.
(Note: the date/time calculation currently multiplies bar count by 7 days, so it’s designed mainly for daily charts. On other timeframes, that conversion can be adapted.)
📊 How to Read It on the Chart
Visual Element Meaning Interpretation
Teal lines Completed historical cycles (low to low) Show actual periodic rhythm of the market
Orange dashed line Projection of the next expected cycle Anticipated path toward the next cyclical low
Orange label 🔮 Upcoming Cycle Forecast Displays expected price and bar location
Average cycle length Internal variable (bars between lows) Represents the dominant cycle period
📈 Interpretation
When teal segments show consistent spacing, the market is following a stable rhythm → cycles are predictable.
When cycle spacing shortens, the market is accelerating (volatility rising).
When it widens, the market is slowing down or entering accumulation.
The orange dashed line represents the next expected low zone:
If the market drops near this line → cyclical pattern confirmed.
If the market breaks well below → cycle amplitude has increased (trend weakening).
If the market rises above and delays → a new longer cycle may be forming.
🧠 Practical Use
Combine with oscillators (e.g., RSI or TSI) to confirm momentum alignment near projected lows.
Use in conjunction with volume to identify accumulation or exhaustion near the expected turning point.
Compare across timeframes: weekly cycles confirm long-term rhythm; daily cycles refine short-term entries.
⚡ Summary
Aspect Description
Purpose Detect and forecast recurring market cycles
Cycle basis Low-to-Low pivot analysis
Visuals Teal historical cycles + Orange forecast line
Forecast Next expected low (price and time)
Ideal timeframe Daily
Main outputs Average cycle length, next projected cycle, visual cycle map Indicator

Indicator

Indicator
