OPEN-SOURCE SCRIPT
KNN Adaptive Cycles

█ OVERVIEW
An adaptive Stochastic RSI whose lookback lengths are driven by the market's measured dominant cycle period, further refined in real time by a K-Nearest Neighbors machine learning layer. Rather than accepting a fixed RSI or Stochastic length, the indicator continuously measures the dominant cycle in price using two independent spectral methods, then uses KNN to anticipate where the cycle is heading and to condition the oscillator output against historical outcomes — so the indicator adapts to what the market is actually doing, not what a static setting assumes it should be.
█ CYCLE DETECTION
The indicator measures the dominant cycle period using two independent methods from the digital signal processing work of John Ehlers, who treated price as a waveform and applied engineering filters to extract its underlying structure.
Autocorrelation Periodogram
Computes Pearson correlation across lags from the minimum to maximum period range, identifying the lag at which price most strongly repeats. Returns a correlation coefficient used directly as a confidence score.
Goertzel / DFT Power Spectrum
A frequency-domain scan that computes spectral power at each candidate period and selects the one carrying the most energy. Independent of the autocorrelation method, giving two mathematically distinct perspectives on the same cycle.
Before measurement, price is conditioned with Ehlers' filter set: a Highpass filter to remove the trend component, a Super Smoother for anti-aliasing, and an optional Bandpass pre-filter to isolate the cycle band. In AC + DFT (Confirmed) mode the two estimates are cross-checked, with each method weighted by its agreement strength and the AC correlation coefficient before blending into a single confirmed period. Single-method modes run the selected method at full per-bar resolution.
█ KNN MACHINE LEARNING
Two independent KNN nearest-neighbor routines operate on top of the cycle and signal layers. Both use weighted Euclidean distance across feature vectors, a 1/distance-weighted outcome average across K neighbors, and ALMA smoothing on the output bias.
Period KNN
Searches history for bars whose cycle state most closely resembles the current bar — matching on current period, rate of change, stability streak, confidence score, and volatility regime. Observes what the period actually became Forward Bars later at each neighbor, then blends that prediction into the current period estimate before final smoothing. Helps the indicator anticipate cycle transitions rather than just react to them.
Signal KNN
Searches history for bars whose StochRSI context most closely resembles now — matching on K level, K−D histogram, K slope, volatility regime, OB/OS proximity, and D line. Observes the forward price outcome at each neighbor and blends the resulting bias into the K line before D smoothing, so D inherits the correction naturally.
█ FEATURES
Cycle detection
• Dual spectral cycle detection — AC and DFT run in parallel with a 0–100% confidence score reflecting method agreement
• Confidence-weighted period blending — each method weighted by agreement and correlation strength, smoothed into one adaptive period
• Single-method modes — Optional select Autocorrelation Only or DFT Only run for faster loading
• Optional Performance Throttle — cadence-limited spectral scans for the AC + DFT mode
KNN layer
• Period KNN — anticipates cycle transitions by learning from historical cycle states and their forward outcomes
• Signal KNN — conditions the K line against historically similar StochRSI contexts and their forward price outcomes
• Per-feature importance weights for both KNN routines — tunable to emphasize what matters most on a given instrument
• ALMA-smoothed bias output — configurable length, offset, and sigma
An adaptive Stochastic RSI whose lookback lengths are driven by the market's measured dominant cycle period, further refined in real time by a K-Nearest Neighbors machine learning layer. Rather than accepting a fixed RSI or Stochastic length, the indicator continuously measures the dominant cycle in price using two independent spectral methods, then uses KNN to anticipate where the cycle is heading and to condition the oscillator output against historical outcomes — so the indicator adapts to what the market is actually doing, not what a static setting assumes it should be.
█ CYCLE DETECTION
The indicator measures the dominant cycle period using two independent methods from the digital signal processing work of John Ehlers, who treated price as a waveform and applied engineering filters to extract its underlying structure.
Autocorrelation Periodogram
Computes Pearson correlation across lags from the minimum to maximum period range, identifying the lag at which price most strongly repeats. Returns a correlation coefficient used directly as a confidence score.
Goertzel / DFT Power Spectrum
A frequency-domain scan that computes spectral power at each candidate period and selects the one carrying the most energy. Independent of the autocorrelation method, giving two mathematically distinct perspectives on the same cycle.
Before measurement, price is conditioned with Ehlers' filter set: a Highpass filter to remove the trend component, a Super Smoother for anti-aliasing, and an optional Bandpass pre-filter to isolate the cycle band. In AC + DFT (Confirmed) mode the two estimates are cross-checked, with each method weighted by its agreement strength and the AC correlation coefficient before blending into a single confirmed period. Single-method modes run the selected method at full per-bar resolution.
█ KNN MACHINE LEARNING
Two independent KNN nearest-neighbor routines operate on top of the cycle and signal layers. Both use weighted Euclidean distance across feature vectors, a 1/distance-weighted outcome average across K neighbors, and ALMA smoothing on the output bias.
Period KNN
Searches history for bars whose cycle state most closely resembles the current bar — matching on current period, rate of change, stability streak, confidence score, and volatility regime. Observes what the period actually became Forward Bars later at each neighbor, then blends that prediction into the current period estimate before final smoothing. Helps the indicator anticipate cycle transitions rather than just react to them.
Signal KNN
Searches history for bars whose StochRSI context most closely resembles now — matching on K level, K−D histogram, K slope, volatility regime, OB/OS proximity, and D line. Observes the forward price outcome at each neighbor and blends the resulting bias into the K line before D smoothing, so D inherits the correction naturally.
█ FEATURES
Cycle detection
• Dual spectral cycle detection — AC and DFT run in parallel with a 0–100% confidence score reflecting method agreement
• Confidence-weighted period blending — each method weighted by agreement and correlation strength, smoothed into one adaptive period
• Single-method modes — Optional select Autocorrelation Only or DFT Only run for faster loading
• Optional Performance Throttle — cadence-limited spectral scans for the AC + DFT mode
KNN layer
• Period KNN — anticipates cycle transitions by learning from historical cycle states and their forward outcomes
• Signal KNN — conditions the K line against historically similar StochRSI contexts and their forward price outcomes
• Per-feature importance weights for both KNN routines — tunable to emphasize what matters most on a given instrument
• ALMA-smoothed bias output — configurable length, offset, and sigma
نص برمجي مفتوح المصدر
بروح TradingView الحقيقية، قام مبتكر هذا النص البرمجي بجعله مفتوح المصدر، بحيث يمكن للمتداولين مراجعة وظائفه والتحقق منها. شكرا للمؤلف! بينما يمكنك استخدامه مجانًا، تذكر أن إعادة نشر الكود يخضع لقواعد الموقع الخاصة بنا.
discord.gg/REapC6SGtz
b3artrades@gmail.com
b3artrades@gmail.com
إخلاء المسؤولية
لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.
نص برمجي مفتوح المصدر
بروح TradingView الحقيقية، قام مبتكر هذا النص البرمجي بجعله مفتوح المصدر، بحيث يمكن للمتداولين مراجعة وظائفه والتحقق منها. شكرا للمؤلف! بينما يمكنك استخدامه مجانًا، تذكر أن إعادة نشر الكود يخضع لقواعد الموقع الخاصة بنا.
discord.gg/REapC6SGtz
b3artrades@gmail.com
b3artrades@gmail.com
إخلاء المسؤولية
لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.