Polynomial Regression Clustering [LuxAlgo]The Polynomial Regression Clustering indicator utilizes K-Means clustering to categorize historical price data into discrete levels and fits polynomial regression curves to each identified cluster.
This tool allows traders to visualize non-linear trends within specific price regimes, providing a unique perspective on support, resistance, and price momentum.
🔶 USAGE
The indicator identifies "K" number of clusters based on the vertical distribution of price over a user-defined lookback period. Each cluster represents a group of bars that share similar price levels, and a polynomial regression line is calculated to represent the localized trend for that specific group.
🔹 Cluster Identification
The script groups price action into color-coded dots. By default, it uses the HL2 (Average price) to determine which cluster a bar belongs to. This is particularly useful for identifying historical value areas where price has spent a significant amount of time.
🔹 Polynomial Fitting
Unlike standard linear regression, which produces a straight line, the polynomial regression curves can bend to fit the data more accurately.
A Polynomial Degree of 1 will result in a standard linear regression (straight lines). A Polynomial Degree of 2 or higher allows for curves that capture parabolic moves or cyclical swings within each cluster.
🔹 Future Projections
The current active cluster (the one containing the most recent price point) can be projected into the future. This allows you to see where the localized trend for the current price regime is heading based on the mathematical fit of historical data.
🔶 DETAILS
🔹 K-Means Algorithm
The script uses an iterative K-Means algorithm to find the optimal centroids (center points) for the price levels. It calculates the distance of each price point to the nearest centroid and refines the centroid position until the clusters are stable or the maximum iterations are reached.
🔹 Regression Logic
Once price points are assigned to a cluster, the script solves for the coefficients of a polynomial equation that minimizes the distance between the line and the cluster's data points. To ensure numerical stability with higher degrees, the horizontal (time) axis is normalized before performing matrix operations.
🔶 SETTINGS
🔹 K-Means
Number of Clusters (K): Defines how many price levels the indicator should look for. Higher values create more granular levels. Lookback Period: The number of recent bars used to perform the clustering and regression calculation. Max Iterations: The maximum number of refinement steps for the K-Means algorithm.
🔹 Regression
Polynomial Degree: Controls the "bend" of the regression lines. Higher degrees allow for more complex curves. Extend All Fits to Current Bar: When enabled, the regression lines for all historical clusters are extended to the rightmost edge of the chart. Project Current Cluster into Future: Extends the current regime's regression line into the future (empty space) using a dashed line.
🔹 Visual Style
Show Regression Lines: Toggles the visibility of the polynomial curves. Show Cluster Dots: Toggles the visibility of the colored dots on each price bar. Dot Size: Adjusts the size of the cluster dots. Cluster Colors: Customizable colors for each of the identified clusters.
Indicadores y estrategias
Volume Surge Breakout + TP/SL█ OVERVIEW
“Volume Surge Breakout + TP/SL” is a breakout indicator designed to capture strong momentum moves driven by sudden increases in trading volume and decisive price action. Instead of focusing on classical consolidation structures, the indicator reacts to volume-based impulses combined with candle strength, identifying moments when the market shifts out of short-term balance.
After a confirmed breakout, the indicator automatically plots the entry level, Stop Loss, and up to three Take Profit targets, making it a complete momentum-trading tool.
█ CONCEPTS
Strong market moves often begin with a sudden surge in volume, signaling increased participation and commitment from market participants. This indicator detects such moments by combining three core conditions:
- volume significantly above its average,
- a candle body clearly larger than the previous one,
- directional price close confirming bullish or bearish intent.
When these conditions are met, a momentum zone (box) is drawn around the signal candle. The box extends forward until a breakout occurs, which then triggers the entry signal and full TP/SL projection. A breakout in the opposite direction invalidates the zone, filtering out false impulses.
█ FEATURES
Volume filter
- volume > volume SMA × Volume Threshold (default 2.0×)
- adjustable volume average length (Volume SMA Length)
Candle strength filter
- current candle body > previous candle body × Body Multiplier
- removes weak and random price moves
Dynamic impulse zones (boxes)
- green for LONG, red for SHORT
- semi-transparent fill with colored borders
- boxes extend to the right until a breakout occurs
- opposite breakout deletes the zone
Breakout signals
- small green triangles below the bar (LONG)
- small red triangles above the bar (SHORT)
- signals appear only after a valid breakout from the zone
Volume strength display
- optional label showing the volume multiplier (e.g. 2.35×)
- color-coded to match trade direction
Automatic Take Profit & Stop Loss
- two SL calculation modes:
• ATR-based (default 1.5× ATR)
• Percentage-based from entry price
- up to 3 Take Profit levels based on Risk-to-Reward ratios
- independent visibility toggles for SL, TP1, TP2, TP3
- visual fills:
• red – risk zone
• green – reward zone
Single active trade logic
- TP/SL levels are locked once SL or the furthest TP is hit
- lines terminate exactly at the exit bar
Alerts
- LONG – bullish volume impulse
- SHORT – bearish volume impulse
█ HOW TO USE
Add the indicator to your TradingView chart → Indicators → search for
“Volume Surge Breakout + TP/SL”.
After each valid breakout, you will see:
- a volume impulse box,
- a breakout triangle,
- the entry line,
- SL and TP1–TP3 levels,
- a visual risk-to-reward projection.
Key settings to optimize:
Volume
- Volume SMA Length – averaging period for volume
- Volume Threshold – minimum volume multiplier
- Body Multiplier – required candle body expansion
TP / SL
- choose SL mode: ATR or Percentage
- ATR period and multiplier
- RR values for TP1, TP2, TP3
Signal interpretation:
- Green box + green triangle + TP above price = LONG
- Red box + red triangle + TP below price = SHORT
- No breakout = no trade (box remains observational)
█ APPLICATIONS
- Momentum and breakout trading across all timeframes
- Best used as an entry trigger, not as a standalone strategy
Recommended confluence-based approach:
The highest-quality signals occur when the breakout aligns with broader market context:
- higher-timeframe trend agreement
- breakout signal generated by the indicator
- increasing momentum (e.g. RSI, MACD, custom momentum oscillators)
- no major resistance/support levels directly in front of price
- volume impulse confirming market participation
Example:
If the market is in an uptrend, a LONG breakout signal appears, momentum is accelerating, and no nearby resistance is present, the trade is worth considering, using the automatically projected RR levels.
- Aggressive two-sided trading is possible but requires stricter signal selection
- Higher RR setups (e.g. TP3 = 3–5× SL) with lower win rates often outperform over time
█ NOTES
This indicator works only on markets with real volume data (e.g. stocks, futures, many crypto markets).
On instruments without real volume (such as some CFD indices), signals may be unreliable or the indicator may not function correctly.
Always test and optimize parameters for the specific instrument and timeframe. The indicator intentionally does not interpret market structure — its sole purpose is to identify clean volume-driven impulses.
Level 1 Gold - MAs & BiasLevel 1 Gold - MAs & Bias
A clean trend bias indicator designed for the Level 1 Gold trading strategy.
Features:
EMA 5 (Orange) - Fast exponential moving average for momentum confirmation
SMA 21 (Blue) - Slow simple moving average for trend direction
Trend Bias Detection - Tracks the last EMA5/SMA21 crossover to determine trade direction:
EMA5 crosses ABOVE SMA21 → "BUYS ONLY" (only take long trades)
EMA5 crosses BELOW SMA21 → "SELLS ONLY" (only take short trades)
Session Filter - Highlights invalid trading sessions (default: 06:00-16:00 UK time, avoids Monday AM and Friday PM)
Crossover Markers - Green Circle (bullish cross), Red Circle (bearish cross)
How to Use:
Wait for an EMA5/SMA21 crossover to establish bias
Only take trades in the direction of the bias
Avoid trading during shaded (invalid) session times
Look for breakouts across your horizontal support/resistance levels that align with the bias
Settings:
Moving average lengths (default: EMA 5, SMA 21)
Session times and filters (customizable)
Toggle visuals on/off
Adjustable colors
Best Used On: 1H timeframe for Gold (XAUUSD)
ATR Structure Trail Pro & Range Filter (v6)📌 ATR Structure Trail Pro & Range Filter (v6)
Multi-purpose trend-following and consolidation detection tool
🔍 Overview
This indicator combines structure pivots, an ATR-based trailing stop, range detection, and clean visual signals to identify trend shifts and potential trade zones.
It is designed for traders who want simple, clean structure reading without unnecessary chart noise.
This indicator does not guarantee profit and is intended for educational and analytical purposes only, serving as a visual aid for reading price action.
⚙️ Main Components
1️⃣ Structure Pivot Flip (Trend Change Detection)
The indicator uses Pivot High / Pivot Low structure to detect when price creates:
Higher High → BUY bias
Lower Low → SELL bias
When a structural flip occurs:
a green arrow appears (potential bullish setup)
or a red arrow appears (potential bearish setup)
These arrows are not trade signals, but visual markers highlighting a shift in market context.
2️⃣ ATR Trail Stop (Adaptive Trend Line)
The ATR trail line automatically adapts to market volatility:
green during bullish phases
red during bearish phases
The ATR multiplier determines how far the dynamic trail is placed relative to price.
The trail line is not a guaranteed exit level — it acts as a dynamic structural reference.
3️⃣ Range/Box Zones (Consolidation Filter)
When the indicator detects that price is entering a tight consolidation range based on ATR and recent volatility, it draws a box zone:
blue in bullish context
purple in bearish context
Range zones indicate low-risk/no-trade areas where entries are typically avoided according to price action logic.
🎯 Trading Logic (Non-Signaling)
This indicator is not a trading system.
It visually highlights:
✔ structure
✔ trend
✔ volatility
✔ consolidation
✔ potential reversals
Users make trading decisions independently of these visual elements.
🧩 Inputs & Customization
You can fully customize:
ATR length & multiplier
Pivot sensitivity
Box fill and border colors
ATR trail color, width, and style (solid/dashed/dotted)
Visibility of all components individually
The indicator works across all timeframes and instruments.
💡 How to Use
Use arrows as informational markers of structure change
Use the ATR trail as a dynamic guide for current trend
Use range boxes to avoid entries during consolidation
Combine it with your own price action analysis, EMA/Kijun lines, session opens, or volume levels
⚠️ Important Notes
This indicator provides no performance guarantees
Not financial advice or a trading signal
Users are responsible for their own testing and application
Intended strictly for educational and analytical use in compliance with TradingView’s rules
📬 Author Notes
If you find this indicator useful, feel free to leave a comment or suggestion for future improvements.
All inputs are open for expansion and further development.
Elliott Wave Auto S🌊 ELLIOTT WAVE AUTO — Automatic Elliott Wave Detection
═══════════════════════════════════════════════════════════════════
📜 THE HISTORY
Ralph Nelson Elliott (1871-1948), an American accountant, spent his forced retirement analyzing 75 years of Dow Jones data... by hand. In 1938, he published "The Wave Principle", revealing that markets move in repetitive patterns of 5 impulse waves followed by 3 corrective waves (A-B-C).
What's often forgotten: Elliott worked primarily on MONTHLY and WEEKLY timeframes. A complete cycle could take months, even years. It was a strategy of PATIENCE, not scalping.
═══════════════════════════════════════════════════════════════════
🎯 OUR APPROACH
This indicator attempts to stay as close as possible to Elliott's original method. The algorithm uses Pivot Point detection (ta.pivothigh / ta.pivotlow) to objectively identify tops and bottoms.
Unlike manual counting where 3 analysts give 3 different results, this method is:
✅ Mathematical — No subjective interpretation
✅ Reproducible — 100 traders = 1 single count
✅ Automatic — Real-time detection
✅ Open source — Nothing hidden, study it freely
═══════════════════════════════════════════════════════════════════
⛔ ORANGE LABELS — INVALIDATIONS
You will sometimes notice ORANGE labels with the ⛔ symbol on your chart. These are not errors! They indicate that a fundamental Elliott rule has been violated, invalidating the current cycle.
Back in his time, Elliott established strict rules to validate a count. If any of these rules is broken, the cycle is no longer valid and we must start looking for a new starting point.
Here are the 3 fundamental rules applied by this indicator:
┌─────────────────────────────────────────────────────────────────┐
│ 📖 RULE 1: Wave 2 NEVER retraces 100% of Wave 1 │
│ │
│ If Wave 2 price exceeds the starting point of Wave 1, │
│ it wasn't a true Wave 1. │
│ → The indicator then reverses the trend (BULL ↔ BEAR) │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ 📖 RULE 2: Wave 3 is NEVER the shortest │
│ │
│ Wave 3 is supposed to be the most powerful. If it's shorter │
│ than Wave 1 AND Wave 5, the count is invalid. │
│ → Orange label "5 ⛔" displayed, cycle cancelled │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ 📖 RULE 3: Wave 4 NEVER overlaps Wave 1 territory │
│ │
│ In an uptrend: Wave 4 low cannot drop below Wave 1 high. │
│ In a downtrend: Wave 4 high cannot exceed Wave 1 low. │
│ → Orange label "4 ⛔" displayed, cycle cancelled │
└─────────────────────────────────────────────────────────────────┘
💡 These invalidations are NORMAL and part of the method. They ensure that only cycles perfectly respecting Elliott's theory are counted. That's why you'll see few complete cycles — exactly like in Elliott's time.
═══════════════════════════════════════════════════════════════════
📊 HOW TO USE IT
▸ Wave 1: Cycle start detected. Watch, don't act.
▸ Wave 2: Potential ENTRY zone. The retracement is over,
Wave 3 (the most powerful) should follow.
▸ Wave 3: The most powerful! Never trade against a Wave 3.
Let your profits run.
▸ Wave 4: Second potential ENTRY zone for those who missed Wave 2.
▸ Wave 5: Last impulse. Prepare your EXIT.
The impulse cycle is ending.
▸ Waves A-B-C: Correction phase. Patience recommended.
Wait for the end of C for the next cycle.
▸ Orange Label ⛔: Rule violated, cycle invalidated.
The indicator starts looking for a new cycle.
═══════════════════════════════════════════════════════════════════
🔔 TOGGLEABLE ALERTS
Each wave has its own alert, individually toggleable in the settings:
🌊 Wave 1 — Cycle start
🌊 Wave 2 — Potential entry zone
🌊 Wave 3 — The most powerful
🌊 Wave 4 — Potential entry zone
🌊 Wave 5 — Last impulse
🔄 Wave A — Correction start
🔄 Wave B — Corrective bounce
🔄 Wave C — Correction end
✅ Complete cycle
💡 Tip: Enable only the alerts that match your strategy. For example, only "Wave 2" and "Wave 4" for entries, and "Wave 5" for exits.
═══════════════════════════════════════════════════════════════════
📏 SETTINGS
▸ Move Size:
• Small = More signals, more noise (scalping)
• Medium = Balanced (intraday/swing) ← Recommended
• Large = Fewer signals, more reliable (position)
Note: Sensitivity automatically adjusts based on your
timeframe for optimal results.
▸ Labels: Display 1, 2, 3, 4, 5, A, B, C on the chart
▸ Lines: Visually connect the waves
▸ Fibonacci Ratios: Display each wave's ratio (optional)
▸ Label Size: Small / Normal / Large per your preference
═══════════════════════════════════════════════════════════════════
🎨 COLOR CODE
🟢 Green = Bullish trend (BULL)
🔴 Red = Bearish trend (BEAR)
🟣 Pink/Purple = Corrective waves (A, B, C)
🟠 Orange = Invalidation (Elliott rule violated)
═══════════════════════════════════════════════════════════════════
⚠️ DISCLAIMER
Like in Elliott's time, complete 1-2-3-4-5-A-B-C cycles are RARE. This is normal and intentional.
The Elliott Wave method is a patience strategy that rewards those who know how to wait for perfect setups. The many invalidations (orange labels) prove that the indicator strictly respects the original rules.
If you're looking for dozens of signals per day, this method is probably not for you. But if you value quality over quantity, welcome.
Happy trading! 🌊
Z-Score Predictive Zones [AlgoPoint]Z-Score Predictive Zones
This indicator is an advanced evolution of the classic Z-Score (Standard Score) oscillator. Unlike traditional Z-Score indicators that use static overbought/oversold levels (e.g., +2.0 or -2.0), this script utilizes a dynamic memory system to identify where the market statistically tends to reverse based on recent history.
It provides a dual-view system: it displays the oscillator in the bottom pane and simultaneously projects those statistical extremes onto the main chart as Predictive Support and Resistance Zones.
1. Underlying Concept & Math
The core calculation is based on the Standard Score formula: Z = (Price - Mean) / Standard Deviation
- Adaptive Thresholds : The script detects pivot points (peaks and troughs) in the Z-Score history. It stores the most recent reversals (based on user-defined depth) and calculates the average level where the market has historically reversed.
- Reverse Engineering (Price Projection) : The script takes these average Z-Score reversal levels and reverse-engineers the formula to find the corresponding price on the main chart: Projected Price = Mean + (Target Z * Standard Deviation)
- Noise Reduction : The raw Z-Score is smoothed using a Volume Weighted Moving Average (VWMA) to reduce false signals.
2. Key Features
Dynamic Predictive Zones (Main Chart):
- Red Zone (Resistance) : Represents the price area where the Z-Score hits its historical average peak.
- Green Zone (Support) : Represents the price area where the Z-Score hits its historical average trough.
Note: These zones expand and contract based on market volatility (Standard Deviation).
Dual Visualization:
- Bottom Pane : Shows the Z-Score oscillator with the calculated dynamic steps.
- Main Chart : Uses force_overlay=true to draw the corresponding price channels directly on the candles, allowing for real-time price action analysis.
- RSI Gradient Coloring : The oscillator line changes color based on RSI (Relative Strength Index) values to provide additional momentum context (Purple/Blue gradients).
- Signal Dots : Plots small circles on the main chart when the price enters these extreme statistical zones, indicating a potential mean reversion opportunity.
3. How to Use
This indicator is best used for Mean Reversion strategies.
- Potential Short : When price enters the Red Zone (Upper Channel) and a red dot appears, the price is statistically overextended relative to its recent volatility profile.
- Potential Long : When price enters the Green Zone (Lower Channel) and a green dot appears, the price is statistically undervalued relative to the mean.
- Trend Warning : If the price candles close forcefully beyond these zones and the zones begin to widen rapidly, it may indicate a breakout or a strong trend initiation rather than a reversal.
4. Settings
- Z-Score Length : The lookback period for the Mean and Standard Deviation.
- Lookback Depth : How many past reversal points the script should "remember" to calculate the average zones.
- Reversal Thresholds : The minimum Z-Score value required to register a peak or trough as a valid data point.
- Visuals : Toggle signal dots on/off.
Neural Probability Channel [AlgoPoint]The Neural Probability Channel (NPC) is a next-generation volatility and trend analysis tool designed to overcome the limitations of traditional bands (like Bollinger Bands) and smoothing filters (like standard Moving Averages).
Unlike traditional indicators that rely on linear deviation or simple averages, the NPC utilizes a Rational Quadratic Kernel—a concept derived from machine learning regression models—to calculate a non-repainting, highly adaptive baseline (Fair Value). This allows the indicator to distinguish between market noise and genuine trend shifts with superior accuracy.
The volatility bands are dynamically calculated using a hybrid of Standard Error (Mean Deviation) and ATR, ensuring the channels adapt organically to market conditions—expanding during high-impact moves and contracting during consolidation.
How It Works
- The Neural Baseline (Center Line): Instead of a standard Moving Average, the NPC uses a Rational Quadratic Kernel weighting system. This assigns "importance" to price data based on both recency and similarity. It acts as a "Center of Gravity" for price, providing a smoother yet responsive trend detection line without the lag associated with SMAs or EMAs.
Crucially, the math is causal (no lookahead), meaning it does not repaint.
- Adaptive Volatility Bands: The channel width is not fixed. It uses a Hybrid Volatility Model:
- Inner Channel: Represents the "Probability Zone" (approx. 70% confidence). Price staying here indicates a stable trend.
- Outer Channel: Represents "Extreme Deviation" (Statistical Anomalies). When price touches or breaches these outer bands, it is statistically overextended (Overbought/Oversold).
Signal Generation:
- Reversion Signals: Generated when price breaches the Outer Bands and closes back inside. This suggests a "Snap-back" or Mean Reversion event.
- Trend Confirmation: The color of the baseline and the fill zones changes based on the slope of the Kernel, giving an instant visual read on market bias.
How to Use It
- Mean Reversion Strategy: Look for price action extending beyond the Outer Bands (Thinner lines). If price leaves a wick and closes back inside, it signals a high-probability reversal toward the Neural Baseline.
- Green Signal: Potential Long (Reversal from Lows).
- Red Signal: Potential Short (Reversal from Highs).
- Trend Following: Use the Neural Baseline (Thick Center Line) as a dynamic support/resistance level.
If price is holding above the baseline and the cloud is green, the trend is Bullish.
If price is holding below the baseline and the cloud is red, the trend is Bearish.
- Squeeze Detection: When the Inner and Outer bands compress significantly, it indicates low volatility and often precedes an explosive breakout.
Settings
- Lookback Window: Determines the depth of the Kernel analysis.
- Smoothness (Bandwidth): Higher values create a smoother baseline (better for trends), while lower values make it more reactive (better for scalping).
- Regression Alpha: Controls the weight distribution of the Kernel.
- Channel Multipliers: Adjust the width of the Inner and Outer bands to fit your specific asset's volatility profile.
Clusters Volume Profile [LuxAlgo]The Clusters Volume Profile indicator utilizes K-Means clustering to categorize historical price action into distinct groups and generates individual volume profiles for each detected cluster. This tool provides a unique perspective on volume distribution by isolating price behaviors based on proximity rather than strictly chronological order.
🔶 USAGE
The indicator identifies "clusters" of price activity within a user-defined lookback period. Each cluster is assigned a unique color and its own horizontal volume profile, allowing traders to see where liquidity is most concentrated within specific price regimes.
🔹 Identifying Institutional Zones
Traders can use the Point of Control (POC) of high-volume clusters to identify significant institutional interest. Because the K-Means algorithm groups price action by density rather than time, a cluster's POC often represents a "fair value" level where significant exchange occurred. These dashed POC lines frequently act as robust support or resistance levels when price returns to them in the future.
🔹 Market Regime Detection
By observing the vertical distribution and overlap of clusters, traders can identify market phases. Overlapping clusters with high volume often indicate accumulation or distribution phases (sideways markets), whereas distinct, vertically separated clusters with lower volume gaps between them suggest a trending environment. A shift from multiple overlapping clusters to a new, isolated cluster can signal a breakout or the start of a new trend.
🔹 Precision Entry & Exits
Cluster boundaries and POC lines provide concrete levels for trade management. An entry can be sought when price retests a high-volume cluster POC, while stops can be placed outside the total price range of that specific cluster (the area covered by its volume profile). Conversely, targets can be set at the POC of the next major cluster above or below current price action.
🔹 Volume Conviction
The tool provides specific volume metrics that allow traders to gauge conviction. By comparing the "Total" volume label of one cluster against another, a trader can determine which price regime had more participation. A breakout into a price zone with a high-volume cluster suggests stronger conviction and a higher probability of the level holding compared to a zone with low total volume.
🔶 DETAILS
The script employs a K-Means clustering algorithm. This process involves:
Initializing "centroids" across the price range of the lookback period.
Iteratively assigning each price bar to the nearest centroid based on the HLC2 (median) price.
Recalculating centroids based on the volume-weighted average price of the assigned bars.
Finalizing assignments after the specified number of iterations to ensure stable clusters.
By separating price action into these clusters, the tool helps identify high-interest zones that might be obscured by a single, traditional Volume Profile.
🔶 SETTINGS
🔹 Clustering Settings
Lookback Period: Determines the number of recent bars used for the clustering analysis.
Number of Clusters: Sets how many distinct price groups the algorithm should attempt to find (2 to 10).
K-Means Iterations: Controls the number of times the algorithm refines the cluster centers. Higher values can lead to more stable results.
🔹 Volume Profile Settings
Rows per Cluster VP: Defines the vertical resolution (number of bins) for each individual cluster's profile.
Max VP Width (Bars): Sets the maximum horizontal length of the volume profile histograms.
VP Offset: Adjusts the horizontal spacing between the current bar and the start of the volume profiles.
Highlight Price Dots: Toggles the visibility of the colored dots on the price action to identify cluster assignments.
Dot Size: Adjusts the size of the cluster assignment dots on the chart, ranging from tiny to huge.
Put Spread Signals Daily v5 (NO ta.sum)//@version=5
indicator("Put Spread Signals Daily v5 (NO ta.sum)", overlay=true)
// Inputs
ma20Len = input.int(20, "MA20")
ma50Len = input.int(50, "MA50")
ma200Len = input.int(200, "MA200")
pullbackPct = input.float(0.01, "Pullback near MA20 (1%=0.01)", step=0.005)
minRedDays = input.int(1, "Min red days (last 5)", minval=0, maxval=5)
stopBelow200Pct = input.float(0.005, "Stop below MA200 %", step=0.0025)
// MAs
ma20 = ta.sma(close, ma20Len)
ma50 = ta.sma(close, ma50Len)
ma200 = ta.sma(close, ma200Len)
// Trend + pullback
bullTrend = close > ma50 and close > ma200 and ma50 > ma200
nearMA20 = close <= ma20 * (1 + pullbackPct)
// Red candle count last 5 bars (NO ta.sum)
red0 = close < open ? 1 : 0
red1 = close < open ? 1 : 0
red2 = close < open ? 1 : 0
red3 = close < open ? 1 : 0
red4 = close < open ? 1 : 0
redCount = red0 + red1 + red2 + red3 + red4
hasMinRed = redCount >= minRedDays
// Bounce
bounce = close > open and close > close
// Signals
enter = bullTrend and nearMA20 and hasMinRed and bounce
takeProfit = ta.crossover(close, ma20)
stopOut = close < ma200 * (1 - stopBelow200Pct)
// Plots
plot(ma20, "MA20", linewidth=2)
plot(ma50, "MA50", linewidth=2)
plot(ma200, "MA200", linewidth=2)
plotshape(enter, title="ENTER", style=shape.labelup, location=location.belowbar, text="ENTER", size=size.small)
plotshape(takeProfit, title="EXIT_TP", style=shape.labeldown, location=location.abovebar, text="TP", size=size.small)
plotshape(stopOut, title="EXIT_STOP", style=shape.labeldown, location=location.abovebar, text="STOP", size=size.small)
// Alerts
alertcondition(enter, title="ENTER Alert", message="ENTER: Trend up + pullback near MA20 + bounce. Consider selling put credit spread (30-45 DTE).")
alertcondition(takeProfit, title="EXIT TP Alert", message="EXIT TP: Price reclaimed MA20. Consider taking profit.")
alertcondition(stopOut, title="EXIT STOP Alert", message="EXIT STOP: Close below MA200 threshold. Consider closing/rolling.")
bosstvs tikole sir | ALL IN ONE ULTIMATE NEW STRONG BUY SELLWhat this indicator is
“bosstvs tikole sir | ALL IN ONE ULTIMATE” is a multi-indicator trading tool for TradingView.
It combines trend direction, buy/sell signals, targets, and key levels into one chart.
It is mainly designed for intraday & swing trading.
Main components explained
1. SuperTrend (Trend Direction)
Uses SuperTrend to identify the market trend
When price crosses above SuperTrend → bullish
When price crosses below SuperTrend → bearish
Sensitivity controls how fast/slow signals appear
2. Buy & Sell Signals
A BUY signal appears when:
Price crosses above SuperTrend
Price is above 13-period SMA
Label shows Buy or Strong Buy
Strong Buy = short-term momentum is stronger
A SELL signal appears when:
Price crosses below SuperTrend
Price is below 13-period SMA
Label shows Sell or Strong Sell
Alerts are available for both BUY and SELL.
3. Trend Cloud (Market Bias)
Uses 21 SMA & 34 SMA
Green cloud → bullish trend
Red cloud → bearish trend
Helps you stay on the correct side of the trend
4. Pivot Highs & Lows (Support / Resistance)
Automatically marks recent swing highs and lows
Useful for:
Stop-loss placement
Breakout & rejection trades
5. First Candle High–Low Targets (Intraday Logic)
Takes the first candle of the day
Calculates:
Buy target = High + Day range
Sell target = Low − Day range
Shows target levels on the chart
Signals when price hits the target
Best used on intraday timeframes.
6. EMA, SMA & VWAP (Dynamic Levels)
Optional moving averages:
EMA 21 → short-term trend
SMA 50 → medium-term trend
VWAP → institutional price level
You can turn each ON/OFF from settings.
How traders typically use it
Check the cloud → trend direction
Wait for SuperTrend signal
Confirm with EMA / SMA
Use pivot levels for stop-loss
Use day targets for exits
Best timeframes
5 min / 15 min → intraday
30 min / 1H → swing trades
Who this indicator is for
✔ Intraday traders
✔ Trend followers
✔ Traders who want everything in one script
❌ Not ideal for pure sideways markets
Statistical Range and Daily Range - MaePla PakkakeawSupport & Resistance Box (MaePla Pakkakeaw)
Major support and resistance levels are drawn approximately 500 points apart.
These are called Statistical Lines.
Statistical support and resistance levels are drawn at price levels ending in 0 and 5.
Daily Range
(Start the Day on H4 Timeframe)
At 7:00 AM, check the H4 candle close.
Identify the price level closest to a statistical line as the minor support or resistance.
The next statistical line 500 points above becomes the upper price range.
The next statistical line 500 points below becomes the lower price range.
CODY BOT REVERSALFree Telegram Trading Community t.me
What Is CODY BOT?
CODY BOT is an easy-to-use trading tool that spots potential price reversals on your chart. It shows arrows when it detects certain candlestick patterns that often happen before the market changes direction.
How It Works
Green "Buy" Arrow Appears When:
Current candle closes higher than yesterday's open
Yesterday's candle closed lower than its own open
This pattern often signals a possible upward move coming
Red "Sell" Arrow Appears When:
Current candle closes lower than yesterday's open
Yesterday's candle closed higher than its own open
This pattern often signals a possible downward move coming
What You'll See on Your Chart
Green up arrows below candles (buy signals)
Red down arrows above candles (sell signals)
You'll also get alerts if you set them up
Best Ways to Use It
Good For:
Day trading (5-minute to 1-hour charts)
Swing trading (4-hour to daily charts)
All markets: stocks, forex, crypto
Spotting quick trend changes
Tips for Better Results:
Wait for the candle to close before trading
Use with support/resistance lines for confirmation
Add volume to check if others are trading too
Start with paper trading to practice
Always use stop-loss to protect yourself
What Makes It Special
No lag - signals appear immediately
Easy to understand - just follow the arrows
Works on any timeframe
Free to use
No complicated settings
Quick Start Guide
Add CODY BOT to your TradingView chart
Watch for green/red arrows at candle close
Click the alert bell if you want notifications
Test with fake money first
Combine with what you already know about trading
Remember: No indicator is perfect. Use CODY BOT as one tool in your toolbox, not the only tool. Always manage your risk and never trade more than you can afford to lose.
Perfect for: Traders who like simple, clear signals without complicated math.
GK Trend Ribbon SWING + PREPARE HUD
GK Trend Ribbon SWING + PREPARE HUD
Is a trend-following swing-trading indicator designed to identify high-probability directional bias, early trade preparation, and confirmed trend shifts using a volatility-adjusted zero-lag trend ribbon. This script is purpose-built for traders who value patience, structure, and confirmation, rather than fast scalping or candle-by-candle noise.
HOW IT WORKS
indicator is built around a Zero-Lag EMA (ZLEMA) to reduce traditional EMA delay while maintaining smooth trend behaviour. An ATR-based volatility envelope is applied above and below the ribbon to define dynamic trend boundaries. Trend states are determined as follows: Bullish mode: Price sustains above the upper volatility band with confirmation Bearish mode: Price sustains below the lower volatility band with confirmation Neutral mode: Price remains inside the ribbon range A trend change is only confirmed after multiple bar confirmation, helping filter false breakouts and market noise.
PREPARE SIGNALS
(Early Awareness)Before a confirmed trend flip, the indicator displays PREPARE GK BUY / PREPARE GK SELL warnings: These appear only on the live (unconfirmed) candle They act as early awareness, not entry signals They disappear if conditions are not confirmed This allows traders to prepare mentally and structurally without repainting past signals. Confirmed Signals Confirmed GK BUY / GK SELL signals are only printed after bar close and only when: A valid trend transition is confirmed Directional conditions persist The previous trend state is invalidated Once printed, confirmed signals do not repaint.
HUD BANNER
The integrated HUD provides real-time market state feedback: Bullish Mode Bearish Mode Neutral / Wait Prepare Buy / Sell warnings This allows quick decision-making without needing to interpret raw price action continuously. Inputs & Customisation Swing Ribbon Length – controls trend smoothness (higher = slower, stronger trends)ATR Length – volatility measurement period Band Multiplier – sensitivity of trend boundaries Confirmation Bars – number of bars required to confirm a trend shift.
RECOMENDED USEGE
Best suited for 15-minute, 30-minute, and higher time frames Designed for swing trading, not scalping Expect natural drawdown during trend development Works best when combined with proper risk management and market structure awareness
Important Notes This indicator does not predict price It reacts to confirmed market structure and volatility No indicator guarantees profitability Always use appropriate risk management Disclaimer This script is provided for educational and analytical purposes only .It is not financial advice .Trading involves risk, and users are responsible for their own trading decisions.
[CT] MTF CISD w/ExtensionsThis indicator is a modified version of “Change in State of Delivery CISD” originally created by © AlgoAlpha and released under the Mozilla Public License 2.0. The core CISD logic, including how the script identifies qualifying bullish and bearish state changes and how it draws the original CISD levels, comes from AlgoAlpha’s work. The version you are using has been modified by © ChaosTrader63 to add multi time frame CISD functionality, optional HTF labeling and styling controls, and a configurable method to extend a user selected number of the most recent current time frame CISD levels beyond the last candle.
At its core, CISD is designed to identify moments when price behavior suggests a meaningful shift in control, where one side of the market has effectively “taken delivery” and the prior state has changed. The script watches price swings, then tracks specific candle state transitions that can act like triggers. When the conditions are met, it prints a CISD level as a horizontal line originating from the candle that defined the trigger and extending to the detection candle, creating a clear reference level that can behave like a decision point for future price interaction. In practice, those levels often act as areas where price may react, reject, or accept, because they represent the point where a meaningful state change was confirmed by price behavior rather than by a simple moving average or lagging trend filter.
The indicator also includes swing based liquidity tracking to provide context around potential liquidity events. It detects swing highs and swing lows using a pivot period you control, then maintains those swing levels as “liquidity lines” until they are either mitigated or expire after a set number of bars. When price wicks into one of those swing liquidity levels and confirms the mitigation, the script records that event. If a CISD trigger happens shortly after, and the new state change occurs with evidence that opposing liquidity was just taken, the script flags that as a stronger event by marking it on the chart. This is meant to separate normal CISD signals from those that occur after a sweep, because a sweep plus a decisive state change is often more meaningful than a state change that happens in the middle of noise.
The user controls in the calculations section determine how sensitive or selective the CISD detection is. The noise filter controls how strict the script is about qualifying the internal structure that leads to a CISD event. Higher values reduce noise and typically produce fewer, more selective CISD levels, while lower values will produce more frequent levels that may be less reliable in choppy conditions. The swing period controls how far back the script looks when identifying pivot highs and lows, which changes how “major” a swing must be to count as liquidity. The expiry bars setting controls how long older liquidity levels remain active before they stop updating or are removed, and the liquidity lookback determines how recently a swing mitigation must have occurred for the script to treat the CISD as happening with a sweep.
Visually, the script colors candles based on the current CISD trend state. When a bearish CISD is detected, the trend state flips bearish and candles are shaded using the bearish color with a user controlled transparency blend, and when a bullish CISD is detected the trend state flips bullish and candles are shaded using the bullish color. This makes the tool useful not only for marking levels, but also for keeping a simple “state” view on the chart so you can see when the indicator believes control has shifted. If you enable the option to use HTF trend for candle coloring, then the candle shading can reflect the higher time frame trend state instead of the local chart state, which is helpful when you want to trade a lower time frame while staying aligned with the higher time frame CISD bias.
The modifications add a higher time frame CISD layer so you can see more significant CISD levels from a chosen HTF while trading on a lower time frame chart. When enabled, the script computes CISD on the higher time frame through a request security call and then draws HTF CISD lines onto your current chart. You can require confirmed HTF signals only, which means the HTF CISD will print only after the HTF candle closes, reducing repaint style behavior and preventing the level from appearing and disappearing mid-candle. The HTF CISD lines keep the original bullish and bearish color scheme, and you can choose whether they render as solid or dashed to visually separate HTF structure from current time frame structure. The script can also place a label on the HTF CISD level, showing the selected HTF, for example “15 min HTF CISD,” and you can control the label background color, text color, size, and a horizontal offset so the label sits to the right of the current price rather than directly on top of the level.
The other key modification is the extension system for the current time frame CISD levels. The original script draws CISD levels from the origin candle to the detection candle, which is the “normal” behavior and is still preserved for all CISD levels. The enhancement allows you to choose how many of the most recent current time frame CISD levels you want to extend past the last candle by a defined number of bars. This is designed for traders who want their freshest decision levels projected into the future so they can be used as immediate references for reaction, acceptance, rejection, entries, or targets, without cluttering the chart by extending every single historical level. Because the extension uses the original line and simply moves the line’s end point to bar index plus your offset, it extends cleanly from the true starting point with no visual gap, and it automatically updates as new bars print. When a level is no longer within the most recent group, the script restores the original endpoint so older CISD lines revert back to normal and do not continue extending.
To use the indicator effectively, start by choosing whether you want it to be a current time frame decision tool, a higher time frame structure tool, or both. If you are trading lower time frames, enabling HTF CISD with confirmed only is usually the cleanest way to stay aligned with the dominant structure while avoiding levels that shift during an unclosed HTF candle. Then tune the swing period and noise filter to your market. If you are seeing too many levels in chop, increase the noise filter and consider a longer swing period so only larger structural transitions qualify. If you are missing important shifts, reduce the noise filter slightly so the script becomes more responsive. For execution, treat CISD levels like state change reference prices. When price returns to a bullish CISD level, look for acceptance above it to confirm continuation or rejection below it to warn of failure, and do the inverse for bearish levels. The liquidity sweep markers are especially useful as a context filter, because a CISD that occurs after a sweep often represents a more forceful transition where one side grabbed liquidity and then reversed state, which can create cleaner follow-through or stronger reaction zones.
Overall, this modified version keeps AlgoAlpha’s original CISD and liquidity framework intact, but adds the two things traders typically need when using a state change concept in live execution: the ability to overlay higher time frame CISD structure on a lower time frame chart, and the ability to project only the most relevant recent CISD levels into future bars so the levels are immediately actionable without turning the chart into a wall of extended lines.
Relative Valuation Oscillator [QuantAlgo]🟢 Overview
The Relative Valuation Oscillator identifies statistical price deviations from fair value using logarithmic price analysis and standard deviation bands. It calculates how far current price has deviated from its mean on a logarithmic scale, normalized by volatility, to generate a centered oscillator that highlights periods when price is statistically stretched above or below its historical average, helping traders identify potential mean reversion opportunities and extreme valuation conditions across different timeframes and markets.
🟢 How It Works
The indicator's core methodology lies in its statistical approach to price valuation, where deviations are measured using logarithmic returns and normalized by standard deviation:
log_price = math.log(close)
mean_log_price = ta.sma(log_price, lookback_period)
standard_deviation = ta.stdev(log_price, lookback_period)
valuation_score = (log_price - mean_log_price) / standard_deviation
First, the script converts price to logarithmic form to account for percentage-based price movements rather than absolute dollar changes, ensuring the indicator works consistently across different price levels and asset classes.
Then, it calculates the mean log price over the specified lookback period to establish a baseline fair value reference:
mean_log_price = ta.sma(log_price, lookback_period)
Next, standard deviation measurement quantifies the typical volatility of log price around this mean, providing a statistical framework for defining normal versus extreme price behavior:
standard_deviation = ta.stdev(log_price, lookback_period)
The valuation score is then derived by measuring how many standard deviations the current log price sits from its mean, creating a normalized oscillator that fluctuates around zero:
valuation_score = (log_price - mean_log_price) / standard_deviation
Finally, threshold-based signal detection identifies extreme conditions when the valuation score exceeds user-defined standard deviation multiples:
is_overvalued = valuation_score > threshold_mult
is_undervalued = valuation_score < -threshold_mult
This creates a statistical mean reversion system that identifies when price has deviated significantly from its historical average on a volatility-adjusted basis, providing traders with objective measurements of relative over or undervaluation.
🟢 Signal Interpretation
▶ Undervalued Zone (Below Negative Threshold): Oscillator falling below the negative threshold line indicates price has deviated significantly below its statistical mean = Potential long/buy opportunities for mean reversion strategies
▶ Overvalued Zone (Above Positive Threshold): Oscillator rising above the positive threshold line indicates price has deviated significantly above its statistical mean = Potential short/sell or profit-taking opportunities
▶ Fair Value Range (Between Thresholds): Oscillator remaining between positive and negative threshold lines indicates price is trading within normal statistical bounds. Within this range, the zero line acts as a directional filter: oscillator above zero but below the upper threshold suggests bullish trend/momentum with price trading above its statistical mean = Trend-following long positions can be maintained; oscillator below zero but above the lower threshold suggests bearish trend/momentum with price trading below its statistical mean = Trend-following short positions can be maintained. The oscillator can remain in these directional zones during sustained trends until mean reversion occurs, signaled by crosses back toward zero or transitions to the opposite extreme threshold.
▶ Zero Line Crosses: Oscillator crossing above zero indicates transition from below-average to above-average valuation, confirming shift to bullish momentum = Potential trend-following long entry; crossing below zero indicates transition from above-average to below-average valuation, confirming shift to bearish momentum = Potential trend-following short entry or long exit. These crosses can signal both the start of directional trends and early mean reversion from extreme conditions.
🟢 Features
▶ Preconfigured Presets: Three optimized parameter sets for different trading approaches and timeframes. "Default" provides balanced sensitivity for swing trading on 4-hour and daily charts, generating signals at statistically significant deviations. "Fast Response" delivers more frequent signals for intraday trading on 5-minute to 1-hour charts, reacting quickly to short-term deviations with increased signal frequency. "Smooth Trend" focuses on major extremes for position trading on daily to weekly timeframes, filtering noise to identify only the most significant statistical outliers.
▶ Built-in Alerts: Five alert conditions enable automated monitoring of valuation extremes and transitions. "Overvalued Threshold Crossed" triggers when the oscillator crosses above the positive threshold, signaling potential overvaluation. "Undervalued Threshold Crossed" activates when the oscillator crosses below the negative threshold, signaling potential undervaluation. "Crossed Above Fair Value (0)" and "Crossed Below Fair Value (0)" provide alerts for zero line transitions, indicating shifts between above-average and below-average valuation. "Any Extreme Valuation" offers a combined alert for any threshold breach regardless of direction, allowing traders to monitor both extremes with a single alert setup.
▶ Color Customization: Six visual themes (Classic, Aqua, Cosmic, Cyber, Neon, plus Custom) accommodate different chart backgrounds and visual preferences, with distinct colors for overvalued, undervalued, and fair value conditions. Optional background highlighting with adjustable transparency (0-100%) tints the main chart background during extreme valuation periods, providing immediate visual context without requiring continuous oscillator monitoring. Optional overlay signals display small circle markers directly on the price chart above bars during overvaluation and below bars during undervaluation, allowing correlation of statistical extremes with specific price levels and candlestick patterns.
Q-Trend + Keltner Squeeze ZonesThe indicator you are using is a **custom combination** of two distinct tools overlaid on the same chart in TradingView: **Q-Trend** (by tarasenko_) and a **Keltner Channel Squeeze** setup (with Bollinger Bands for squeeze detection). The result is a visual system designed to identify trend direction and manage positions with volatility-aware levels.
### 1. Q-Trend Component
**Purpose**: Determines the overall trend bias and generates entry/continuation signals.
**How it works** (core logic):
- It calculates a dynamic **trend line** (often labeled "Q-Trend Line" when visible) as the midpoint between the highest and lowest price over a long lookback period (default 200 bars).
- An **ATR-based buffer** (epsilon = ATR × multiplier, default 1.0) is added/subtracted to create upper and lower threshold bands around this trend line.
- Signals occur when price crosses or decisively moves beyond these thresholds:
- **Buy signal** → price breaks above the upper threshold (trend line + epsilon).
- **Sell signal** → price breaks below the lower threshold (trend line – epsilon).
- **Strong signals** incorporate additional conditions based on proximity to recent range extremes.
- Bar coloring (blue for bullish, red for bearish by default) and optional labels/arrows reinforce the trend direction.
**Practical role in your setup**:
- Acts as the **primary trend filter**.
- You only consider long positions when the chart shows bullish coloring/signals, and short positions when bearish.
### 2. Keltner Channel Squeeze Component
**Purpose**: Identifies periods of low volatility (compression) and potential directional breakouts, while providing dynamic support/resistance and trailing levels.
**How it works**:
- **Center line** → 20-period EMA of close (orange when visible) — serves as your visual midpoint reference.
- **Inner bands** → Center ± (ATR × inner multiplier). Default inner = 1.8 ATR.
- **Outer bands** → Center ± (ATR × outer multiplier). Default outer = 3.3 ATR.
- **Bollinger Bands** (optional, default hidden) → 20-period SMA ± 2 standard deviations — used only internally to detect a **squeeze** (when BB width < inner Keltner width).
- **Squeeze breakout arrows**:
- Lime up arrow below bar → bullish breakout (close above upper inner band after squeeze).
- Red down arrow above bar → bearish breakout (close below lower inner band after squeeze).
- **Labels** appear at key events:
- "SQUEEZE BREAK UP" / "SQUEEZE BREAK DOWN" on initial breakout.
- "REBALANCE UP" / "REBALANCE DOWN" when price returns inside the inner band after a breakout (potential mean-reversion or failure).
**Visual zones** (when fills are enabled):
- Upper red zone (between inner and outer upper bands) → potential short/rejection area in downtrends.
- Lower blue zone (between inner and outer lower bands) → potential long/rejection area in uptrends.
### Your Overall Strategy (as Described)
This is a **trend-following system with volatility-based scaling and protection**. It is designed to enter/add to positions in the direction of the prevailing trend while using the Keltner structure for timing and risk management.
**Key rules you follow**:
1. **Trend filter first** — Confirm direction with Q-Trend:
- Bullish (blue bars, Buy/Strong Buy signals) → only consider long trades.
- Bearish (red bars, Sell/Strong Sell signals) → only consider short trades.
2. **Addition (scaling in)**:
- In an **uptrend**: Add to longs when price pulls back **below the centerline** (mid Keltner/EMA) or touches/rejects the **inner lower band**.
- In a **downtrend**: Add to shorts when price rallies to the **inner upper band**.
- Rationale: These are temporary retracements within the trend, not reversals. Scaling here improves average entry price.
3. **Entry trigger**:
- Often initiated or confirmed by a Q-Trend Buy/Sell signal.
- Keltner breakout arrows (lime/red) can provide additional timing confirmation.
4. **Trailing stop-loss**:
- For **long positions**: Trail stop-loss below the **outer lower band** (lower_outer).
- For **short positions**: Trail stop-loss above the **outer upper band** (upper_outer).
- As price moves favorably, the outer band follows (via the shifting EMA + ATR), automatically locking in gains.
- Activate/tighten the trail upon entry (e.g., after a Buy signal or breakout arrow).
**Risk considerations**:
- Use position sizing appropriate to account risk (e.g., 1–2% per trade).
- The outer bands widen in high volatility → more room to breathe but larger potential loss.
- Avoid forcing trades in choppy/range-bound markets (Q-Trend signals become less reliable).
- Backtest on your specific instrument/timeframe (e.g., futures like ES/NQ) to validate behavior.
This setup rewards patience: wait for clear trend alignment (Q-Trend), add on volatility-supported pullbacks (Keltner inner/mid), and let winners run while protecting with adaptive trailing levels (Keltner outer). If you would like clarification on any parameter, visual adjustment, or addition of alerts for your exact rules, please specify.
CRR Market StructureCRR — Market Structure (Educational) is an educational chart overlay designed to help traders visualize market structure and price behavior in a clear, objective way.
This indicator focuses on:
Swing structure (HH, LH, HL, LL)
Break of Structure (BOS)
Change of Character (ChoCH)
Current market range
Optional internal Fibonacci levels
Optional confirmation filters (ATR, Volume, MACD, Gap detection)
Important
This script is NOT a trading strategy.
It does NOT generate buy or sell signals, does NOT predict future price, and does NOT provide financial advice.
It is strictly a visual and educational tool to support discretionary analysis.
How to Use This Indicator
This tool is intended to be used as a context and structure guide, not as a signal generator.
Market Structure Reading
HH / HL → Bullish structure
LH / LL → Bearish structure
Observe how price reacts after BOS or ChoCH events.
BOS vs ChoCH
BOS confirms continuation in the current trend.
ChoCH highlights a potential structural shift.
Strength is visually differentiated using optional filters.
Range Awareness
Yellow dotted lines represent the current active range.
Useful for identifying consolidation, expansion, or compression phases.
Fibonacci Context (Optional)
Internal Fibonacci levels visualize retracements inside the last structure range.
Designed for context only, not entries.
Community Usage Guidelines
This indicator is built to encourage shared learning and discussion:
Share charts showing clean BOS / ChoCH examples.
Compare structure behavior across different markets and timeframes.
Discuss price behavior, not signals.
Use screenshots to explain why structure matters.
If you publish ideas using this indicator:
Focus on market structure explanation.
Avoid calling entries or targets.
Keep analysis educational and transparent.
Final Notes
Market structure is not about prediction, but about understanding price behavior.
This tool aims to help traders see the market more clearly, reduce noise, and develop stronger analytical skills.
If you find this indicator useful:
Like
Share insights
Collaborate respectfully with the community
Scalp Master EliteWe present Scalp Master Elite 👑
This is an advanced trading indicator designed to identify high-probability reversal and take-profit zones 📍.
It combines a dynamic EMA + ATR channel 📊 with multiple confirmation indicators (RSI, Stochastic, CCI, Supertrend, Price Action and more) to reduce noise and false signals 🚫📉.
Thanks to its volatility-adaptive logic 🌊, the indicator works perfectly for scalping and intraday trading ⚡, while also adapting smoothly to higher timeframes and long-term trades 📈⏳.
Inverted bullish / bearish triangle signals 🔺🔻 are followed by one confirmed target per setup 🎯, helping traders manage exits with clarity and discipline.
Optional targets 🎯, smart alerts 🔔, ATR-based filters 📐 and a real-time win-rate table 🏆 provide full trade context with clean and intuitive visuals 🧠✨.
Topscore SMC Dashboard v7.2 DUAL + Liquidity + HTF FVGThis is a highly advanced **Smart Money Concepts (SMC) & ICT (Inner Circle Trader)** trading suite. It automates the analysis of market structure, liquidity, and imbalances across multiple timeframes to provide high-probability trade setups.
Here is a breakdown of how it works, its features, and how to trade with it.
---
### 1. Key Features & Logic
#### **A. Liquidity Pools (BSL / SSL)**
* **What it does:** It identifies "Equal Highs" (BSL - Buy Side Liquidity) and "Equal Lows" (SSL - Sell Side Liquidity).
* **Visuals:**
* **Red Dashed Lines:** BSL (Resistance/Liquidity above).
* **Green Dashed Lines:** SSL (Support/Liquidity below).
* **The "Sweep":** When price pierces these lines and reverses, the script marks it as **"💰 BSL/SSL Swept"**. In SMC, a sweep is often a precursor to a reversal.
#### **B. Fair Value Gaps (FVG) - Dual Timeframe**
* **LTF FVG (Lower Timeframe):** Detects standard gaps on your *current* chart (Standard Boxes).
* **HTF FVG (Higher Timeframe):** Uses `request.security` to look inside a higher timeframe (default is 1 Hour/60min) and projects those gaps onto your current chart.
* **Benefit:** Allows you to trade a 5-minute chart while seeing 1-hour "Magnet" levels without switching screens.
#### **C. Probability Engine**
* The script calculates a "Win Probability" % based on a confluence checklist. It adds points for:
1. **Liquidity Sweeps:** (+40 points) Highest weight.
2. **HTF FVG Alignment:** (+30 points) Trading into a higher timeframe gap.
3. **Trend Alignment:** (+15 points) Is price above/below the 50 SMA?
4. **FVG Quality:** (+10 points) Size and clarity of the gap.
* **Dual Calculation:** It calculates the score for **BOTH Long and Short** scenarios simultaneously and highlights the stronger side.
#### **D. Smart Risk Management**
* **Stop Loss (SL):** It doesn't just use a fixed number. It intelligently places SL behind:
* The recent Liquidity Sweep wick.
* The boundary of an FVG.
* A recent Swing High/Low.
* **Take Profit (TP):** Calculated based on your defined Risk:Reward Ratio (default 1:2).
---
### 2. The Dashboard (Top Right) explained
The dashboard is your "Cockpit." Here is how to read it row by row:
| Row | Description |
| --- | --- |
| **Entry** | Shows current price (or your manual entry price if set in settings). |
| **Liquidity** | Tells you if a pool (BSL/SSL) has just been swept or if active pools exist. |
| **HTF** | Status of the Higher Timeframe. e.g., "Bull FVG" means price is inside a 1H Buy zone. |
| **LONG / SHORT** | Shows the Probability Score for both directions. The stronger side will have a Star (⭐). |
| **SL / TP** | The exact price levels for Stop Loss and Take Profit calculated by the script. |
| **RR / Status** | Shows Risk:Reward and flashes **"HIGH PROB!"** if score > 65%. |
| **Confluence** | Lists *why* the score is high (e.g., "SSL Swept, HTF Bull FVG"). |
---
### 3. How to Trade using this Indicator
#### **Scenario 1: The Reversal Setup (High Probability)**
1. **Wait for a "Sweep":** Look for price to cross a Dotted Line (Liquidity Pool) and generate a **"💰 Swept"** label.
2. **Check HTF:** Ideally, this sweep happens inside a Higher Timeframe FVG (Large colored box).
3. **Check Dashboard:** Look for the probability score to turn **Green (>65%)**.
4. **Entry:** Enter when the dashboard confirms the setup.
5. **Execution:** Place your SL and TP exactly where the lines on the chart indicate.
#### **Scenario 2: Trend Continuation**
1. **Trend Check:** Price is trending (e.g., creating higher highs).
2. **Retracement:** Price pulls back into a **LTF FVG** (small box) or **HTF FVG** (large box).
3. **Confirmation:** Dashboard shows "Confluence: Uptrend, Quality FVG".
4. **Trade:** Take the trade in the direction of the trend.
---
### 4. Settings Guide (Inputs)
* **General Settings:**
* `Show LTF/HTF FVG`: Toggle boxes on/off.
* `Max boxes to keep`: Increase if you want to see history, decrease to make the chart faster.
* **HTF Settings:**
* `HTF Timeframe`: If you scalp M1/M5, set this to "60" (1 Hour). If you trade H1, set this to "240" (4 Hour) or "D" (Daily).
* **Liquidity Settings:**
* `Liquidity Lookback`: Higher number = Major swing points only. Lower number = Minor internal liquidity.
* **Trade Setup Calculator:**
* `Entry Price`: Leave at 0 for "Live" pricing. Set a specific price if you are planning a Limit Order and want to see where the SL/TP would be.
* `Risk:Reward`: Default is 2.0. Change to 1.5 or 3.0 based on your style.
### 5. Pro Tips for this Script
1. **Don't follow blindly:** A 90% probability on the dashboard is mathematical based on *past* logic, not a guarantee of the future.
2. **Best Timeframes:** This works best on **M5 and M15** for execution, with the HTF setting set to **H1 or H4**.
3. **The "Sweep" is Key:** The highest probability setups usually involve a Liquidity Sweep (Stop Hunt) *before* the move. If there is no sweep, the setup is weaker.
นี่คือคำอธิบายฉบับภาษาไทยสำหรับอินดิเคเตอร์ **"SMC Dashboard v7.2 DUAL + Liquidity + HTF FVG"** ครับ
ตัวนี้ถือเป็นเครื่องมือระดับ "All-in-One" สำหรับสายเทรด **SMC (Smart Money Concepts)** และ **ICT** ที่ช่วยวิเคราะห์โครงสร้างตลาด สภาพคล่อง (Liquidity) และช่องว่างราคา (FVG) ให้แบบอัตโนมัติ พร้อมคำนวณความน่าจะเป็นในการเข้าเทรดให้ด้วย
---
### 1. หลักการทำงานและฟีเจอร์เด่น
#### **A. การหา Liquidity (สภาพคล่อง / จุดกิน Stop Loss)**
* **BSL (Buy Side Liquidity):** เส้นประสีแดงด้านบน (แนวต้านที่มีคนวาง SL ไว้เยอะ)
* **SSL (Sell Side Liquidity):** เส้นประสีเขียวด้านล่าง (แนวรับที่มีคนวาง SL ไว้เยอะ)
* **The Sweep (การกวาด):** เมื่อราคาแทงทะลุเส้นประเหล่านี้แล้วดึงกลับ ระบบจะขึ้นป้ายเตือนว่า **"💰 BSL/SSL Swept"**
* *เทคนิค:* ในสาย SMC การเกิด Sweep คือสัญญาณการกลับตัวที่ทรงพลังมาก (แปลว่ารายใหญ่เก็บของครบแล้ว)
#### **B. Fair Value Gaps (FVG) แบบ 2 Timeframe**
* **LTF FVG (กล่องเล็ก):** คือ Gap ใน Timeframe ปัจจุบันที่คุณเปิดอยู่
* **HTF FVG (กล่องใหญ่):** ระบบจะไปดึงข้อมูลจาก **Timeframe ใหญ่** (ค่ามาตรฐานคือ 1 ชั่วโมง) มาวาดเป็นกล่องบนกราฟปัจจุบันให้
* *ประโยชน์:* ทำให้คุณเทรด M5 แต่เห็นแนวรับ/ต้านสำคัญของ H1 ได้ทันทีโดยไม่ต้องสลับหน้าจอ
#### **C. ระบบคำนวณความน่าจะเป็น (Probability Engine)**
ระบบจะให้คะแนน (Score) ว่าฝั่งไหนน่าเล่นกว่ากัน โดยดูจาก:
1. มีการกวาด Liquidity (Sweep) หรือไม่? (+40 คะแนน)
2. ราคาอยู่ในโซน HTF FVG หรือไม่? (+30 คะแนน)
3. เทรนด์เป็นขาขึ้นหรือลง? (+15 คะแนน)
4. คุณภาพของ Gap สวยไหม? (+10 คะแนน)
---
### 2. วิธีอ่านค่าบน Dashboard (ตารางมุมขวาบน)
ตารางนี้เปรียบเสมือนหน้าปัดเครื่องบิน บอกข้อมูลสำคัญดังนี้:
| หัวข้อ | ความหมาย |
| --- | --- |
| **Entry** | ราคาปัจจุบัน (หรือราคาที่เราตั้งใจจะเข้า) |
| **Liquidity** | สถานะล่าสุด: บอกว่ามีการ "Sweep" (กวาด) ไปแล้วหรือยัง |
| **HTF** | บอกสถานะ Timeframe ใหญ่ เช่น "Bull FVG" (อยู่ในโซนซื้อของ H1) |
| **LONG / SHORT** | **ไฮไลท์สำคัญ:** บอก % ความน่าจะเป็นของทั้งสองฝั่ง ฝั่งไหนคะแนนเยอะกว่าจะมีดาว (⭐) |
| **SL / TP** | จุด Stop Loss และ Take Profit ที่ระบบคำนวณให้แนะนำ |
| **RR / Status** | อัตราส่วนกำไรต่อขาดทุน ถ้าคะแนนเกิน 65% จะขึ้นว่า **"HIGH PROB!"** (น่าเข้ามาก) |
| **Confluence** | เหตุผลสนับสนุน: ระบบจะบอกว่าทำไมถึงให้คะแนนสูง (เช่น เพราะมี Sweep + เทรนด์ขาขึ้น) |
---
### 3. วิธีการเทรด (How to Trade)
#### **ท่าไม้ตาย 1: สวนเทรนด์ (Reversal Setup)**
1. **รอสัญญาณ Sweep:** รอให้ราคาแทงทะลุเส้นประ (Liquidity) แล้วหดไส้กลับ (ขึ้นป้าย 💰 Swept)
2. **ดู Dashboard:** คะแนนความน่าจะเป็นต้องเป็นสีเขียว (>65%)
3. **เข้าออเดอร์:** กด Buy/Sell ตามทิศทางที่กลับตัว
4. **วาง SL/TP:** ตามเส้นที่ระบบขีดให้บนกราฟ (SL จะอยู่หลังไส้เทียนที่ไปกวาดมา)
#### **ท่าไม้ตาย 2: ตามเทรนด์ (Continuation)**
1. **ดูเทรนด์:** กราฟเป็นขาขึ้น (ราคายืนเหนือเส้น SMA 50)
2. **รอย่อ:** ราคาย่อตัวลงมาในกล่อง **FVG** (ทั้งกล่องเล็กหรือกล่องใหญ่)
3. **เช็ค Dashboard:** ช่อง Confluence ขึ้นว่า "Uptrend, Quality FVG"
4. **เข้าออเดอร์:** Buy ตามน้ำขึ้นไป
---
### 4. การตั้งค่าที่แนะนำ (Settings)
* **HTF Timeframe:**
* ถ้าคุณเทรด **M1 - M5** แนะนำให้ตั้ง HTF เป็น **"60" (1 ชั่วโมง)**
* ถ้าคุณเทรด **M15** แนะนำให้ตั้ง HTF เป็น **"240" (4 ชั่วโมง)**
* **Risk:Reward:** ค่าเดิมคือ 2.0 (กำไร 2 เท่าของความเสี่ยง) สามารถปรับเป็น 1.5 หรือ 3.0 ได้ตามสไตล์
* **Entry Price:** ปกติให้เป็น 0 (ใช้ราคา Real-time) แต่ถ้าจะวาง Pending Order ให้ใส่ราคาที่เราต้องการลงไป ระบบจะคำนวณ SL/TP ใหม่ให้เห็นภาพล่วงหน้า
### 5. ข้อแนะนำเพิ่มเติม
* **อย่าเชื่อ 100%:** แม้ Dashboard จะบอกว่าโอกาสชนะ 90% แต่มันคำนวณจากสูตรคณิตศาสตร์ ตลาดจริงมีความผันผวนเสมอ
* **การกวาด (Sweep) คือหัวใจ:** Setup ที่ดีที่สุดของตัวนี้คือตอนที่เกิด **Liquidity Sweep** แล้วไปชนกับ **HTF FVG** (กล่องใหญ่) จังหวะนี้จะมีโอกาสชนะสูงที่สุดครับ
Scientific MACD Scientific MACD v5.1 — User Guide
An advanced momentum oscillator featuring eight scientifically-modeled moving average algorithms with adaptive signal generation and real-time calculation stability.
Overview
This indicator reimagines the traditional MACD through the lens of multiple scientific disciplines. Rather than relying on simple exponential moving averages, it offers eight distinct mathematical frameworks for calculating trend components—each derived from physics, biology, information theory, or behavioral science. The result is a highly adaptive momentum system that adjusts its sensitivity to market conditions through dynamic error-tracking and hybrid ensemble methods.
Core Architecture
Three-Component Structure
Like the classic MACD, this indicator maintains three essential elements:
Fast Line: Short-term trend component (default: 12 periods)
Slow Line: Long-term trend component (default: 26 periods)
Signal Line: Smoothed derivative of the MACD line (default: 9 periods)
Independent Algorithm Selection
Each component can use any of the eight available moving average types independently. This allows sophisticated combinations such as Wave fast + Entropy slow + Synaptic signal, creating multi-domain confirmation systems.
Scientific Moving Average Models
1. Wave Mechanics MA
A Fourier-inspired bandpass filter that decomposes price into harmonic components. Uses multiple sine wave harmonics (fundamental + overtones) centered around a mean price, with amplitude derived from period range. Higher harmonics receive decreasing weights. Ideal for identifying cyclical price structures and filtering noise through frequency domain analysis.
2. Thermodynamic Entropy MA
Applies information theory concepts to market returns. Calculates Shannon entropy across a 5-bin probability distribution of returns, then uses entropy ratio to adapt smoothing intensity. High entropy (disorder) increases smoothing; low entropy (trending) decreases smoothing. Adds small entropy-based adjustments to center the moving average.
3. Biological Synaptic MA
Implements Hebbian learning rules from neural biology. Maintains adaptive weights for recent price history that strengthen when current price movements correlate with past movements (associative learning). Weights decay exponentially with time and normalize between 0.5 and 2.0. Excels at capturing momentum persistence and regime changes.
4. Quantum Uncertainty MA
Models price as a quantum superposition of states with probabilistic amplitudes. Uses Gaussian distance functions to project current price onto historical basis states, then calculates expectation values. Incorporates decoherence (mixing with previous states) for stability. Naturally handles uncertainty and provides smooth transitions between trend states.
5. Fluid Dynamics MA
Treats price movement as fluid flow with Reynolds number classification. Calculates characteristic velocity, viscosity, and Reynolds number to determine flow regime. Laminar flow (low Re) uses diffusion-dominated smoothing; turbulent flow (high Re) uses advection-dominated smoothing. Includes stability clamps to prevent extreme deviations.
6. Network Cascade MA
Applies epidemiological SIR (Susceptible-Infected-Recovered) models to price trends. Models trend strength as infection rate spreading through market participants. Adaptive smoothing based on active infections (trend strength) with mean reversion as recovery increases. Beta parameter derived from return surprises relative to volatility.
7. Behavioral Economics MA
Incorporates Prospect Theory from psychology. Maintains an adaptation level (reference point) that updates slowly. Applies Tversky-Kahneman value functions with loss aversion (lambda = 2.25) and diminishing sensitivity (alpha = 0.88). Weights prices by psychological value rather than linear distance, emphasizing gains/losses relative to perceived anchors.
8. Hybrid Ensemble MA
Combines all seven models through inverse-error weighting. Tracks exponential moving average of prediction errors for each component model, then assigns weights inversely proportional to recent error. Automatically favors whichever scientific model best fits current market conditions. Displays real-time weight distribution table when enabled.
Signal Generation
Quality-Filtered Crossovers
Standard MACD crossovers are enhanced with statistical quality gates:
Bull Signal: MACD crosses above Signal while MACD is below zero and histogram exceeds 80th percentile of recent values
Bear Signal: MACD crosses below Signal while MACD is above zero and histogram below 20th percentile of recent values
High-Quality Signals
Additional filter requiring signal quality ratio (histogram magnitude divided by histogram volatility) to exceed 2.0. These appear as HQ↑ and HQ↓ markers, indicating statistically significant momentum shifts.
Visualization Features
Dynamic Color Coding
MACD Line: Lime/olive when above signal (bullish), red/maroon when below (bearish)
Histogram: Intensity varies with signal quality—brighter colors indicate stronger statistical significance
Signal Line: Orange for clear differentiation
Zero Line: Dashed gray reference
Volatility Zone: Gray fill between ±1 standard deviation of MACD values
Hybrid Weight Display
When Hybrid MA is selected and Show Hybrid Weights is enabled, a real-time table displays current ensemble weightings for all seven component models as percentages. Updates dynamically as market conditions favor different scientific approaches.
Key Input Parameters
Core Settings
Fast Length: Short-term lookback (2-200, default 12)
Slow Length: Long-term lookback (3-500, default 26)
Signal Length: Smoothing period for signal line (2-100, default 9)
Scientific Parameters
ZigZag Detection Depth: Influences cyclicality measures in Wave and Fluid models (3-20, default 5)
Real-Time Calculation Fix: Blends calculated values with current price during unconfirmed bars to prevent repainting artifacts
MA Configuration
Independent algorithm selection for Fast, Slow, and Signal components. Options: Wave, Entropy, Synaptic, Quantum, Fluid, Cascade, Behavioral, Hybrid.
Display Settings
Toggle for Hybrid weight table visibility.
Operational Workflow
Select appropriate lengths for your timeframe and trading style
Choose MA algorithms based on market characteristics:
Trending markets: Synaptic, Cascade, or Behavioral
Cyclical/ranging markets: Wave or Quantum
High volatility: Entropy or Fluid
Unknown regime: Hybrid (adaptive ensemble)
Enable Real-Time Calculation Fix for live trading to prevent repainting
Monitor standard crossovers for entry signals
Prioritize HQ (High Quality) signals for lower-risk entries
Use histogram color intensity to gauge signal strength
When using Hybrid, monitor weight table to understand which models are currently dominant
Best Practices
Use longer lengths (20-50-10) for swing trading, standard (12-26-9) for day trading
Combine complementary algorithms: fast Wave + slow Entropy captures cycles within noise-filtered trends
Enable Hybrid during regime uncertainty—it automatically selects optimal models
Disable Real-Time Calculation Fix for historical analysis, enable for live signals
Watch for divergence between MACD and price while monitoring histogram quality for confirmation
Volatility zone fill helps identify when MACD moves reach statistical extremes
This indicator provides mathematically sophisticated trend analysis. Algorithm selection significantly impacts signal characteristics—experiment with combinations to find optimal fit for your market and timeframe.
RT Signals & Overlays Signals & Overlays™ is an all-in-one toolkit made up of more than 20+ features primarily focused on generating useful signals & overlays to fulfill any trader's technical analysis needs with relevant data.
Adaptive Buy Sell Signal [AvantCoin]
A comprehensive customized indicator for different markets
🔴Before you start🔴:
Please note that this tool is designed to assist you in analyzing the market, and NOT to make buy/sell decisions for you. You should combine its data with your own strategies and indicators before making any trading choices
====================
Market-Specific Optimizations
Auto-Detection (or Manual Selection)
It automatically detects which market you're trading:
Forex (EUR/USD, GBP/USD, etc.)
Stocks (AAPL, TSLA, etc.)
Indices (NAS100, SPX, etc.)
Commodities (Gold, Silver, Oil)
Crypto (BTC, ETH, etc.)
avantcoin.com
Forex-Specific Features:
✅ Session Filters: Avoids low-liquidity Asian session
✅ Session backgrounds: Green for London/NY overlap (best trading time)
✅ Tighter ADX threshold (20) - good for Forex trends
✅ Lower volatility filter - skips dead zones
⚙️ Min Confluence: 5 (balanced)
⚙️ Cooldown: 5 bars
⚙️ Volume threshold: 1.3x (Forex has consistent volume)
avantcoin.com
Stocks-Specific Features:
✅ Market hours filter: Only signals during NYSE hours.
✅ Gap detection: Avoids trading immediately after large gaps up/down
✅ Higher ADX threshold (22) - Stocks trend differently
✅ Stricter volume requirement (1.5x) - Stocks vary more
⚙️ Min Confluence: 6 (higher quality)
⚙️ Cooldown: 3 bars (stocks move faster)
Indices (Nasdaq, S&P; 500):
✅ Similar to stocks but slightly more lenient
✅ Lower ADX (18) - Indices are smoother
⚙️ Min Confluence: 5
⚙️ Cooldown: 4 bars
Commodities (Gold, Silver, Oil):
✅ Highest ADX requirement (23) - Only trade strong trends
✅ Higher volatility filter (1.6x) - Commodities can be wild
⚙️ Min Confluence: 6
⚙️ Cooldown: 6 bars (avoid whipsaws)
Crypto:
✅ 24/7 trading (no session restrictions)
✅ Lower ADX (15) - Crypto is always volatile
✅ Much higher volume threshold (2.0x) - Crypto volume spikes
⚙️ Min Confluence: 4 (crypto moves fast)
⚙️ Cooldown: 3 bars
📊 Visual Enhancements:
Market Type Badge at top of table (Forex, Stocks, etc.)
Session Status:
Forex: Shows 🟢 LDN/NY, 🔵 London, 🟠 NY, 🔴 Asian
Stocks: Shows 🟢 Open or 🔴 Closed
Session Background Colors on chart (optional)
Current Settings Display: Shows your Min score, ADX threshold, Cooldown
⚙️ How to Use:
For Forex:
Enable "Avoid Asian Session"
Best signals during London/NY overlap
For Stocks:
Enable "Trade Stock Hours Only"
Watch for gap warnings
avantcoin.com
Institutional Reload Zones //@version=5
indicator("MSS Institutional Reload Zones (HTF + Sweep + Displacement) ", overlay=true, max_boxes_count=20, max_labels_count=50)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Inputs
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
pivotLeft = input.int(3, "Pivot Left", minval=1)
pivotRight = input.int(3, "Pivot Right", minval=1)
htfTf = input.timeframe("60", "HTF Timeframe (60=1H, 240=4H)")
emaFastLen = input.int(50, "HTF EMA Fast", minval=1)
emaSlowLen = input.int(200, "HTF EMA Slow", minval=1)
atrLen = input.int(14, "ATR Length", minval=1)
dispMult = input.float(1.2, "Displacement ATR Mult", minval=0.5, step=0.1)
closeTopPct = input.float(0.25, "Close within top %", minval=0.05, maxval=0.5, step=0.05)
sweepLookbackBars = input.int(60, "Sweep lookback (bars)", minval=10, maxval=500)
sweepValidBars = input.int(30, "Sweep active for N bars", minval=5, maxval=200)
cooldownBars = input.int(30, "Signal cooldown (bars)", minval=0, maxval=300)
extendBars = input.int(200, "Extend zones (bars)", minval=20)
showOB = input.bool(true, "Show Pullback OB zone")
showFib = input.bool(true, "Show 50-61.8% zone")
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// HTF trend filter
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
htfClose = request.security(syminfo.tickerid, htfTf, close)
htfEmaFast = request.security(syminfo.tickerid, htfTf, ta.ema(close, emaFastLen))
htfEmaSlow = request.security(syminfo.tickerid, htfTf, ta.ema(close, emaSlowLen))
htfBull = (htfEmaFast > htfEmaSlow) and (htfClose >= htfEmaFast)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// LTF structure pivots
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
atr = ta.atr(atrLen)
ph = ta.pivothigh(high, pivotLeft, pivotRight)
pl = ta.pivotlow(low, pivotLeft, pivotRight)
var float lastSwingHigh = na
var float lastSwingLow = na
if not na(ph)
lastSwingHigh := ph
if not na(pl)
lastSwingLow := pl
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Sweep filter (simple + robust)
// “sweep” = breaks below lowest low of last N bars and reclaims (close back above that level)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
sweepLevel = ta.lowest(low, sweepLookbackBars)
sweepNow = (low < sweepLevel) and (close > sweepLevel)
var int sweepUntil = na
if sweepNow
sweepUntil := bar_index + sweepValidBars
sweepActive = not na(sweepUntil) and (bar_index <= sweepUntil)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Displacement filter
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
cRange = high - low
closeTopOk = close >= (high - cRange * closeTopPct)
dispOk = (cRange >= atr * dispMult) and closeTopOk and (close > open)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// MSS bullish (filtered)
// base MSS: close crosses above last swing high
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
baseMssBull = (not na(lastSwingHigh)) and ta.crossover(close, lastSwingHigh)
var int lastSignalBar = na
cooldownOk = na(lastSignalBar) ? true : (bar_index - lastSignalBar >= cooldownBars)
mssBull = baseMssBull and htfBull and sweepActive and dispOk and cooldownOk
if mssBull
lastSignalBar := bar_index
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Find last bearish candle before MSS for OB zone
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
f_lastBearish(_lookback) =>
float obH = na
float obL = na
int found = 0
for i = 1 to _lookback
if found == 0 and close < open
obH := high
obL := low
found := 1
= f_lastBearish(30)
// Impulse anchors for fib zone (use lastSwingLow to current high on MSS bar)
impLow = lastSwingLow
impHigh = high
fib50 = (not na(impLow)) ? (impLow + (impHigh - impLow) * 0.50) : na
fib618 = (not na(impLow)) ? (impLow + (impHigh - impLow) * 0.618) : na
fibTop = (not na(fib50) and not na(fib618)) ? math.max(fib50, fib618) : na
fibBot = (not na(fib50) and not na(fib618)) ? math.min(fib50, fib618) : na
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Boxes (delete previous, draw new) — SINGLE LINE calls only
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
var box obBox = na
var box fibBox = na
if mssBull
if showOB and not na(obHigh) and not na(obLow)
if not na(obBox)
box.delete(obBox)
obBox := box.new(left=bar_index, top=obHigh, right=bar_index + extendBars, bottom=obLow, bgcolor=color.new(color.gray, 82), border_color=color.new(color.gray, 30))
if showFib and not na(fibTop) and not na(fibBot)
if not na(fibBox)
box.delete(fibBox)
fibBox := box.new(left=bar_index, top=fibTop, right=bar_index + extendBars, bottom=fibBot, bgcolor=color.new(color.teal, 85), border_color=color.new(color.teal, 35))
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Visuals
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
plotshape(mssBull, title="MSS Bull (Filtered)", style=shape.labelup, text="MSS✔", size=size.tiny, color=color.new(color.green, 0), textcolor=color.white, location=location.belowbar)
plot(htfEmaFast, title="HTF EMA Fast", color=color.new(color.orange, 80))
plot(htfEmaSlow, title="HTF EMA Slow", color=color.new(color.purple, 80))






















