Relative Strength vs S&P 500 (with RS Rating)Relative Strength vs S&P 500 (with RS Rating) - Plots the S&P 500 and the stock's Relative Strength.
- Optional Show RS New High Markers
指標和策略
Relative Strength % vs SPX (Bar-by-Bar)This gives a bar-by-bar strength against any ticker. Good for picking up Intraday RS
Position calculator (without Forex)That's an excellent idea. Here is a complete description of the simplified Pine Script v6 position size calculator, written in English.
📐 Pine Script V6 Position Size Calculator: Full Description
This Pine Script v6 indicator is a simplified, universal position size calculator designed for traders to quickly determine the exact quantity of an asset (shares, crypto units, etc.) they should trade to maintain a specific risk tolerance. It focuses solely on the most common and accessible calculation method: determining the number of units/contracts.
1. 🎯 Purpose
The primary goal of the script is to answer the question: "Given my total account capital and a defined stop-loss price, how many units of this asset can I buy/sell while only risking a specified percentage of my capital?"
It uses the classic position sizing formula:
Position Size (Units)=Risk Per UnitAccount Risk Amount
2. ⚙️ Indicator Settings (Inputs)
The script provides the user with five key adjustable parameters, all located in the indicator's settings panel:
Parameter Type Default Value Description
Capital total ($) float 10000.0 Your total trading account balance. This is the basis for calculating the risk amount.
Risque par trade (%) float 1.0 The maximum percentage of your capital you are willing to lose on this specific trade.
Prix d'Entree float 150.0 The target entry price for the trade. Since the "use current price" option was removed, this manual price is always used.
Prix Stop Loss float 145.0 The protective stop-loss price where you will exit the trade.
Core USD Liquidity Index### 🏦 Core USD Liquidity Index (v1)
**Purpose:**
The *Core USD Liquidity Index* tracks global **USD liquidity conditions**, the single most important macro driver behind risk-on and risk-off environments.
It combines 4 key monetary metrics into one normalized composite line:
- **FRED:RRPONTSYD** → Reverse Repo balance (⬆️ = liquidity tightening)
- **FRED:WALCL** → Federal Reserve balance sheet (⬆️ = liquidity expansion)
- **FRED:TB3MS** → 3-Month Treasury Bill rate (⬆️ = liquidity tightening)
- **TVC:DXY** → U.S. Dollar Index (⬆️ = global liquidity tightening)
---
### 🧭 **How it Works**
Each metric is normalized and aggregated to create a unified liquidity signal.
The index functions as a **"Liquidity Thermometer"**, visualizing whether dollars are entering or leaving global financial circulation.
---
### 📊 **Interpretation**
| Zone | Meaning | Market Behavior |
|------|----------|-----------------|
| 🟢 Above 0 | Liquidity expanding | Risk assets (BTC, SPX, Tech) strengthen |
| ⚪ Around 0 | Neutral liquidity | Sideways / indecisive markets |
| 🔴 Below 0 | Liquidity contracting | USD strengthens, risk assets weaken |
---
### 💡 **Use Cases**
- Identify **macro liquidity inflection points** ahead of price action
- Track **Fed policy impact** (balance sheet, RRP flows, T-Bill yields)
- Confirm or fade BTC/SPX rallies based on liquidity context
**Recommended timeframe:** Weekly or Daily
**Best pairs:** BTCUSD, SPX500, NASDAQ100, XAUUSD
Normalized EFINormalized EFI (nEFI)
The Normalized EFI (nEFI) is a volume-weighted momentum oscillator that refines the classic Elder Force Index (EFI) by normalizing it against average trading volume. This makes it highly adaptable across different assets, timeframes, and market conditions—especially useful when comparing momentum strength between low- and high-volume instruments.
How It Works:
Relative Price Change: Measures the percentage change in price from the prior bar:
(Close - Close ) / Close
Volume Normalization: Divides current volume by its EMA (default: 30 periods) to create a relative volume factor:
Volume / EMA(Volume, 30)
Normalized Force: Combines the two:
nEFI_raw = PriceChange% × RelativeVolume × 100
Smoothing: Applies an EMA (default: 13 periods) to reduce noise and highlight meaningful trends.
Key Features & Inputs:
Smoothing Length (default: 13): Controls responsiveness of the EMA smoothing.
Volume EMA Length (default: 30): Sets the lookback for volume normalization—longer values create a more stable baseline.
Zero Line Centered: Positive values indicate buying pressure; negative values show selling pressure.
How to Use:
Trend Confirmation: Rising nEFI above zero supports bullish trends; falling below zero confirms bearish moves.
Divergences: Look for price making new highs/lows while nEFI fails to follow — often signals reversal.
Zero Line Crossovers: Cross above zero = potential buy signal; cross below = sell signal.
Extreme Readings: Spikes far from zero may indicate overbought/oversold conditions or climax moves.
Advantages:
Volume-Adaptive: Unlike raw EFI, nEFI scales properly across assets with vastly different volume profiles (e.g., stocks vs. crypto).
Consistent Scaling: Values are intuitive and comparable over time and across symbols.
Reduced Noise: EMA smoothing filters out erratic volume spikes common in illiquid markets.
Cross-Market Friendly: Works reliably on forex, futures, stocks, and crypto without manual recalibration.
Ideal for:
Swing traders, momentum strategies, and multi-asset analysis seeking a clean, interpretable measure of volume-adjusted price force.
GBTimes2Library "GBTimes2"
Library containing all GB (Gartley Butterfly) time values for trading indicators
getTimes()
Returns array of all GB time values in packed format (HHMM)
Returns: Array of integers representing GB times throughout the day
Position Size & Drawdown ManagerThis tool is designed to help traders dynamically adjust their position size and drawdown expectations as their trading capital changes over time. It provides a simple and intuitive way to translate backtest results into real-world position sizing decisions.
Purpose and Functionality
The indicator uses your original backtest parameters — including base capital, base drawdown percentage, and base position size — and your current account balance to calculate how your risk profile changes. It presents two main scenarios:
Lock Drawdown %: Keeps your original drawdown percentage fixed and calculates the new position size required.
Lock Position Size: Keeps your position size unchanged and shows how your drawdown percentage will shift.
Why it’s useful
Many traders face the challenge of scaling their strategies as their account grows or shrinks. This tool makes it easy to visualize the relationship between position sizing, capital, and drawdown. It’s particularly valuable for risk management, portfolio rebalancing, and maintaining consistent exposure when transitioning from backtest conditions to live trading.
How it works
The calculations are displayed in a clean, color-coded table that updates dynamically. This allows you to instantly see how capital fluctuations impact your expected drawdown or position size. You can toggle between light and dark themes and highlight important cells for clarity.
Practical use case
Combine this tool with your TradingView strategy results to better interpret your backtests and adjust your real-world trade sizes accordingly. It bridges the gap between simulated performance and actual account management.
Chart example
The chart included focuses only on this indicator, showing the output table and visual layout clearly without additional scripts or overlays.
LONG SETUP → 8/13/48 EMA + BoSMarks a perfect ENTRY (green "LONG") the exact candle where: 8 EMA crosses above BOTH 13 & 200 EMA
Price is above 200 EMA
Price breaks the most recent swing high (Break of Structure)
Keeps you IN the trade as long as price stays above the 8,13, 48 EMA
Plots EXIT signals:
Red "STOP" label under the last swing low
Orange "EXIT" when price closes below 13 EMA
Purple "EXIT" when price closes below 48 EMA
Use daily timeframe
Volume Cluster Support and Resistance Levels [QuantAlgo]🟢 Overview
This indicator identifies statistically significant support and resistance levels through volume cluster analysis, isolating price zones characterized by elevated trading activity and institutional participation. By quantifying areas where volume concentration exceeded historical norms, it reveals price levels with demonstrated supply-demand imbalances that exhibit persistent influence on subsequent price action. The methodology is asset-agnostic and timeframe-independent, applicable across equities, cryptocurrencies, forex, and commodities from intraday to weekly intervals.
🟢 Key Features
1. Support and Resistance Levels
The indicator scans historical price data to identify bars where volume exceeds a user-defined threshold multiplier relative to the rolling average. For each qualifying bar, a representative price is calculated using the average of high, low, and close. Proximate price levels within a specified percentage range are then aggregated into discrete clusters using volume-weighted averaging, eliminating redundant signals. Clusters are ranked by cumulative volume to determine statistical significance. Finally, the indicator plots horizontal levels at each cluster price: support levels (green) below current price indicate zones where historical buying pressure exceeded selling pressure, while resistance levels (red) above current price mark zones where sellers historically dominated. These levels represent areas of established liquidity and price discovery, where institutional order flow previously concentrated.
The Touch Count (T) metric quantifies historical price interaction frequency, while Total Volume (TV) measures aggregate trading activity at each level, providing objective criteria for assessing level strength and trade execution decisions.
2. Volume Histogram
A histogram appears below the price chart, displaying relative volume for each bar within the lookback period, with bar height scaled to the maximum volume observed. Green bars represent up-periods (close > open) indicating buying pressure, while red bars show down-periods (close < open) indicating selling pressure. This visualization helps you confirm the validity of support/resistance levels by seeing where volume actually spiked, identify accumulation/distribution patterns, and validate breakouts by checking if they occur on above-average volume.
3. Built-in Alerts
Automated alerts trigger when price crosses below support levels or breaks above resistance levels, allowing you to monitor multiple assets without constant chart-watching.
4. Customizable Color Schemes
The indicator provides four preset color configurations (Classic, Aqua, Cosmic, Custom) optimized for visual clarity across different charting environments. Each scheme maintains consistent color mapping for support and resistance zones across both level lines and volume histogram components. The Custom configuration permits full color specification to accommodate individual charting setups, ensuring optimal visual contrast for extended analysis sessions.
Classic:
Aqua:
Cosmic:
Custom:
🟢 Pro Tips
→ Trade entry optimization: Execute long positions at support levels with high touch counts or upon confirmed resistance breakouts accompanied by above-average volume
→ Risk parameter definition: Position stop-loss orders near identified support/resistance zones with statistical significance to minimize premature exits
→ Breakout validation: Require volume confirmation exceeding historical average when price penetrates resistance to filter false breakouts
→ Level strength assessment: Prioritize levels with higher touch counts and total volume metrics for enhanced probability trade setups
→ Multi-timeframe confluence: Synthesize support/resistance levels across multiple timeframes to identify high-conviction zones where daily support aligns with 4-hour resistance structures
Ornstein-Uhlenbeck Trend Channel [BOSWaves]Ornstein-Uhlenbeck Trend Channel - Adaptive Mean Reversion with Dynamic Equilibrium Geometry
Overview
The Ornstein-Uhlenbeck Trend Channel introduces an advanced equilibrium-mapping framework that blends statistical mean reversion with adaptive trend geometry. Traditional channels and regression bands react linearly to volatility, often failing to capture the natural rhythm of price equilibrium. This model evolves that concept through a dynamic reversion engine, where equilibrium adapts continuously to volatility, trend slope, and structural bias - forming a living channel that bends, expands, and contracts in real time.
The result is a smooth, equilibrium-driven representation of market balance - not just trend direction. Instead of static bands or abrupt slope shifts, traders see fluid, volatility-aware motion that mirrors the natural pull-and-release dynamic of market behavior. Each channel visualizes the probabilistic boundaries of fair value, showing where price tends to revert and where it accelerates away from its statistical mean.
Unlike conventional envelopes or Bollinger-type constructs, the Ornstein-Uhlenbeck framework is volatility-reactive and equilibrium-sensitive, providing traders with a contextual map of where price is likely to stabilize, extend, or exhaust.
Theoretical Foundation
The Ornstein-Uhlenbeck Trend Channel is inspired by stochastic mean-reversion processes - mathematical models used to describe systems that oscillate around a drifting equilibrium. While linear regression channels assume constant variance, financial markets operate under variable volatility and shifting equilibrium points. The OU process accounts for this by treating price as a mean-seeking motion governed by volatility and trend persistence.
At its core are three interacting components:
Equilibrium Mean (μ) : Represents the evolving balance point of price, adjusting to directional bias and volatility.
Reversion Rate (θ) : Defines how strongly price is pulled back toward equilibrium after deviation, capturing the self-correcting nature of market structure.
Volatility Coefficient (σ) : Controls how far and how quickly price can diverge from equilibrium before mean reversion pressure increases.
By embedding this stochastic model inside a volatility-adjusted framework, the system accurately scales across different markets and conditions - maintaining meaningful equilibrium geometry across crypto, forex, indices, or commodities. This design gives traders a mathematically grounded yet visually intuitive interpretation of dynamic balance in live market motion.
How It Works
The Ornstein-Uhlenbeck Trend Channel is constructed through a structured multi-stage process that merges stochastic logic with volatility mechanics:
Equilibrium Estimation Core : The indicator begins by identifying the evolving mean using adaptive smoothing influenced by trend direction and volatility. This becomes the live centerline - the statistical anchor around which price naturally oscillates.
Volatility Normalization Layer : ATR or rolling deviation is used to calculate volatility intensity. The output scales the channel width dynamically, ensuring that boundaries reflect current variance rather than static thresholds.
Directional Bias Engine : EMA slope and trend confirmation logic determine whether equilibrium should tilt upward or downward. This creates asymmetrical channel motion that bends with the prevailing trend rather than staying horizontal.
Channel Boundary Construction : Upper and lower bands are plotted at volatility-proportional distances from the mean. These envelopes form the “statistical pressure zones” that indicate where mean reversion or acceleration may occur.
Signal and Lifecycle Control : Channel breaches, mean crossovers, and slope flips mark statistically significant events - exhaustion, continuation, or rebalancing. Older equilibrium zones gradually fade, ensuring a clear, context-aware visual field.
Through these layers, the channel forms a continuously updating equilibrium corridor that adapts in real time - breathing with the market’s volatility and rhythm.
Interpretation
The Ornstein-Uhlenbeck Trend Channel reframes how traders interpret balance and momentum. Instead of viewing price as directional movement alone, it visualizes the constant tension between trending force and equilibrium pull.
Uptrend Phases : The equilibrium mean tilts upward, with price oscillating around or slightly above the midline. Upper band touches signal momentum extension; lower touches reflect healthy reversion.
Downtrend Phases : The mean slopes downward, with upper-band interactions marking resistance zones and lower bands acting as reversion boundaries.
Equilibrium Transitions : Flat mean sections indicate balance or distribution phases. Breaks from these neutral zones often precede directional expansion.
Overextension Events : When price closes beyond an outer boundary, it marks statistically significant disequilibrium - an early warning of exhaustion or volatility reset.
Visually, the OU channel translates volatility and equilibrium into structured geometry, giving traders a statistical lens on trend quality, reversion probability, and volatility stress points.
Strategy Integration
The Ornstein-Uhlenbeck Trend Channel integrates seamlessly into both mean-reversion and trend-continuation systems:
Trend Alignment : Use mean slope direction to confirm higher-timeframe bias before entering continuation setups.
Reversion Entries : Target rejections from outer bands when supported by volume or divergence, capturing snapbacks toward equilibrium.
Volatility Breakout Mapping : Monitor boundary expansions to identify transition from compression to expansion phases.
Liquidity Zone Confirmation : Combine with BOS or order-block indicators to validate structural zones against equilibrium positioning.
Momentum Filtering : Align with oscillators or volume profiles to isolate equilibrium-based pullbacks with statistical context.
Technical Implementation Details
Core Engine : Stochastic Ornstein-Uhlenbeck process for continuous mean recalibration.
Volatility Framework : ATR- and deviation-based scaling for dynamic channel expansion.
Directional Logic : EMA-slope driven bias for adaptive mean tilt.
Channel Composition : Independent upper and lower envelopes with smoothing and transparency control.
Signal Structure : Alerts for mean crossovers and boundary breaches.
Performance Profile : Lightweight, multi-timeframe compatible implementation optimized for real-time responsiveness.
Optimal Application Parameters
Timeframe Guidance:
1 - 5 min : Reactive equilibrium tracking for short-term scalping and microstructure analysis.
15 - 60 min : Medium-range setups for volatility-phase transitions and intraday structure.
4H - Daily : Macro equilibrium mapping for identifying exhaustion, distribution, or reaccumulation zones.
Suggested Configuration:
Mean Length : 20 - 50
Volatility Multiplier : 1.5× - 2.5×
Reversion Sensitivity : 0.4 - 0.8
Smoothing : 2 - 5
Parameter tuning should reflect asset liquidity, volatility, and desired reversion frequency.
Performance Characteristics
High Effectiveness:
Trending environments with cyclical pullbacks and volatility oscillation.
Markets exhibiting consistent equilibrium-return behavior (indices, majors, high-cap crypto).
Reduced Effectiveness:
Low-volatility consolidations with minimal variance.
Random walk markets lacking definable equilibrium anchors.
Integration Guidelines
Confluence Framework : Pair with BOSWaves structural tools or momentum oscillators for context validation.
Directional Control : Follow mean slope alignment for directional conviction before acting on channel extremes.
Risk Calibration : Use outer band violations for controlled contrarian entries or trailing stop management.
Multi-Timeframe Synergy : Derive macro equilibrium zones on higher timeframes and refine entries on lower levels.
Disclaimer
The Ornstein-Uhlenbeck Trend Channel is a professional-grade equilibrium and volatility framework. It is not predictive or profit-assured; performance depends on parameter calibration, volatility regime, and disciplined execution. BOSWaves recommends using it as part of a comprehensive analytical stack combining structure, liquidity, and momentum context.
Oversold Screener · Webhook v3.3#Oversold Screener · Webhook v3.3
US Equities · 15-minute signals · AVWAP entries A–F · Optional CVD gate
## TL;DR
This indicator finds short-term, emotion-driven selloffs in large, liquid US stocks and pings your webhook with a compact alert (symbol + 15-minute close time).
It anchors an Event-AVWAP at the first qualified 15-minute bar after the selloff and proposes disciplined “right-side” entries (A–F) as price mean-reverts back through statistically defined bands. Optional macro fuses and CVD filters help avoid catching knives.
---
## What it does
1. Universe filter (off-chart): You run this on constituents of S&P 500 / Nasdaq-100 / Nasdaq Golden Dragon (or your curated list of healthy companies).
2. Signal (Step-2): On the 15-minute timeframe—including extended hours—the script flags an “oversold event” when:
• Depth: Today’s drawdown vs yesterday’s RTH reference (min of yesterday’s VWAP and Close) is large.
• Relative: The stock underperforms both its market benchmark (e.g., SPY/QQQ) and its sector ETF over the same 16/32×15m windows.
• Macro fuses: If any of the following exceed thresholds, the signal is suppressed: VIX spike, market 16/32×15m selloff, sector 16/32×15m selloff.
• RSI guard: 1-hour RSI is below a configurable level (default 30).
• Cooldown: De-dupes repeated events; you won’t be spammed by the same name intraday.
3. Execution geometry: At the event bar’s close the indicator anchors an AVWAP calculated natively in 15m space and draws ±1σ/±2σ/±3σ bands from a rolling variance of typical price.
4. Entry proposals: It labels A–F entries when price regains key bands after first probing the lower ones (see below). Optional 15m CVD confirmation can be required.
5. Alerts: When the event closes, TradingView raises a single alert with a tiny JSON payload so your downstream AI/service can do the news check and decide.
---
## Why this approach works
• Depth vs yesterday’s RTH reference targets “fresh” dislocations rather than slow trends.
• Relative filters ensure the stock fell much more than both the market and its sector, isolating idiosyncratic panic.
• AVWAP from the event bar approximates the market’s true average position after the shock; band reclaims are robust right-side confirmations.
• Optional CVD (delta volume) catches sell-side exhaustion and buy-side emergence without requiring a full order-book feed.
• Macro fuses (VIX / market / sector) avoid swimming against systemic stress.
---
## Inputs (key)
Bench ETF / Sector ETF
Choose your market (SPY or QQQ) and sector ETF (XLK/XLF/XLY… or KWEB/CQQQ for China tech ADRs).
Depth & relative settings (15-minute space)
• Depth vs prior-day RTH reference: percentage thresholds for 16 and 32 bars.
• Relative to market & sector: underperformance thresholds over 16 and 32 bars.
Macro circuit breakers
• VIX max change (e.g., +8%/+12% over the session)
• Market max 16/32×15m selloff (e.g., −1.5% / −2.5%)
• Sector max 16/32×15m selloff (e.g., −2.0% / −3.0%)
If any one exceeds the limit, the signal is suppressed.
Momentum guard
• RSI(1h) < 30 (configurable).
AVWAP band engine (15m native)
• Bands: ±1σ / ±2σ / ±3σ with EMA smoothing and optional σ cap.
• Settling bars after anchor (default 1–3) to reduce immediate whipsaws.
Entry toggles
• Enable/disable A, B, C, D, E, F individually.
• Optional CVD gate (on/off), lookback window and reversal thresholds.
Housekeeping
• Debounce per ticker and per entry type.
• Entry window length (default 1 week) and per-type cap (show top 3 per event).
• Webhook on/off.
---
## Entries (A–F)
These are right-side confirmations; each requires first touching the prerequisite lower band before reclaiming a higher one.
A Touch ≤ −2σ, then cross up through −1σ (classic exhaustion → relief).
B Touch ≤ −1σ, then reclaim AVWAP (crowd average changes hands).
C Break −1σ up, retest near −1σ within N bars, then bounce (retest confirmation).
D After compression (low ATR%), reclaim AVWAP (coiled spring).
E Touch ≤ −2σ, then reclaim AVWAP after a base (deeper flush → stronger reclaim).
F Touch ≤ −3σ, then cross up through −1σ (capitulation → violent mean reversion).
Optional CVD gate (15m): require sell-pressure exhaustion and a CVD turn-up before validating entries. Defaults are conservative so that A/F remain the highest-quality.
---
## Alert payload (minimal by design)
On event close, one alert is fired with a tiny JSON:
{
"event": "step2_signal",
"symbol": "TSLA",
"ts_15m_ms": 1730879700000
}
Use “Once per bar close” and the 15-minute chart. Your webhook receiver can enrich with fundamentals/news and decide Allow / Hold / Reject, then monitor A–F entries for execution.
---
## How to use
1. Run on your 15-minute chart with extended session enabled.
2. Create one alert per chart (or use TradingView’s multi-chart / watchlist alerts if you have Pro+).
3. Your backend ingests the minimal payload, fetches news and fundamentals, and returns a decision.
4. For Allowed names, watch the on-chart A–F labels; scale in across levels, scale out into upper HVNs/POC or AVWAP give-back.
---
## Defaults that work well
• RSI(1h) < 30
• Depth vs yesterday’s RTH ref: ≤ −4% (16 bars), ≤ −6% (32 bars)
• Relative to market/sector: ≤ −3% (16 bars), ≤ −4% (32 bars)
• Macro fuses: VIX day change ≤ +10%; market ≤ −2.0% / −3.0%; sector ≤ −2.5% / −3.5%
• AVWAP bands: EMA(σ)=3; σ cap off; settle ≥ 1 bar
• CVD gate off initially; enable after you’re comfortable with its behavior.
---
## Notes & limitations
• Indicator, not a strategy: it proposes event points and entries; position sizing and exits are up to you.
• Designed for US equities with ample liquidity; thin names will be noisy.
• Repainting: AVWAP and bands are anchored and do not repaint; entries are evaluated on bar close.
• To keep charts readable, we limit entry labels to the first three occurrences per type within the one-week window.
---
## What’s new in v3.3
• 15-minute event engine (always 15m, independent of the chart you view).
• Depth measured vs yesterday’s RTH VWAP/CLOSE (the lower of the two).
• Removed structure-health (SMA50 coverage) and MA50/200 position checks.
• Macro circuit breakers: VIX + market + sector thresholds; any one trips a fuse.
• RSI guard moved to 1-hour.
• AVWAP bands include ±3σ and new Entry F (−3σ → −1σ reclaim).
• Optional 15m CVD gate for entries.
• Minimal webhook payload for fast downstream AI checks.
• Debounce + entry-window caps to prevent over-labeling and to focus the week after the event.
• Numerous performance and stability tweaks in the 15m security sandbox.
---
## Disclaimer
This is a research tool. It does not constitute investment advice. Test in Replay first, start with small size, and respect your risk.
Machine Learning Moving Average [BackQuant]Machine Learning Moving Average
A powerful tool combining clustering, pseudo-machine learning, and adaptive prediction, enabling traders to understand and react to price behavior across multiple market regimes (Bullish, Neutral, Bearish). This script uses a dynamic clustering approach based on percentile thresholds and calculates an adaptive moving average, ideal for forecasting price movements with enhanced confidence levels.
What is Percentile Clustering?
Percentile clustering is a method that sorts and categorizes data into distinct groups based on its statistical distribution. In this script, the clustering process relies on the percentile values of a composite feature (based on technical indicators like RSI, CCI, ATR, etc.). By identifying key thresholds (lower and upper percentiles), the script assigns each data point (price movement) to a cluster (Bullish, Neutral, or Bearish), based on its proximity to these thresholds.
This approach mimics aspects of machine learning, where we “train” the model on past price behavior to predict future movements. The key difference is that this is not true machine learning; rather, it uses data-driven statistical techniques to "cluster" the market into patterns.
Why Percentile Clustering is Useful
Clustering price data into meaningful patterns (Bullish, Neutral, Bearish) helps traders visualize how price behavior can be grouped over time.
By leveraging past price behavior and technical indicators, percentile clustering adapts dynamically to evolving market conditions.
It helps you understand whether price behavior today aligns with past bullish or bearish trends, improving market context.
Clusters can be used to predict upcoming market conditions by identifying regimes with high confidence, improving entry/exit timing.
What This Script Does
Clustering Based on Percentiles : The script uses historical price data and various technical features to compute a "composite feature" for each bar. This feature is then sorted and clustered based on predefined percentile thresholds (e.g., 10th percentile for lower, 90th percentile for upper).
Cluster-Based Prediction : Once clustered, the script uses a weighted average, cluster momentum, or regime transition model to predict future price behavior over a specified number of bars.
Dynamic Moving Average : The script calculates a machine-learning-inspired moving average (MLMA) based on the current cluster, adjusting its behavior according to the cluster regime (Bullish, Neutral, Bearish).
Adaptive Confidence Levels : Confidence in the predicted return is calculated based on the distance between the current value and the other clusters. The further it is from the next closest cluster, the higher the confidence.
Visual Cluster Mapping : The script visually highlights different clusters on the chart with distinct colors for Bullish, Neutral, and Bearish regimes, and plots the MLMA line.
Prediction Output : It projects the predicted price based on the selected method and shows both predicted price and confidence percentage for each prediction horizon.
Trend Identification : Using the clustering output, the script colors the bars based on the current cluster to reflect whether the market is trending Bullish (green), Bearish (red), or is Neutral (gray).
How Traders Use It
Predicting Price Movements : The script provides traders with an idea of where prices might go based on past market behavior. Traders can use this forecast for short-term and long-term predictions, guiding their trades.
Clustering for Regime Analysis : Traders can identify whether the market is in a Bullish, Neutral, or Bearish regime, using that information to adjust trading strategies.
Adaptive Moving Average for Trend Following : The adaptive moving average can be used as a trend-following indicator, helping traders stay in the market when it’s aligned with the current trend (Bullish or Bearish).
Entry/Exit Strategy : By understanding the current cluster and its associated trend, traders can time entries and exits with higher precision, taking advantage of favorable conditions when the confidence in the predicted price is high.
Confidence for Risk Management : The confidence level associated with the predicted returns allows traders to manage risk better. Higher confidence levels indicate stronger market conditions, which can lead to higher position sizes.
Pseudo Machine Learning Aspect
While the script does not use conventional machine learning models (e.g., neural networks or decision trees), it mimics certain aspects of machine learning in its approach. By using clustering and the dynamic adjustment of a moving average, the model learns from historical data to adjust predictions for future price behavior. The "learning" comes from how the script uses past price data (and technical indicators) to create patterns (clusters) and predict future market movements based on those patterns.
Why This Is Important for Traders
Understanding market regimes helps to adjust trading strategies in a way that adapts to current market conditions.
Forecasting price behavior provides an additional edge, enabling traders to time entries and exits based on predicted price movements.
By leveraging the clustering technique, traders can separate noise from signal, improving the reliability of trading signals.
The combination of clustering and predictive modeling in one tool reduces the complexity for traders, allowing them to focus on actionable insights rather than manual analysis.
How to Interpret the Output
Bullish (Green) Zone : When the price behavior clusters into the Bullish zone, expect upward price movement. The MLMA line will help confirm if the trend remains upward.
Bearish (Red) Zone : When the price behavior clusters into the Bearish zone, expect downward price movement. The MLMA line will assist in tracking any downward trends.
Neutral (Gray) Zone : A neutral market condition signals indecision or range-bound behavior. The MLMA line can help track any potential breakouts or trend reversals.
Predicted Price : The projected price is shown on the chart, based on the cluster's predicted behavior. This provides a useful reference for where the price might move in the near future.
Prediction Confidence : The confidence percentage helps you gauge the reliability of the predicted price. A higher percentage indicates stronger market confidence in the forecasted move.
Tips for Use
Combining with Other Indicators : Use the output of this indicator in combination with your existing strategy (e.g., RSI, MACD, or moving averages) to enhance signal accuracy.
Position Sizing with Confidence : Increase position size when the prediction confidence is high, and decrease size when it’s low, based on the confidence interval.
Regime-Based Strategy : Consider developing a multi-strategy approach where you use this tool for Bullish or Bearish regimes and a separate strategy for Neutral markets.
Optimization : Adjust the lookback period and percentile settings to optimize the clustering algorithm based on your asset’s characteristics.
Conclusion
The Machine Learning Moving Average offers a novel approach to price prediction by leveraging percentile clustering and a dynamically adapting moving average. While not a traditional machine learning model, this tool mimics the adaptive behavior of machine learning by adjusting to evolving market conditions, helping traders predict price movements and identify trends with improved confidence and accuracy.
hbd.mozanitstones - GoldThis PineScript indicator code aims to create an advanced composite trading system and generates buy/sell signals by combining multiple technical analyses. Essentially, the system utilizes a composite scoring mechanism using trend filters based on moving averages (EMA 50 and EMA 200) and various oscillators (such as RSI, MACD, and Stochastic) to support buy and sell decisions. It also integrates advanced confirmation tools such as the Multi-Timeframe (MTF) EMA filter, along with additional filters such as SuperTrend, Bollinger Bandwidth, and Volume Ratio. The code's key feature is that it generates final signals that meet both traditional signal conditions and the minimum number of confirmations achieved by weighting these various indicators, thus increasing signal reliability.
Crash Stats 15m (ETH) — X% | prev RTH min(VWAP, Close)# Crash Stats 15m (ETH) — X% Drawdown Event Analyzer
A 15-minute indicator that scans up to the last 5 years to find **crash events** where the close falls by at least **X%** relative to the **lower of** the prior day’s **RTH VWAP** and **RTH close**. It then measures recovery and follow-through behavior, tags the market regime around each event, and summarizes everything in a table.
---
## What the script detects
**Crash event (trigger):**
* On a 15-minute bar, `close <= refPrice * (1 - X%)`.
* `refPrice = min(previous RTH VWAP, previous RTH close)`.
* First touch only: subsequent bars below the threshold on the same trading day are ignored.
* Extended hours (ETH) are supported; if ETH is off, the script safely infers the previous RTH reference.
**Per-event measurements**
1. **Time to “turn up”** – first close **above the event-anchored AVWAP** (AVWAP cumulated from the trigger bar onward).
2. **Time to recover the reference price** – first close ≥ `refPrice`.
3. **Time to recover Y% above the crash-day average price** – first close ≥ `crashDayVWAP * (1+Y%)`.
4. **Post-crash lowest price & timing** – the lowest low and how long after the event it occurs, within a user-defined horizon (default 10 trading days, approximated in calendar days).
5. **Intraday RTH low timing** – on the crash day’s RTH session, when did the day’s intraday low occur, and **was it on the first 15-minute bar**?
6. **First 15-minute low of the RTH day** – recorded for context.
All durations are shown as **D days H hours M minutes**.
---
## Regime tagging (A / B)
For each event the script classifies the surrounding trend using daily closes:
* Let `r6m = (prevClose – close_6mAgo) / close_6mAgo`,
`r12m = (prevClose – close_12mAgo) / close_12mAgo`.
* **A**: both `r6m > 0` and `r12m > 0` (uptrend across 6m & 12m).
* **B**: one positive, one negative, and `r6m + r12m ≥ 0` (mixed but net non-negative).
* Otherwise: **—**.
This helps separate selloffs in strong uptrends (A) from mixed regimes (B) and others.
---
## Inputs
* **X — Crash threshold (%)**: default 5.
* **Y — Recovery above crash-day average (%)**: default 5.
* **Lookback years**: default 5 (bounded by data availability).
* **Horizon for post-crash lowest (trading days)**: default 10 (approximated as calendar days).
* **RTH session**: default `09:30–16:00` (exchange timezone).
* **Show markers**: plot labels on triggers.
* **Rows to display**: last N events in the table.
---
## Table columns
* Index, **Trigger time**, **Drop %**, **Ref price**, **Regime (A/B/—)**
* **Time to turn up** (above anchored AVWAP)
* **Time to ref price**, **Time to day VWAP + Y%**
* **Window lowest price**, **Time to window low**
* **RTH first-15m low**, **RTH lowest time**, **Was RTH low on first 15m?**
* **Crash-day VWAP**
---
## How to use
1. **Set chart to 15-minute** and **enable extended hours** for equities (recommended).
2. Keep defaults (**X=5%, Y=5%**) to start; tighten to 3–4% for more frequent events on less volatile symbols.
3. For non-US symbols or futures, adjust the **RTH session** if needed.
4. Read the table (top-right) for per-event diagnostics and aggregate averages (bottom row).
---
## Notes & implementation details
* Works whether ETH is on or off. If ETH is off, the script back-fills “previous RTH” references at the next RTH open and uses the prior daily close as a fallback.
* The “turn up” definition uses **event-anchored AVWAP**, a robust, price–volume anchor widely used for post-shock mean reversion analysis.
* Events are **de-duplicated**: only one event per trading day (per target RTH cycle).
* Lookback is limited by your plan and the data vendor. The script requests deep history (`max_bars_back=50000`), but availability varies by symbol.
* Durations use minute precision and are rendered as **days–hours–minutes** for readability.
---
## Quick troubleshooting
* **No events found**: lower **X%**, enable **ETH**, or ensure sufficient history is loaded (scroll back, or briefly switch to a higher timeframe to force deeper backfill, then return to 15m).
* **RTH boundaries off**: check the **RTH session** input matches the venue.
* **Few rows in table**: increase **Rows to display**.
---
## Typical use cases
* Back-test how fast different symbols tend to stabilize after a sharp gap-down or intraday shock.
* Compare recovery behavior across regimes **A / B** for sizing and risk timing.
* Build playbooks: e.g., if the RTH low occurs on the first 15m bar X% of the time, plan entries accordingly.
---
## Changelog
* **v1.0**: Initial public release with crash detection, anchored-AVWAP reversal, reference & VWAP+Y recovery timers, regime tagging, window-low timing, RTH low timing, and first-15m low capture.
detects bottom rebound signal🧩 General Idea:
This indicator detects bottom rebound signals — the start of an upward move after a downtrend — using a combination of RSI + price + volume.
⚙️ How the Indicator Works:
Calculates the RSI (Relative Strength Index) using a 14-period length.
→ Purpose: Measure momentum after a decline.
Monitors upward RSI crossovers at levels 45, 50, 55, and 60.
→ Purpose: Confirm that momentum is shifting from bearish to bullish.
Checks for a price increase of more than 2% compared to the previous close.
→ Purpose: Ensure that the move is strong and not just a small fluctuation.
Confirms that today’s volume is higher than yesterday’s.
→ Purpose: Validate that buying pressure is supported by real market activity.
When all conditions are met together ⇒ a rebound signal is generated ✅
(It plots a value of 1 as a histogram — can be used as a filter).
Triggers an alert when a rebound signal occurs — so you can get notified automatically in TradingView.
🎯 Indicator Purpose:
To identify stocks that are truly rebounding from their bottom, confirming it through momentum, price strength, and volume — often highlighting early entry opportunities before a larger uptrend.
🧩 الفكرة العامة:
يرصد لحظات ارتداد السهم من القاع — أي بداية صعود بعد فترة نزول — اعتمادًا على RSI + السعر + الحجم.
⚙️ خطوات عمل المؤشر:
يحسب مؤشر القوة النسبية (RSI) بطول 14 شمعة.
الهدف: قياس الزخم بعد نزول طويل.
يراقب تقاطعات RSI لأعلى عند المستويات (45، 50، 55، 60).
الهدف: تأكيد أن الزخم بدأ يتحول من سالب إلى موجب.
يتحقق من ارتفاع السعر أكثر من 2٪ مقارنةً بالإغلاق السابق.
الهدف: التأكد أن الصعود حقيقي وليس مجرد تذبذب بسيط.
يتأكد أن حجم التداول اليوم أكبر من اليوم السابق.
الهدف: وجود دعم حقيقي من المشترين (تأكيد على دخول سيولة).
عند تحقق كل الشروط السابقة معًا ⇒ يعطي إشارة ارتداد من القاع ✅
(يرسم عمودًا بقيمة 1 في الأسفل ويمكن استخدامه كفلتر).
يصدر تنبيه (Alert) عند تحقق الإشارة لتتابعها تلقائيًا في TradingView.
🎯 الهدف من المؤشر:
تحديد الأسهم التي بدأت ترتد فعليًا من القاع مع تأكيد الزخم والحجم والسعر — وهي غالبًا فرص دخول مبكرة قبل استمرار الصعود.
تنبيه مهم: يعمل كفلتر نبيه على قائمة محددة ولا يظهر على الشارت
loxxmasLibrary "loxxmas"
TODO:loxx moving averages used in indicators
kama(src, len, kamafastend, kamaslowend)
KAMA Kaufman adaptive moving average
Parameters:
src (float) : float
len (int) : int
kamafastend (int) : int
kamaslowend (int) : int
Returns: array
ama(src, len, fl, sl)
AMA, adaptive moving average
Parameters:
src (float) : float
len (int) : int
fl (int) : int
sl (int) : int
Returns: array
t3(src, len)
T3 moving average, adaptive moving average
Parameters:
src (float) : float
len (simple int) : int
Returns: array
adxvma(src, len)
ADXvma - Average Directional Volatility Moving Average
Parameters:
src (float) : float
len (int) : int
Returns: array
ahrma(src, len)
Ahrens Moving Average
Parameters:
src (float) : float
len (int) : int
Returns: array
alxma(src, len)
Alexander Moving Average - ALXMA
Parameters:
src (float) : float
len (int) : int
Returns: array
dema(src, len)
Double Exponential Moving Average - DEMA
Parameters:
src (float) : float
len (simple int) : int
Returns: array
dsema(src, len)
Double Smoothed Exponential Moving Average - DSEMA
Parameters:
src (float) : float
len (int) : int
Returns: array
ema(src, len)
Exponential Moving Average - EMA
Parameters:
src (float) : float
len (simple int) : int
Returns: array
fema(src, len)
Fast Exponential Moving Average - FEMA
Parameters:
src (float) : float
len (int) : int
Returns: array
hma(src, len)
Hull moving averge
Parameters:
src (float) : float
len (simple int) : int
Returns: array
ie2(src, len)
Early T3 by Tim Tilson
Parameters:
src (float) : float
len (int) : int
Returns: array
frama(src, len, FC, SC)
Fractal Adaptive Moving Average - FRAMA
Parameters:
src (float) : float
len (int) : int
FC (int) : int
SC (int) : int
Returns: array
instant(src, alpha)
Instantaneous Trendline
Parameters:
src (float) : float
alpha (float)
Returns: array
ilrs(src, len)
Integral of Linear Regression Slope - ILRS
Parameters:
src (float) : float
len (int)
Returns: array
laguerre(src, alpha)
Laguerre Filter
Parameters:
src (float) : float
alpha (float)
Returns: array
leader(src, len)
Leader Exponential Moving Average
Parameters:
src (float) : float
len (int)
Returns: array
lsma(src, len, offset)
Linear Regression Value - LSMA (Least Squares Moving Average)
Parameters:
src (float) : float
len (simple int)
offset (simple int)
Returns: array
lwma(src, len)
Linear Weighted Moving Average - LWMA
Parameters:
src (float) : float
len (int)
Returns: array
mcginley(src, len)
McGinley Dynamic
Parameters:
src (float) : float
len (simple int)
Returns: array
mcNicholl(src, len)
McNicholl EMA
Parameters:
src (float) : float
len (simple int)
Returns: array
nonlagma(src, len)
Non-lag moving average
Parameters:
src (float) : float
len (int)
Returns: array
pwma(src, len, pwr)
Parabolic Weighted Moving Average
Parameters:
src (float) : float
len (int)
pwr (float)
Returns: array
rmta(src, len)
Recursive Moving Trendline
Parameters:
src (float) : float
len (int)
Returns: array
decycler(src, len)
Simple decycler - SDEC
Parameters:
src (float) : float
len (int)
Returns: array
sma(src, len)
Simple Moving Average
Parameters:
src (float) : float
len (int)
Returns: array
swma(src, len)
Sine Weighted Moving Average
Parameters:
src (float) : float
len (int)
Returns: array
slwma(src, len)
linear weighted moving average
Parameters:
src (float) : float
len (int)
Returns: array
smma(src, len)
Smoothed Moving Average - SMMA
Parameters:
src (float) : float
len (simple int)
Returns: array
super(src, len)
Ehlers super smoother
Parameters:
src (float) : float
len (int)
Returns: array
smoother(src, len)
Smoother filter
Parameters:
src (float) : float
len (int)
Returns: array
tma(src, len)
Triangular moving average - TMA
Parameters:
src (float) : float
len (int)
Returns: array
tema(src, len)
Tripple exponential moving average - TEMA
Parameters:
src (float) : float
len (simple int)
Returns: array
vwema(src, len)
Volume weighted ema - VEMA
Parameters:
src (float) : float
len (simple int)
Returns: array
vwma(src, len)
Volume weighted moving average - VWMA
Parameters:
src (float) : float
len (simple int)
Returns: array
zlagdema(src, len)
Zero-lag dema
Parameters:
src (float) : float
len (simple int)
Returns: array
zlagma(src, len)
Zero-lag moving average
Parameters:
src (float) : float
len (int)
Returns: array
zlagtema(src, len)
Zero-lag tema
Parameters:
src (float) : float
len (simple int)
Returns: array
threepolebuttfilt(src, len)
Three-pole Ehlers Butterworth
Parameters:
src (float) : float
len (int)
Returns: array
threepolesss(src, len)
Three-pole Ehlers smoother
Parameters:
src (float) : float
len (int)
Returns: array
twopolebutter(src, len)
Two-pole Ehlers Butterworth
Parameters:
src (float) : float
len (int)
Returns: array
twopoless(src, len)
Two-pole Ehlers smoother
Parameters:
src (float) : float
len (int)
Returns: array
Double Grid + Auto Countdown Timer (Stable v6.1)Adjustable grid indicator with two levels and bar countdown timer fully adjustable.
AUTO asset, 1h/4h, Last Lines + Alerts + Signal BoxUnified PC-ATR v5 (Indicator) — AUTO asset, 1h/4h, Last Lines + Alerts + Signal Box






















