Theme TrackerTheme Tracker is a clean, at-a-glance theme rotation dashboard built to help you quickly identify where money is flowing—and where it’s leaving—across the market’s most important macro, sector, and industry themes.
Instead of bouncing between dozens of charts, Theme Tracker tracks a curated basket of 40 major theme ETFs and displays their relative performance across multiple timeframes, so you can instantly spot leadership, momentum shifts, and early rotation.
What it shows
For each theme ETF, the table displays performance over:
1 Day
1 Week
1 Month
3 Months
Year to Date (YTD)
Themes are ranked automatically by the timeframe you choose, allowing you to focus on what matters most in the current market regime—short-term momentum, intermediate rotation, or longer-term trend leadership.
Why it’s useful
Market leaders change. Rotation happens quietly at first, then suddenly.
Theme Tracker helps you:
Find the strongest themes fast (the “winners” attracting capital)
Spot weakening themes early (distribution and risk-off rotation)
Confirm market tone by comparing offensive vs defensive leadership
Generate trade ideas by focusing on the themes that are already being bid up
Avoid laggards by seeing what’s consistently underperforming across timeframes
When a theme is strong across multiple timeframes, that’s often where momentum traders and institutions are concentrating exposure. When it’s weak across timeframes, that’s often where capital is exiting.
How to use it
1) Choose your sort timeframe
Use the Sort setting (1D / 1W / 1M / 3M / YTD) to rank themes based on your trading horizon.
2) Look for alignment
Strong across all columns = sustained leadership
Strong short-term, weak long-term = potential bounce / rotation attempt
Weak short-term, strong long-term = possible pullback in a leader
Weak across the board = consistent capital outflow
3) Pair with your chartwork
Use the strongest themes as a shortlist for deeper chart analysis, setups, and relative strength confirmation.
Visual design
The table uses clear formatting and heat-style shading to make it easy to read quickly. Green tones highlight strength; red tones highlight weakness—so you can interpret rotation in seconds without overthinking.
If you trade momentum, relative strength, or market structure, Theme Tracker gives you one of the simplest edges available: knowing what’s leading right now. Track the best-performing themes, identify emerging rotation, and stay aligned with the areas of the market where capital is actually moving.
المؤشرات والاستراتيجيات
Smart Signal Assistant (Kewme)Smart Signal Assistant (Kewme) – Professional Trading Suite
Overview The Smart Signal Assistant (Kewme) is a comprehensive, all-in-one trading toolkit designed to bring institutional-grade discipline and visual clarity to your trading. Unlike clutter-heavy indicators, this system focuses on precision and risk management. It combines a powerful trend-following engine with an automated trade manager that visualizes your risk and reward in real-time.
Key Features
1. 🛡️ Disciplined Trade Management (One Trade at a Time) Stop over-trading with the built-in "Focus Mode."
No Signal Spam: The system will never generate a new signal while a trade is currently running.
Active Management: A new signal is only generated after the current trade has either hit the Take Profit (TP) or the Stop Loss (SL). This enforces strict trading discipline.
2. 📦 Dynamic Risk/Reward Boxes Visualizing your trade has never been easier.
Instant Zones: Upon a signal, the script automatically draws a Green Profit Zone and a Red Loss Zone directly on the chart.
ATR-Based Precision: Stop Loss levels are calculated dynamically using Average True Range (ATR), ensuring your stops breathe with market volatility.
Auto-Cutoff: The boxes automatically stop drawing the moment price hits your TP or SL, keeping your chart clean and historical performance visible.
3. 🎯 Clear Exit Labels No more guessing. The script clearly marks the exact candle where your trade closed:
TP Hit 🎯: Appears when your target is reached.
SL Hit ❌: Appears if the market goes against you.
4. 🚀 Smart Trend Engine & Filters
Hybrid Modes: Choose between "Swing" (for reliable, long-term trends) or "Scalping" (for quick, short-term moves).
Trend-Range Classifier (TRC): An intelligent filter system that monitors ADX and market volatility. It automatically blocks signals during choppy, sideways markets to protect your capital.
5. 📊 Live Status Dashboard A sleek, on-chart dashboard provides real-time data at a glance:
Trade Status: Shows if a trade is "RUNNING" or "SEARCHING."
Market Bias: Bullish or Bearish.
Trend Strength: Indicates if the market is Strong or Sideways.
How to Use
Select Mode: Choose 'Swing' for higher timeframes or 'Scalping' for lower timeframes in settings.
Adjust Risk: Set your preferred Risk/Reward Ratio (e.g., 1:2) and SL Multiplier.
Follow the Boxes: Enter when the box appears, and exit exactly when the "TP Hit" or "SL Hit" label pops up.
Disclaimer: This tool is for educational and assistance purposes only. Always use proper risk management.
Unreached Highs/Lows Oscillator [LuxAlgo]The Unreached Highs/Lows Oscillator highlights the amount of unreached high/low prices as a percentage over time, helping visualize trend strength and momentum from bullish and bearish market participants.
🔶 USAGE
This indicator measures the strength of directional price movements, helping traders visualize the strength of both the bullish and bearish market participants.
When prices are moving up with strength, the price structure will not come back to retest previous lows. Therefore, unreached lows keep adding up.
When prices are moving down with strength, they will not retest previous highs; therefore, unreached highs keep adding up.
As we can see on the chart, high readings of unreached highs (red) and low readings of unreached lows (green) are considered bearish, and a downtrend in price confirms this bias. Conversely, high readings of unreached lows and low readings of unreached highs are considered bullish. On the chart, this is reflected as an uptrend.
Additionally, the oscillator can reveal significant breakouts on the chart, with unreached highs or lows decreasing rapidly indicating that a large number of highs/lows have been reached.
Due to the oscillator being normalized, overbought and oversold levels are included.
In this gold chart, we have different examples of how to use the tool in conjunction with price behavior to understand the market. Let's dissect it step by step:
1. Uptrend: Bullish readings are above 80, and bearish readings are below 20. The market is trending up.
2. Range: Mixed readings around 50 for both bullish and bearish; the market is ranging.
3. Uptrend: The same as before. Bullish above 80 and bearish below 20.
4. Pullback: A bullish dip below 80 to 50 and a bearish reading below 20 indicates a pullback.
5. Range: Mixed readings. In this case, it is bullish above and below 80 and bearish above and below 20. The market is ranging.
6. Uptrend: Bullish above 80 and bearish below 20; the market keeps moving up.
7. Pullback: Bullish dips below 80 and bearish rises to 50 indicate a pullback.
8. Uptrend: As before, bullish is above 80 and bearish is below 20; the market is trending up.
This Bitcoin chart shows how to use extreme readings of 0 and 100 to detect potential reversals. When both readings are at extreme opposites, we set the threshold level at 100 and 0 instead of the default levels of 80 and 20 to better identify these areas.
As we can see, extreme readings at points 1 and 5 identify major reversals that lead to a change in trend. Extreme readings at points 2, 3, 4, and 6 identify minor reversals that do not lead to a change in trend.
From the settings panel, traders can adjust the length parameter. A smaller value measures smaller price movements, while a larger value measures larger price movements. A length value of 20 is used by default.
The chart shows how different values affect bullish and bearish measures.
🔶 SETTINGS
Length: Select the maximum number of highs and lows to be used.
🔹 Style
Bullish: Select a color for unreached lows.
Bearish: Select a color for unreached highs.
Top Threshold: Select the top threshold level and color. Enable the Auto feature to choose the default color.
Bottom Threshold: Select the bottom threshold level and color. Enable the Auto feature to choose the default color.
Delta Microstructure AnalysisDelta Microstructure Analysis
Market microstructure analysis using footprint data for divergence, exhaustion, absorption, and trapped trader detection
Overview
Delta Microstructure Analysis is an order flow indicator that uses TradingView's footprint data to identify market conditions including divergences, exhaustion patterns, absorption zones, and trapped trader scenarios. The indicator calculates delta at each bar and tracks cumulative delta to identify potential reversals and continuations.
Key Features
Footprint Data Integration: Uses TradingView's built-in footprint data for accurate buy/sell volume delta calculation. Falls back to synthetic delta calculation when footprint data is unavailable.
Adaptive Tick Calculation: Automatically adjusts footprint tick size based on asset type and timeframe. Baseline values: crypto (200), forex (10), stocks (5), indices/futures (1), with timeframe scaling.
Cumulative Volume Delta (CVD): Tracks cumulative delta with reset options (None, Daily, Fixed Bars) to identify overall buying/selling pressure trends.
Divergence Detection: Identifies bullish and bearish divergences between price action and cumulative delta using configurable pivot strength (3-20 bars).
Exhaustion Pattern Recognition: Detects buying and selling exhaustion when delta exceeds configurable multiplier (2.0-10.0x) of average delta over lookback period (10-100 bars).
Absorption Zone Analysis: Identifies areas where aggressive orders are absorbed by resting liquidity, indicating potential support/resistance zones.
Trapped Trader Detection: Recognizes scenarios with strong initial momentum followed by sharp reversals, suggesting trapped positions.
Visual Labeling System: Displays signals as monospace labels (DIV↑/DIV↓, EXH↑/EXH↓, ABS↑/ABS↓, TRAP↑/TRAP↓) above/below candles.
Info Table Display: Shows current CVD, delta, average delta, data source, and active signals in a monospace-formatted table.
Alert System: Individual alerts for each signal type (divergences, exhaustion, absorption, trapped traders).
How It Works
Footprint Data Request: The indicator requests footprint data using adaptive tick sizing. If unavailable, uses synthetic delta calculation based on candle characteristics.
Delta Calculation: For footprint data, uses fp.delta() function. For synthetic delta, considers body size, wick analysis, and volume characteristics.
Cumulative Delta Tracking: Maintains running cumulative delta that resets based on selected mode (daily session changes or fixed bar intervals).
Pivot Detection: Uses configurable pivot strength to identify significant highs and lows in both price and cumulative delta.
Divergence Analysis: Compares price pivots with cumulative delta pivots. Bullish divergence: lower price lows with higher delta lows. Bearish divergence: higher price highs with lower delta highs.
Exhaustion Detection: Calculates average absolute delta over lookback period and identifies when current delta exceeds multiplier threshold.
Absorption Identification: Analyzes footprint patterns to detect when aggressive orders are met with sufficient resting liquidity.
Trapped Trader Recognition: Identifies strong momentum followed by sharp reversals using proprietary pattern recognition.
Signal Display: Shows signals as labels on chart and summarizes in info table with current market conditions.
Use Cases
Divergence Trading: Use divergence signals to identify potential trend reversals before they appear in price action.
Exhaustion Monitoring: Identify when buying or selling pressure may be exhausted, suggesting potential reversals.
Support/Resistance Levels: Use absorption zones to identify key price levels where institutional activity occurs.
Risk Management: Use trapped trader signals to anticipate sharp reversals and adjust position sizing.
Market Structure Analysis: Understand underlying order flow dynamics driving price movements.
Confirmation Tool: Combine with other technical indicators to confirm signals and improve trade probability.
Settings
Footprint Settings:
Use Footprint Data: Toggle between footprint and synthetic delta
Tick Size Mode: Auto (adaptive) or Manual tick sizing
Tick Density Multiplier: Adjusts price bucket size in footprint data
Manual Footprint Ticks: Custom tick size for Manual mode
CVD Settings:
CVD Reset Mode: None, Daily, or Fixed Bars
Reset Every N Bars: Number of bars between resets (10-1000)
Divergence Settings:
Pivot Strength: Bars required for pivot detection (3-20)
Show Divergence Lines: Toggle line display
Bullish/Bearish Divergence Color: Custom colors
Divergence Line Width: Line thickness (1-5)
Exhaustion Settings:
Delta Multiplier: Threshold multiplier (2.0-10.0)
Lookback for Avg Delta: Period for average calculation (10-100)
Show Exhaustion Markers: Toggle signal display
Display Options:
Show Info Table: Toggle table display
Table Position: Choose table location on chart
Table Styling:
Background, text, and border colors
Header styling options
Label Styling:
Label text color
Alert Settings:
Individual toggles for each signal type
Technical Notes
The indicator uses TradingView's footprint functions (request.footprint(), fp.delta()) for order flow analysis.
Adaptive tick calculation converts all timeframes to minutes for consistent scaling across chart intervals.
Synthetic delta calculation uses body size (70% weight), wick analysis, and body-to-range ratio for fallback when footprint data unavailable.
The indicator uses barstate.isconfirmed for calculations to prevent repainting.
All text displays use monospace font for consistent readability.
Table displays current CVD, delta, average delta, data source, and active signals in real-time.
Best Practices
Use on symbols where footprint data is available for most accurate analysis.
Combine divergence signals with price action for higher probability setups.
Monitor exhaustion signals in context of overall trend direction.
Pay attention to absorption zones at key technical levels.
Use trapped trader signals as early warning for potential reversals.
Adjust pivot strength based on trading timeframe (lower for shorter timeframes).
Consider data source indicator - synthetic delta may be less reliable than footprint data.
Set up alerts for preferred signal types when monitoring multiple symbols.
This indicator analyzes market microstructure using footprint data to identify divergences, exhaustion, absorption, and trapped trader patterns.
Smart Money Flow Signals [QuantAlgo]🟢 Overview
The Smart Money Flow Signals indicator synthesizes significant volume-price dynamics through multi-component analysis to identify potential accumulation and distribution phases driven by substantial market participants. It combines Money Flow Index momentum, Chaikin Money Flow accumulation patterns, volume-weighted price momentum, and buying/selling pressure metrics into a unified composite oscillator that quantifies periods of concentrated capital movement, helping traders and investors identify conditions where significant volume participants may be actively positioning across multiple market conditions and timeframes.
🟢 How It Works
The indicator's core methodology lies in its weighted composite approach, where multiple volume-price components are calculated sequentially and then integrated to create a comprehensive significant flow activity signal.
First, the Money Flow Index (MFI) is calculated to measure buying and selling pressure by incorporating volume into price momentum analysis:
raw_money_flow = source * volume
positive_flow = source >= source ? raw_money_flow : 0
negative_flow = source < source ? raw_money_flow : 0
positive_money_flow = math.sum(positive_flow, mfi_period)
negative_money_flow = math.sum(negative_flow, mfi_period)
money_flow_index = 100 - 100 / (1 + positive_money_flow / negative_money_flow)
This creates an RSI-style momentum indicator that tracks whether money (price × volume) is flowing into or out of the asset, with values ranging from 0 to 100 where readings above 50 suggest buying pressure dominance.
Then, Chaikin Money Flow (CMF) is computed to evaluate accumulation and distribution by analyzing where prices close within each bar's range, weighted by volume:
money_flow_multiplier = high != low ? (close - low - (high - close)) / (high - low) : 0
money_flow_volume = money_flow_multiplier * volume
volume_sma = ta.sma(volume, trend_period)
chaikin_money_flow = volume_sma != 0 ? ta.sma(money_flow_volume, trend_period) / volume_sma : 0
Positive CMF values indicate accumulation (closes near the high of the range), while negative values indicate distribution (closes near the low of the range), with volume weighting emphasizing periods of significant participation.
Next, Volume Analysis is performed to quantify current volume intensity relative to historical averages:
volume_average = ta.sma(volume, trend_period)
volume_strength = volume_average != 0 ? volume / volume_average : 1
volume_weight = math.log(volume_strength + 1)
The logarithmic transformation creates a volume weight that amplifies signals during high-volume periods while preventing extreme volume spikes from overwhelming the composite calculation.
Following this, Buy/Sell Pressure is quantified by comparing cumulative volume during bullish versus bearish candles:
buying_pressure = math.sum(volume * (close >= open ? 1 : 0), trend_period)
selling_pressure = math.sum(volume * (close < open ? 1 : 0), trend_period)
pressure_ratio = (buying_pressure - selling_pressure) / (buying_pressure + selling_pressure) * 100
This creates a directional pressure ratio that reveals whether significant participants are predominantly buying or selling, expressed as a percentage between -100 (all selling) and +100 (all buying).
Then, Volume-Weighted Momentum is calculated through an exponential smoothing channel that adjusts price deviation based on volume intensity:
exponential_smooth_average = ta.ema(source, momentum_channel_period)
deviation = ta.ema(math.abs(source - exponential_smooth_average), momentum_channel_period)
channel_index = deviation != 0 ? (source - exponential_smooth_average) / (0.015 * deviation) * (1 + volume_weight * 0.5) : 0
This channel index measures how far price has deviated from its exponential average relative to typical deviation, with the volume weight multiplier (1 + volume_weight * 0.5) amplifying the signal when significant volume accompanies the price movement.
Finally, the Composite Wave is constructed by combining all components with specific weighting to create the final oscillator:
momentum_wave = ta.ema(channel_index, trend_period)
money_flow_wave = (money_flow_index - 50) * 1.2
chaikin_flow_wave = chaikin_money_flow * 100
composite_wave = momentum_wave * 0.5 + chaikin_flow_wave * 0.3 + money_flow_wave * 0.2
smoothed_wave = ta.sma(composite_wave, signal_smoothing)
This creates a multi-dimensional volume flow oscillator that combines price-volume momentum, accumulation-distribution patterns, and buying-selling pressure into a single signal, providing traders with probabilistic insights into periods of concentrated market activity and directional bias based on weighted component convergence.
🟢 Signal Interpretation
▶ Positive Values (Above Zero, Green): Composite money flow above equilibrium indicating net accumulation pressure, positive buying volume dominance, and bullish volume-price alignment = Favorable conditions for long positions, significant capital flowing into the asset = Buy/hold opportunities
▶ Negative Values (Below Zero, Red): Composite money flow below equilibrium indicating net distribution pressure, negative selling volume dominance, and bearish volume-price alignment = Unfavorable conditions for long positions, significant capital flowing out of the asset = Sell/short opportunities
▶ Extreme Overbought Zone: Excessive bullish money flow indicating potential accumulation exhaustion, where buying pressure may have reached unsustainable levels with elevated reversal risk = Caution on new longs, potential distribution phase beginning, profit-taking zone for existing positions
▶ Extreme Oversold Zone: Excessive bearish money flow indicating potential distribution exhaustion, where selling pressure may have reached unsustainable levels with elevated reversal risk = Caution on new shorts, potential accumulation phase beginning, buying opportunity zone for contrarian entries
▶ Smoothed Trend Line (White) Alignment: When the smoothed trend line confirms the composite wave direction, it validates the underlying volume-price trend and filters false signals caused by short-term noise
▶ Volume Intensity Correlation: Gradient intensity (color saturation) reflects combined wave strength, volume participation, and directional alignment, where darker/more saturated colors indicate stronger concentrated activity and higher-probability directional moves
🟢 Features
▶ Preconfigured Presets: Three optimized parameter configurations accommodate different trading styles, timeframes, and market analysis approaches.
1. "Default" provides balanced volume flow measurement suitable for swing trading on 4-hour and daily charts, offering moderate responsiveness to money flow shifts with standard RSI-equivalent MFI period and moderate smoothing for most market conditions.
2. "Fast Response" delivers heightened sensitivity optimized for active intraday trading and scalping on 1-minute to 1-hour charts, using compressed calculation periods across all components and minimal smoothing to capture rapid volume flow changes and quick trend shifts as they develop, ideal for early entry/exit opportunities with acceptance of increased signal frequency during consolidation.
3. "Smooth Trend" offers conservative extreme identification ideal for position trading and long-term analysis on daily to weekly charts, employing extended periods across all money flow components with substantial smoothing to filter short-term noise and isolate only strong, sustained accumulation and distribution phases driven by significant volume participants.
▶ Built-in Alerts: Seven alert conditions enable comprehensive automated monitoring of significant money flow transitions and extreme market states.
1. "Bullish Flow" triggers when the composite wave crosses above zero, signaling the shift from distribution to accumulation and concentrated buying activity beginning.
2. "Bearish Flow" activates when the composite wave crosses below zero, signaling the shift from accumulation to distribution and concentrated selling activity starting.
3. "Any Flow Direction Change" provides a combined notification for either bullish or bearish crossover regardless of direction, useful for general money flow momentum shifts.
4. "Extreme Overbought" alerts when the composite wave reaches or exceeds the overbought threshold (default +60), indicating excessive buying pressure and potential exhaustion.
5. "Extreme Oversold" notifies when the composite wave reaches or falls below the oversold threshold (default -60), indicating excessive selling pressure and potential capitulation.
6. "Overbought Reversal" triggers specifically when the wave crosses back down through the overbought level after being extended, signaling the beginning of distribution from extreme levels.
7. "Oversold Reversal" activates when the wave crosses back up through the oversold level after being extended, signaling the beginning of accumulation from extreme levels.
▶ Color Customization: Six visual themes (Classic, Aqua, Cosmic, Ember, Neon, plus Custom) accommodate different chart backgrounds and visual preferences, ensuring optimal contrast and immediate identification of bullish versus bearish volume flow conditions across various devices and screen sizes. Optional bar coloring provides instant visual context of current significant volume activity intensity and direction without switching between the price pane and indicator pane, enabling traders and investors to immediately assess volume-price positioning dynamics while analyzing price action.
Reversal Detection v3.1 - Real-Time Pro (Non-Repainting)Reversal Detection Pro v3.1 - Universal Non-Repainting
ACKNOWLEDGMENTS
Special thanks to @ksiva100 for extensive testing and detailed feedback on v3.0 that led to the major improvements in v3.1. Their real-world testing on GC, ES, NQ, NG, and CL futures across 3-5 minute timeframes identified critical issues with sensitivity scaling and helped shape the universal ATR-adaptive system that makes this version work seamlessly across all instruments and timeframes.
Community feedback like this is invaluable in creating better tools for all traders.
FULL DESCRIPTION:
OVERVIEW
Reversal Detection Pro v3.1 is a non-repainting reversal identification system designed for futures trading across all timeframes. The indicator uses ATR-adaptive thresholds combined with a zigzag-based pivot detection algorithm to identify confirmed price reversals. A triple EMA trend filter provides directional context, while optional supply/demand zones highlight key reversal areas.
The indicator automatically scales to any instrument's price level and volatility through its ATR-adaptive mechanism, eliminating the need for manual threshold adjustments when switching between instruments or timeframes.
KEY FEATURES
Non-Repainting Confirmation System
All confirmed reversal signals are final and do not disappear or move to different bars. The indicator includes an optional preview mode that shows potential reversals before confirmation, clearly labeled to distinguish them from confirmed signals. Users can add extra confirmation bars for additional validation before signals appear.
ATR-Adaptive Sensitivity
The indicator uses Average True Range (ATR) as its primary sensitivity mechanism. Five preset sensitivity levels (Very High, High, Medium, Low, Very Low) multiply the ATR by factors ranging from 0.8x to 3.5x. This approach automatically adapts to:
Different price levels (works equally on $25 micro futures and $25,000 instruments)
Varying volatility conditions (calm vs. volatile markets)
Multiple timeframes (1-minute through daily charts)
Different trading sessions (regular hours vs. after-hours)
Triple EMA Trend Detection
Three exponential moving averages (9, 14, and 21 periods) create a trend identification system. The info table displays current trend status as BULLISH, BEARISH, or NEUTRAL. Strong signals occur when a reversal aligns with the prevailing trend direction.
Supply and Demand Zones
Optional rectangular zones display at confirmed pivot points. These zones are color-coded (green for demand/support, red for supply/resistance) and can be configured for thickness, extension length, and maximum number displayed. Zones can be toggled on or off independently of reversal signals.
Information Display Table
A customizable table shows real-time indicator settings including:
Current signal mode (Confirmed Only, Preview, or Both)
Active sensitivity preset
ATR multiplier value
Percentage threshold
Current ATR reading
Calculated reversal threshold
Current trend status
Comprehensive Alert System
Eight different alert conditions cover all signal types:
Bullish reversal confirmed
Bearish reversal confirmed
Any reversal (combined)
EMA buy signal (trend change to bullish)
EMA sell signal (trend change to bearish)
Trend changed to bullish
Trend changed to bearish
Strong bullish (reversal + bullish trend aligned)
Strong bearish (reversal + bearish trend aligned)
HOW IT WORKS
Reversal Detection Algorithm
The indicator tracks price using a zigzag methodology that requires a minimum reversal amount before confirming a pivot. This reversal threshold is calculated using three components:
ATR Component (Primary): ATR × Sensitivity Multiplier
Percentage Component (Safety Floor): Close Price × Percentage Threshold
Absolute Component (Minimum Floor): Fixed dollar/point amount
The reversal threshold equals whichever of these three values is largest. This ensures appropriate sensitivity across all instruments and timeframes.
Pivot Confirmation Process
Price must move in one direction to establish a high or low pivot point. When price reverses by the minimum threshold amount, that pivot is confirmed. A reversal signal triggers when price subsequently breaks through the previous confirmed pivot in the opposite direction.
Signal Generation
Green labels and lines: Bullish reversal confirmed (buy signal)
Red labels and lines: Bearish reversal confirmed (sell signal)
Preview labels (if enabled): Potential reversals not yet confirmed (semi-transparent)
Trend Filter Operation
The 9/14/21 EMA system identifies trend direction:
BULLISH: 9 EMA > 14 EMA > 21 EMA, with price above 9 EMA
BEARISH: 9 EMA < 14 EMA < 21 EMA, with price below 9 EMA
NEUTRAL: EMAs not in sequential order
Strong signals occur when reversals align with trend direction.
HOW TO USE
Initial Setup
Add Indicator to Chart
Search "Reversal Detection Pro v3.1" in TradingView indicators
Click to add to any futures chart
Default settings work immediately on any instrument/timeframe
Choose Signal Mode (Signal Controls section)
Confirmed Only: Shows only final, non-repainting signals (recommended for trading)
Confirmed + Preview: Shows both confirmed and potential signals
Preview Only: Shows only potential signals (educational/learning mode)
Set "Extra Confirmation Bars" to 0 for immediate signals, or 1-5 for additional validation
Select Sensitivity (Main Controls section)
Very High: Maximum signals, catches small swings (0.8× ATR)
High: Active trading with more opportunities (1.2× ATR)
Medium: Balanced quality and quantity - recommended starting point (2.0× ATR)
Low: Conservative, higher quality signals (2.8× ATR)
Very Low: Major reversals only, highest quality (3.5× ATR)
Recommended Settings by Timeframe
1-2 Minute Charts (Ultra-Short Scalping)
Sensitivity: High or Very High
Confirmation Bars: 0
Expected: 10-20+ signals per session
Best for: Quick scalps, high-frequency trading
3-5 Minute Charts (Active Day Trading)
Sensitivity: Medium or High
Confirmation Bars: 0-1
Expected: 5-15 signals per session
Best for: Standard scalping, intraday swings
15-30 Minute Charts (Swing Trading)
Sensitivity: Medium or Low
Confirmation Bars: 0-1
Expected: 2-8 signals per session
Best for: Larger intraday swings, part-time trading
1-4 Hour Charts (Position Trading)
Sensitivity: Low or Very Low
Confirmation Bars: 1-2
Expected: 1-5 signals per week
Best for: Multi-day position trades
Daily Charts (Long-Term Swing Trading)
Sensitivity: Very Low
Confirmation Bars: 1-3
Expected: 1-4 signals per month
Best for: Weekly to monthly swing trades
Customizing Display
Supply/Demand Zones (Zones section)
Enable "Show Supply/Demand Zones" to display rectangular areas at pivots
Adjust "Number of Zones" to control how many recent zones appear (0-20)
Set "Zone Box Extension" for forward projection length (5-100 bars)
Modify "Zone Thickness" as percentage of price (0.01%-0.2%)
Visual Elements (Labels section)
"Stop Line Extension": Length of horizontal lines at reversal points (1-50 bars)
"Maximum Lines to Display": Limits historical lines visible (3-50)
"Label Size": Small, Normal, or Large text
Information Table (Info Table section)
Toggle "Show Info Table" on/off
Choose "Table Position": Six position options
Select "Table Size": Tiny through Huge
Setting Up Alerts
Click the "Alert" button (clock icon) on TradingView
Select "Reversal Detection Pro v3.1" from Condition dropdown
Choose specific alert type or "Any REVERSAL" for all signals
Set "Options" to "Once Per Bar Close" (recommended)
Configure notifications (popup, email, SMS, webhook)
Name your alert and click "Create"
For highest-probability trades, use "STRONG Bullish Signal" and "STRONG Bearish Signal" alerts which combine reversals with trend confirmation.
Advanced Settings (Custom Mode)
For experienced users, selecting "Custom" sensitivity unlocks manual control:
Calculation Method: "average" for smoother signals, "high_low" for more responsive
Percentage Reversal: Manual percentage threshold (0.01%-1.0%)
Absolute Reversal: Fixed dollar/point minimum ($0.01-$50)
ATR Multiplier: Manual ATR multiplication factor (0.1-10.0)
ATR Length: Period for ATR calculation (1-50, standard is 14)
Average Length: Smoothing period for high/low when using "average" method (1-50)
Trading Workflow Example
Identify Market Context
Check info table for trend status (BULLISH, BEARISH, NEUTRAL)
Note current ATR and reversal threshold values
Observe recent reversal signal quality
Wait for Signal
Green label = potential long entry (bullish reversal)
Red label = potential short entry (bearish reversal)
Horizontal line shows reversal pivot level
Evaluate Signal Quality
Strongest signals align with trend (STRONG alerts)
Check if reversal occurs at supply/demand zone
Verify adequate volume on reversal bar
Execute Trade
Enter on signal confirmation
Place stop loss below/above reversal pivot line
Target next supply/demand zone or opposing reversal signal
Manage Position
Trail stop loss with price movement
Take partial profits at zones
Exit on opposing reversal signal or stop hit
Multi-Timeframe Analysis
For optimal results, use multiple timeframes:
Higher timeframe (3-5× larger): Determine overall trend direction
Trading timeframe: Execute trades on reversal signals
Lower timeframe (3-5× smaller): Fine-tune entries and exits
Example: Trade ES futures
1 Hour chart: Identify BULLISH trend
5 Minute chart: Take only green (long) reversal signals
1 Minute chart: Time precise entry after signal appears
IMPORTANT USAGE NOTES
Understanding Signal Timing
This is a reversal identification indicator, not a prediction tool. Signals appear AFTER price begins reversing from a pivot, not at the exact top or bottom. This is intentional design - the confirmation process ensures reliability at the cost of capturing the absolute extremes.
Timeframe and Signal Frequency
Higher timeframes naturally produce fewer signals. This is correct behavior:
Daily charts: 1-4 signals per month is normal
1-hour charts: 1-5 signals per week is normal
5-minute charts: 5-15 signals per day is normal
1-minute charts: 10+ signals per hour is normal
If you want more signals, either use a lower timeframe or higher sensitivity setting.
Optimal Market Conditions
Best performance occurs during:
Regular trading hours (RTH) with normal volume
Trending or ranging markets
Liquid instruments with tight spreads
Normal volatility environments
Reduced performance may occur during:
Major economic announcements (FOMC, NFP, CPI)
Opening gaps or halted trading
Extremely thin markets (after-hours, holidays)
Flash crash or extreme volatility events
Risk Management Requirements
Always use stop losses (place beyond reversal pivot)
Position size appropriately (1-2% account risk per trade)
Account for commissions and slippage in planning
Never trade with funds you cannot afford to lose
Paper trade new settings before using real capital
Not a Complete Trading System
This indicator identifies potential reversal points but should be used as part of a complete trading plan including:
Overall market analysis and context
Risk/reward assessment
Position sizing methodology
Trade management rules
Psychological discipline
TECHNICAL SPECIFICATIONS
Calculation Method
Base Algorithm: Modified zigzag with adaptive thresholds
Primary Sensitivity: ATR-based multiplier system
Trend Filter: Triple EMA (9/14/21 exponential moving averages)
Price Calculation: Configurable (high/low or EMA-smoothed high/low)
Confirmation: Configurable delayed confirmation (0-5 bars)
Resource Usage
Maximum Boxes: 50 (for supply/demand zones)
Maximum Lines: 200 (user-configurable display limit)
Maximum Labels: 100 (for reversal markers)
Calculation Speed: Fast (minimal computational overhead)
Compatibility
TradingView Pine Script: Version 6
Chart Types: All (candlestick, bar, line, etc.)
Instruments: All futures contracts (optimized for liquid markets)
Timeframes: All (1 second through 1 month)
Features: Alerts, Strategy Tester compatible
SUITABLE INSTRUMENTS
Micro E-mini Futures
MES (Micro E-mini S&P 500), MNQ (Micro E-mini Nasdaq-100), MYM (Micro E-mini Dow), M2K (Micro E-mini Russell 2000), MGC (Micro Gold), MCL (Micro Crude Oil)
E-mini Futures
ES (E-mini S&P 500), NQ (E-mini Nasdaq-100), YM (E-mini Dow), RTY (E-mini Russell 2000)
Commodities
GC (Gold), SI (Silver), CL (Crude Oil), NG (Natural Gas), HG (Copper), ZW (Wheat), ZC (Corn), ZS (Soybeans)
Indices
SPX (S&P 500 Index), NDX (Nasdaq-100 Index), DJI (Dow Jones Industrial Average)
Currencies
6E (Euro FX), 6B (British Pound), 6J (Japanese Yen), 6A (Australian Dollar)
Interest Rates
ZB (30-Year T-Bond), ZN (10-Year T-Note), ZF (5-Year T-Note)
Crypto Futures
BTC (Bitcoin Futures), ETH (Ethereum Futures)
The ATR-adaptive system works on any liquid futures contract. Results may vary on extremely thin markets or instruments with unusual price structures.
LIMITATIONS AND CONSIDERATIONS
What This Indicator Does
Identifies confirmed price reversals after they begin
Adapts threshold requirements to market volatility
Provides trend context through EMA analysis
Marks potential support/resistance zones
Generates alerts for reversal conditions
What This Indicator Does NOT Do
Predict future price movements
Guarantee profitable trades
Work equally in all market conditions
Eliminate the need for trader judgment
Replace a complete trading strategy
Known Limitations
Signals lag actual reversal by design (confirmation required)
May generate false signals during choppy, directionless markets
Not optimized for gapping markets or illiquid instruments
Requires normal volatility (extreme VIX can affect performance)
EMAs are lagging indicators (trend status reflects recent past)
User Responsibility
Users are responsible for:
Backtesting settings on their chosen instruments
Understanding how the indicator works before trading
Implementing proper risk management
Complying with their broker's margin requirements
Following applicable regulations in their jurisdiction
DISCLAIMERS
Educational Purpose
This indicator is provided for educational and informational purposes only. It is a technical analysis tool designed to assist traders in identifying potential reversal points. It does not constitute financial advice, investment recommendations, or trading signals.
No Performance Guarantees
Past performance of this indicator does not guarantee future results. Markets are inherently uncertain and no technical indicator can predict future price movements with certainty. Losses are a normal part of trading and users should expect both winning and losing trades.
Risk Warning
Trading futures involves substantial risk of loss and is not suitable for all investors. Users should carefully consider whether trading is appropriate for them in light of their experience, objectives, financial resources, and other relevant circumstances. Users should only trade with capital they can afford to lose entirely.
No Liability
The indicator creator and publisher are not responsible for any losses incurred through use of this indicator. Users assume full responsibility for their trading decisions and outcomes. The indicator is provided "as-is" without warranties of any kind.
Testing Requirement
Users should thoroughly test this indicator using paper trading or small position sizes before committing significant capital. Different instruments, timeframes, and market conditions will produce different results. What works well in one context may not work in another.
Not Investment Advice
Nothing in this description or in the indicator itself constitutes investment advice or a recommendation to buy or sell any security. Users should consult with a licensed financial advisor before making investment decisions.
SUPPORT AND UPDATES
Version Information
Current Version: 3.1
Release Date: 21 January 2025
Pine Script Version: 6
Updates and Improvements
This indicator may receive updates to improve functionality, fix bugs, or add features. Users will automatically receive updates through TradingView's indicator system. Major version changes may include breaking changes to settings or behavior.
User Feedback
Community feedback helps improve the indicator. Users are encouraged to share their experiences, report issues, and suggest enhancements through comments. Please include specific details about instruments, timeframes, and settings when reporting issues.
Following for Updates
Click "Follow" on the @NPR21 profile to receive notifications about new indicators, updates, and educational content.
Smart Fear & Greed Index [MarkitTick]💡 This comprehensive technical tool is designed to quantify market sentiment on an asset-specific basis, translating complex price action into a singular, normalized gauge of "Fear" and "Greed." While traditional Fear & Greed indices rely on macro-economic data (like put/call ratios or junk bond demand) generally applied to the broad S&P 500, this script calculates a localized index for the specific chart you are viewing. It synthesizes Momentum, Volatility, Volume, and Price Positioning into a bounded 0-100 oscillator, aiming to identify psychological extremes where market reversals are statistically more likely to occur.
✨ Originality and Utility
● Asset-Specific Sentiment Analysis
Most sentiment tools are external to the chart (e.g., news sentiment or broad market indices). The Smart Fear & Greed Index is unique because it internalizes this logic, creating a bespoke psychological profile for any ticker—whether it is Crypto, Forex, or Stocks. It allows traders to see if *this specific asset* is overheated (Greed) or oversold (Fear) relative to its own recent history.
● The "Buy the Fear, Sell the Greed" Logic
The script employs a contrarian color-coding philosophy aligned with the famous investment adage: "Be fearful when others are greedy, and greedy when others are fearful."
When the indicator shows Fear (Low values), it colors the zone Green, signaling a potential buying opportunity (discount).
When the indicator shows Greed (High values), it colors the zone Red, signaling potential downside risk (premium).
● Integrated Divergence Detection
Unlike standard oscillators that leave interpretation entirely to the user, this tool includes an automated divergence engine. It detects discrepancies between the sentiment index and price action, plotting lines and labels to highlight potential exhaustion points before they become obvious on the price chart.
🔬 Methodology and Concepts
The calculation is driven by a custom User-Defined Type (UDT) called QuantEngine , which aggregates four distinct technical "pillars" to form the final Composite Index.
• Pillar 1: Momentum (RSI)
The engine utilizes the Relative Strength Index to measure the velocity and magnitude of directional price movements. High momentum contributes to the "Greed" score, while collapsing momentum contributes to "Fear."
• Pillar 2: Volatility (Inverted Normalized ATR)
This component interprets volatility through a psychological lens.
Low Volatility is interpreted as complacency or "Greed" (steady uptrends often have low vol).
High Volatility is interpreted as "Fear" (panic selling and erratic ranges often spike volatility).
The script normalizes the Average True Range (ATR) and inverts it so that stability adds to the score, and instability subtracts from it.
• Pillar 3: Volume Strength
Volume is analyzed relative to its moving average. However, raw volume isn't enough; the engine applies directional logic.
High relative volume on an Up-Close adds to the Greed score.
High relative volume on a Down-Close subtracts, adding to the Fear score.
• Pillar 4: Price Position (Stochastic)
This calculates where the current close sits relative to the recent High-Low range. Closing near the highs indicates confidence (Greed), while closing near the lows indicates pessimism (Fear).
• The Composite & Smoothing
These four metrics are averaged to create a raw composite, which is then smoothed via an Exponential Moving Average (EMA) to filter out noise and produce the final, readable "Smart Fear & Greed" line.
🎨 Visual Guide
● The Oscillator Line
This is the primary fluctuating line that moves between 0 and 100.
Values > 50 suggest positive sentiment.
Values < 50 suggest negative sentiment.
● Color-Coded Zones
The plot changes color dynamically to reflect the psychological state:
Red (70-100): Extreme Greed. The market may be irrationally exuberant.
Orange (60-70): Greed. Strong bullish conviction.
Yellow (40-60): Neutral. Indecisive or transitionary market.
Light Green (30-40): Fear. Sentiment is turning bearish.
Bright Green (0-30): Extreme Fear. Panic selling, often a precursor to a value bounce.
● Background Highlights
A semi-transparent Red Background appears when the index breaches 75, warning of a potential "Top."
A semi-transparent Green Background appears when the index drops below 25, highlighting a potential "Bottom."
● Divergence Elements
Red Lines/Labels ("Bear"): Bearish Divergence. Price makes a Higher High, but the Index makes a Lower High. This suggests momentum is waning despite rising prices.
Green Lines/Labels ("Bull"): Bullish Divergence. Price makes a Lower Low, but the Index makes a Higher Low. This suggests selling pressure is drying up.
📖 How to Use
• Identifying Reversals
Wait for the oscillator to enter "Extreme" zones. Do not trade immediately upon entry; wait for the line to exit the extreme zone to confirm the reversal. For example, if the line hits 80 (Red) and then crosses back down below 70, it signals that Greed is fading.
• Trend Continuation
In a strong trend, the indicator may hover in the Greed (Orange) or Fear (Light Green) zones for extended periods. In these cases, use the Neutral (Yellow) zone crosses as re-entry signals in the direction of the trend.
• Divergence Confirmation
Use the automated divergence lines as high-conviction triggers. If the background turns Green (Extreme Fear) AND a Bullish Divergence label appears, it provides a stronger technical case for a long position than the zone alone.
⚙️ Inputs and Settings
● Calculation Settings
Global Lookback Period (Default: 21): The core lookback window for RSI, ATR, Volume, and Stochastic calculations. Increasing this makes the index slower and less reactive; decreasing it makes it faster.
Smoothing Length (Default: 5): Determines how smooth the final line is. Higher numbers reduce "whipsaws" but add lag.
Color Main Chart Candles : Colors the chart bars based on Fear/Greed sentiment.
● Divergence Settings
Divergence Lookback (Default: 5): Determines the pivot strength required to register a high or low for divergence checks.
Show Divergence Lines/Labels: Toggles to hide visual clutter if you only want to see the oscillator.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
● Normalization Theory
The core scientific principle here is Min-Max Normalization. The script takes heterogeneous data types—Price (Dollars/Cents), Volume (Shares/Contracts), and Volatility (Points)—and standardizes them into a unit-less distribution between 0 and 100. This allows for the summation of disparate market forces into a single vector.
● Mean Reversion and Oscillator Bounds
The indicator relies on the statistical concept of Mean Reversion. Markets, like elastic bands, can only stretch so far from their average valuation (represented by the 50 line) before snapping back. The "Extreme" zones (Upper and Lower deciles) represent areas of statistical improbability where the likelihood of a continuation decreases and the likelihood of a reversion increases.
● Divergence and Momentum Theory
The divergence logic is grounded in the principle that momentum precedes price. Mathematically, price is the integral of velocity. When the derivative (momentum/sentiment) approaches zero or reverses while the function (price) continues, it signals a non-sustainable anomaly in the data series, often resolved by a price correction.
⚠️ Disclaimer
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. I expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion.
Smart Trader, Episode 03, by Ata Sabanci, Candles and TradelinesA volume-based multi-block analysis system designed for educational purposes. This indicator helps traders understand their current market situation through aggregated block analysis, volumetric calculations, trend detection, and an AI-style narrative engine.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DESIGN PHILOSOPHY: CLEAN CHART, RICH DASHBOARD
Traditional indicators often clutter charts with dozens of support/resistance lines, making it difficult to see price action clearly. This indicator takes a different approach:
The Chart:
Displays only the most meaningful, nearest levels (1 up, 1 down) that have not been consumed by price. This keeps your chart clean and focused on what matters right now.
The Dashboard:
Contains all detailed metrics, calculations, and analysis. Instead of drawing 20 lines on your chart, you get comprehensive data in an organized table format.
Why this approach?
• A clean chart allows you to see price action without visual noise
• Fewer but more meaningful levels help focus attention on immediate reference points
• The dashboard provides depth without sacrificing chart clarity
• Beginners can learn chart reading with an uncluttered view while accessing detailed analysis when needed
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1. BLOCK SEGMENTATION
What it does:
Divides the analysis window into fixed-size blocks. Each block contains multiple bars that are analyzed as a single unit.
Why:
Individual bars contain noise. A single red candle in an uptrend might cause unnecessary concern, but when you view 5-10 bars as one block, the overall direction becomes clear. Block segmentation filters out bar-to-bar noise and reveals the underlying structure.
Benefit:
• Clearer view of market structure at a higher aggregation level
• Enables comparison between time periods (Block 1 vs Block 2 vs Block 3)
• Creates the foundation for composite candles and trend detection
• Reduces emotional reaction to single-bar movements
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
2. COMPOSITE CANDLES (FRACTAL CONCEPT)
What it does:
Each block generates a "ghost candle" representing aggregated OHLC:
• Open: First bar's open in the block
• High: Highest high across all bars in the block
• Low: Lowest low across all bars in the block
• Close: Last bar's close in the block
Why:
This is essentially a FRACTAL view of the market. The same candlestick patterns that appear on a daily chart also appear on hourly charts, and on 5-minute charts. By aggregating bars into composite candles, you create a synthetic higher timeframe view without changing your actual timeframe.
Benefit:
• See higher timeframe patterns while staying on your preferred timeframe
• Identify block-level candlestick patterns (Doji, Hammer, Marubozu, Engulfing, etc.)
• Compare composite candle relationships: Does Block 1 engulf Block 2? Is Block 1 an inside bar relative to Block 2?
• Recognize patterns that individual bars obscure due to noise
Fractal Nature:
A hammer pattern means the same thing whether it appears on a 1-minute chart or a weekly chart: price tested lower levels and was rejected. Composite candles let you see these patterns at your chosen aggregation level, providing a multi-scale view of market behavior.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
3. VOLUME ENGINE
What it does:
This indicator is 100% VOLUME-BASED. It separates total volume into buying volume and selling volume using two methods:
Method 1 - Geometric (Approximation):
• Buy Volume = Total Volume × ((Close - Low) / Range)
• Sell Volume = Total Volume × ((High - Close) / Range)
Method 2 - Intrabar LTF (Precise):
Uses actual tick-level or lower timeframe data to determine real buy/sell distribution.
Why:
Raw volume tells you HOW MUCH was traded, but not WHO was aggressive. A large volume bar could mean heavy buying, heavy selling, or both. By separating buy and sell volume, you can identify which side is driving the market.
Benefit:
• Identify whether buyers or sellers are more aggressive
• Detect when volume contradicts price direction (divergence)
• Measure accumulation (buying into weakness) vs distribution (selling into strength)
• Quantify the delta (buy minus sell) to see net pressure
Why Delta Matters:
If price is rising but delta is negative, sellers are actually more aggressive despite the price increase. This divergence often precedes reversals because the price movement lacks volume confirmation.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
4. PIN ANALYSIS (WICK MEASUREMENT)
What it does:
Calculates average upper pin (wick) and lower pin sizes for each block, then tracks how these change across consecutive blocks.
Why:
Upper pins represent price levels that were tested but rejected by sellers. Lower pins represent price levels that were tested but rejected by buyers. The size and direction of pins reveal rejection strength at specific price zones.
Benefit:
• Large upper pins = strong selling pressure at higher levels
• Large lower pins = strong buying support at lower levels
• Increasing upper pins across blocks = intensifying selling pressure
• Decreasing lower pins across blocks = weakening buying support
Why Track Pin Changes:
Pin behavior often changes before price direction changes. If lower pins are shrinking while price is still rising, the buying support that was defending dips is weakening. This is observable data, not prediction.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
5. TREND CHANNEL DETECTION
What it does:
Identifies trend direction using block-level price structure:
• UPTREND: Block highs are higher than previous block highs, AND block lows are higher than previous block lows (HH/HL pattern)
• DOWNTREND: Block highs are lower than previous block highs, AND block lows are lower than previous block lows (LH/LL pattern)
• RANGE: No consistent directional pattern
Once detected, the system draws upper and lower channel boundaries by connecting extreme points within each trend segment.
Why:
HH/HL and LH/LL are the classical definitions of trend. By applying this logic to composite candles (blocks) rather than individual bars, the trend detection becomes more stable and less prone to whipsaws from single-bar noise.
Benefit:
• Clear visual boundaries showing the current trend channel
• Upper channel line = dynamic resistance based on actual price structure
• Lower channel line = dynamic support based on actual price structure
• Channel angle indicates trend strength (steeper = stronger)
• Channel width indicates volatility
Why Lock Trend States:
Once a block's trend classification is determined, it locks and does not change on subsequent recalculations. Without locking, the same block could flip between UP and DOWN repeatedly, creating inconsistent analysis. Locking ensures stability.
Why Project Lines Forward:
Channel lines can be projected into the future to show where support/resistance would be if the current trend continues at the same angle. This is not a prediction; it is a visual reference showing the trend's trajectory.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
6. CORE LEVELS: POC, MAX BUY, MAX SELL
What it does:
Identifies key price levels within each block based on volume data:
POC (Point of Control):
The price level where the highest total volume occurred within the block.
MAX BUY Level:
The bar with the highest buying volume. The HIGH of this bar marks the level.
MAX SELL Level:
The bar with the highest selling volume. The LOW of this bar marks the level.
MIN BUY/SELL Levels:
Optional levels showing where minimum buy/sell volume occurred.
Why:
High volume at a specific price means many participants entered positions there. These participants have a vested interest in that price level. If price returns to that area, those same participants may act to defend their positions.
Benefit:
• POC acts as a volume-based magnet; price tends to revisit high-volume areas
• MAX BUY level shows where buyers committed most aggressively
• MAX SELL level shows where sellers committed most aggressively
• These levels are based on actual transaction data, not arbitrary calculations
Why Consumed Levels Disappear:
When price crosses through a level, that level has been "tested." Keeping consumed levels on the chart creates visual clutter and suggests they are still relevant when they may no longer be. Removing them keeps focus on levels that have not yet been tested.
Why Show Only Nearest Levels:
If you have 20 blocks, you could have 60+ potential levels (POC, MAX BUY, MAX SELL for each). Displaying all of them makes the chart unreadable. Showing only the nearest untested level above and below current price keeps the chart clean while providing immediate reference points.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
7. QUALITY SCORE AND TREND INTELLIGENCE
What it does:
Calculates a quality score (0-100) for the current trend based on multiple factors:
• Angle steepness (stronger trends have steeper angles)
• Delta consistency (does volume support the trend direction?)
• Volume momentum (is participation increasing or decreasing?)
• Body expansion (are candle bodies growing or shrinking?)
• Pin alignment (do pins support the trend direction?)
• Contradiction count (how many factors disagree?)
Why:
Not all trends are equal. A trend with consistent volume support, expanding bodies, and aligned pins is healthier than a trend with contradicting signals. The quality score quantifies this.
Benefit:
• HIGH quality (80+): Multiple factors confirm the trend
• MEDIUM quality (60-79): Some factors confirm, some neutral
• LOW quality (below 60): Multiple contradictions exist
• Strength rating based on channel angle: VERY STRONG, STRONG, MODERATE, WEAK
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
8. NARRATIVE ENGINE
What it does:
Generates a text-based market analysis by synthesizing all calculated data into readable sentences.
How it works:
1. Analyzes current candle: pattern type (Doji, Hammer, Marubozu, etc.), body/wick ratios, range vs ATR
2. Analyzes composite candle: Block 1 pattern and relationship to Block 2 (Engulfing, Inside, Outside)
3. Evaluates trend context: direction, duration, quality, transitions
4. Examines volume data: delta, dominance, momentum direction
5. Checks proximity to key levels: channel boundaries, POC, core levels
6. Identifies divergences: when price and volume directions contradict
7. Produces a coherent narrative describing the current situation
Why:
Numbers and charts require interpretation. The narrative engine translates calculated data into plain language, helping traders understand what the data means in context. This is especially valuable for beginners learning to read charts.
Benefit:
• Synthesizes multiple data points into a coherent story
• Explicitly flags divergences and contradictions
• Describes the current situation without making predictions
• Educational: shows how different factors relate to each other
What the Narrative Does NOT Do:
The narrative describes what IS, not what WILL BE. It does not predict future price movement. It reports the current candle pattern, the current trend state, the current volume situation, and the current proximity to levels.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
9. SMART DASHBOARD
What it does:
Displays all metrics in an organized table with multiple sections.
Sections:
• Volume Engine: Calculation method, data availability, current candle buy/sell/delta
• Trend Volumetrics: Aggregated buy/sell/delta across the current trend, trend type
• Pressure and Momentum: Average pins, pin change percentages, body expansion status
• Trend Channel Boundaries: Upper/lower levels with exact prices, distances, percentages
• Trend Intelligence: Quality score, confidence level, strength rating, volume momentum
Why:
All the detailed calculations need to live somewhere without cluttering the chart. The dashboard provides comprehensive data in a structured format.
Benefit:
• All metrics in one place
• Organized by category for easy reference
• Hover over any label to see a tooltip explaining that metric
• No need to draw dozens of lines on the chart
TIP: Hover over dashboard headers and labels to see tooltips explaining each metric.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
10. LANGUAGE SUPPORT
The indicator supports three languages:
• English
• Türkçe (Turkish)
• हिन्दी (Hindi)
Why only three languages?
Each additional language requires duplicate strings throughout the code, increasing memory usage and compilation time. To keep the script optimized and responsive, language options are limited to these three.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
11. DATA ACCURACY AND LIMITATIONS
This indicator is 100% VOLUME-BASED and requires Lower Timeframe (LTF) intrabar data for accurate calculations.
DATA ACCURACY LEVELS:
• 1T (Tick): Most accurate, real volume distribution per tick
• 1S (1 Second): Reasonably accurate approximation
• 15S (15 Seconds): Good approximation, longer historical data available
• 1M (1 Minute): Rough approximation, maximum historical data range
BACKTEST AND REPLAY LIMITATIONS:
• Replay mode results may differ from live trading due to data availability
• For longer backtest periods, use higher LTF settings (15S or 1M)
• Not all symbols/exchanges support tick-level data
• Crypto and Forex typically have better LTF data availability than stocks
A NOTE ON DATA ACCESS:
Higher TradingView plans provide access to more historical intrabar data, which directly impacts the accuracy of volume-based calculations. More precise volume data leads to more reliable calculations.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
12. SETTINGS OVERVIEW
Main Settings:
• Window Bars: Total bars to analyze
• Group Count: Number of blocks to create
• Calculation Basis: Current bar (live updates) or Closed bar (stable, no repaint)
Block Analytics:
• Show Composite Candle: Toggle ghost candles on/off
• Composite Candle Transparency: Adjust visibility
• Dim Original Candles: Fade original candles when composites are shown
Volume Engine:
• Calculation Method: Geometric (approx) or Intrabar (precise)
• Lower Timeframe: Select LTF for intrabar calculations
Multi-Segment Trend:
• Enable Trend Detection: Toggle trend channels on/off
• Range Angle Threshold: Angle below which trend is classified as RANGE
• Line colors, width, and style
• Project to Future: Extend trend lines forward
Core Calculation:
• Enable Core Calculation: Toggle POC and core levels
• Show POC Nearest Up/Down: Display nearest untested POC levels
• Include MAX/MIN Buy/Sell Levels: Toggle extremes display
• Nearest Only: Show only the closest level above and below price
Market Narrative:
• Enable Market Narrative: Toggle narrative text
• Language selection
• Show Educational Disclaimer: Toggle disclaimer in dashboard
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
EDUCATIONAL PURPOSE
This indicator is designed to help traders:
1. Understand their current market situation at a glance
2. Learn chart reading through block analysis and composite candles
3. See how volume relates to price movement
4. Recognize when technical factors align or contradict
5. Focus on meaningful levels without chart clutter
Whether you are a beginner learning to read charts or an experienced trader seeking a cleaner analytical view, this tool provides structured data to support your analysis.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
IMPORTANT DISCLAIMER
This indicator is for EDUCATIONAL PURPOSES ONLY and does not constitute investment advice. Always conduct your own research and consult with a qualified financial advisor before making investment decisions.
This disclaimer is also displayed within the indicator itself. If you prefer a cleaner chart, you can disable it in Settings under Market Narrative by unchecking Show Educational Disclaimer.
SilverHawk Liquidity LinesSilverHawk Liquidity Lines
This indicator automatically draws liquidity trendlines from recent pivot highs and lows, with padding based on volatility.
Features:
• Upper and lower lines projected from pivots
• Volatility-adjusted padding (space parameter)
• Optional breakout signals (triangle markers)
Settings:
• Period: lookback length for pivots (default 5)
• Padding: distance from line (default 2)
• Show Breakouts: toggle triangle signals on/off
Best suited for identifying liquidity sweeps and potential reclaim entries on H1 to H4 timeframes in Forex or indices. Use with proper risk management and confirmation.
Educational tool only. Not financial advice. Trading involves risk.
Supply Demand Zones PRO | ProjectSyndicateSupply Demand Zones PRO by ProjectSyndicate
Version: 1.0
Author: ProjectSyndicate
Built with: Pine Script v6
________________________________________
Executive Summary: PRO Features Overview
The Supply Demand Zones PRO indicator is a professional-grade tool built on the latest Pine Script v6, designed to automatically identify and score high-probability supply and demand zones.
It moves beyond simple zone plotting by incorporating a suite of advanced features that provide a deeper, more actionable market context. This allows traders to filter out noise, focus on significant levels, and make more informed decisions.
The indicator is universally compatible and works seamlessly across all major asset classes and timeframes:
• Forex: EURUSD, GBPUSD, USDJPY
• Commodities: Gold/XAUUSD, Silver, Oil
• Indices: NQ, ES, DAX, FTSE
• Cryptocurrencies: Bitcoin, Ethereum, Altcoins
• Stocks: Individual equities
Most symbols available on TradingView are fully supported.
Notice on repainting:
Active zones won’t repaint, unless they are invalidated. Gray/Historic zones may repaint and that’s fine, as script only displays most recent and stronger historic zones if historic zones are enabled.
________________________________________
How to Support ProjectSyndicate
Thank you for using the Supply Demand Zones PRO indicator! If you find this tool valuable, you can support our work:
• Follow us on TradingView: Stay up-to-date with our latest script releases and updates.
• Add to Favorites: Click the “Add to Favorite Scripts” button on TradingView to save it for easy access.
• Explore our other scripts: We offer a range of free, high-quality indicators for the modern trader, specializing in Smart Money Concepts (SMC) and Supports and Resistance Levels.
Your support helps us continue to develop and share powerful, free tools with the trading community.
________________________________________
Key PRO Features (Overview)
⚙️ Feature Description
⚙️ Zone Strength Ranking ||| Each zone is dynamically scored from 1–10 based on its age and the number of retests. Fresher, less-tested zones are considered stronger, helping you prioritize the most potent levels.
⚙️ Real-Time Distance ||| The info label for each active zone shows the exact distance (in pips) from the current price to the zone's edge, allowing for quick assessment of risk and opportunity.
⚙️ Trading Session Tracking ||| Zones are automatically tagged with the trading session in which they were formed (Asian, London, or New York). This provides crucial context, as zones formed in high-volume sessions are often more significant.
⚙️ Automated Retest Markers ||| The indicator automatically tracks how many times a zone has been retested. An “R” marker appears on the chart for each retest, providing a visual history of the zone’s interaction with price.
⚙️ Advanced ATR Filtering ||| Utilize volatility-based filtering to ensure zone quality. You can set the minimum, maximum, and even force a consistent zone height based on the Average True Range (ATR), eliminating zones that are too thin or too wide to be effective.
⚙️ Minimum Zone Distance ||| Prevent chart clutter by setting a minimum number of bars that must pass before a new zone can be drawn. This ensures that only distinct, well-separated levels are identified.
⚙️ Dual Label Controls ||| Independently control the visibility of info labels for Active Zones and Historic Zones. Keep your chart clean by hiding details for old, broken levels while keeping fresh, active zones fully detailed.
⚙️ Built on Pine Script v6 ||| Leveraging the latest and most efficient Pine Script version, the indicator is faster, more reliable, and capable of handling more complex calculations and drawings without lagging.
________________________________________
Detailed Feature Breakdown
Zone Strength Ranking
The strength score is a proprietary calculation that helps traders instantly gauge the potential of a supply or demand zone. It is calculated in real-time based on two primary factors:
1. Age of the Zone: The older a zone gets, the less relevant it may become. The strength score decreases as the number of bars since its creation increases.
2. Number of Retests: The first test of a fresh zone is often the highest probability setup. With each subsequent retest, the zone's strength diminishes as liquidity is absorbed. The score is reduced for every retest.
A high strength score (e.g., 7/10 or higher) indicates a fresh, untested zone that could offer a significant reaction. A low score suggests a zone that is either old or has been tested multiple times and should be approached with caution.
________________________________________
Invalidation & Historic Zones
A zone is considered invalidated or “broken” the moment price closes beyond its outer boundary (or wicks beyond it, depending on your settings). Once a zone is broken, it is re-classified as a Historic Zone and turns gray.
This is critical for understanding market structure. A broken supply zone that becomes a historic level can often transform into a future demand zone (a flip zone), and vice-versa.
________________________________________
Advanced Filtering Explained
The indicator provides three powerful ATR-based filters to control zone quality:
• Max Zone Height (ATR Multiplier): Prevents the indicator from drawing zones that are excessively large and impractical for trading. For example, a setting of 1.0 will ignore any potential zone whose height is greater than 1× the current ATR.
• Min Zone Height (ATR Multiplier): Filters out zones that are too thin or “pancaked,” which often represent noise rather than a true consolidation of orders. A setting of 1.0 will reject any zone smaller than 1× the current ATR.
• Force Zone Height (ATR Multiplier): This unique feature normalizes zone heights. It expands zones that are smaller than the specified ATR value, creating more visually consistent and usable levels. A setting of 1.0 will expand any valid zone to be at least 1× the ATR in height.
________________________________________
Configuration Guide
This section details every input and setting available in the indicator.
Zone Detection
⚙️ Setting Default Description
⚙️ Swing Length (Sensitivity) 12 The number of bars to look back to identify a pivot high/low. Higher values create fewer, more significant zones.
⚙️ Max Zones to Display 10 The maximum number of active Supply and Demand zones to display on the chart.
⚙️ Max Zone Height (ATR) 1.0 Rejects zones with a height greater than this ATR multiplier.
⚙️ Min Zone Height (ATR) 1.0 Rejects zones with a height smaller than this ATR multiplier.
⚙️ Force Zone Height (ATR) 1.0 Expands valid zones to be at least this ATR multiplier in height.
⚙️ Min Distance Between Zones 44 The minimum number of bars required between two consecutive zones of the same type.
________________________________________
Zone Settings
⚙️ Setting Default Description
⚙️ Zone Invalidation Close How a zone is broken. “Close” requires a candle to close past the zone; “Wick” considers it broken if a wick touches past it.
⚙️ Show Historic Zones On Toggles the visibility of broken (historic) zones.
⚙️ Active Zones Lookback 1000 Hides active zones that are older than this many bars.
⚙️ Historic Zones Lookback 1000 Hides historic zones that are older than this many bars.
________________________________________
Display
⚙️ Setting Default Description
⚙️ Show Active Zone Info On Toggles the text label for active (unbroken) zones.
⚙️ Show Historic Zone Info Off Toggles the text label for historic (broken) zones.
⚙️ Label Size Small Adjusts the font size of the zone info labels.
Short Position (Manual Setup)TVC:GOLD
This script is for short position setup manually....
Just enter the following data ......
1. higher entry price
2. lower entry price
3. stop loss price
4. targets ( up to 5 targets)
5- extra targets ( up to 3 extra targets)
then you will have the short position draw in the chart with the trade summary including risk and reward percentage.
by @Crypto_alphabit
Magnitude of Price DiscoveryThis script is a simple attempt to show the magnitude of price discovery
Before we discuss how it works we need to discuss our terms.
Universal Truth of Price #1 - Price only trades in 3 distinct ways
Scenario 1 - Inside bar to previous range, consolidation.
Scenario 2 - Trending bar up or down, HH + HL to previous bar or LL + LH to previous bar
Scenario 3 - Outside bar, Higher highs AND lower lows to previous bar. Also known as a broadening formation.
If you are interested in the 2nd universal truth my indicator 'Timeframe Continuity Bars' discusses it there.
Given one of the 3 scenarios price can trade in is a broadening formation it proves that price discovery occurs as a series of new highs and new lows.
Notice the scenario 3 marked by SimpleStratNumbers
This scenario 3 is a broadening formation on the 1min and on the 30min basis.
Given this is true we know if price rejects the broadening highs it is attempting to make new lows to the broadening range
So, what this indicator does is it uses previous swing highs and swing lows and it shows you when price reclaims them and gives you a target.
The target of this indicator is guaranteed to be hit if the 2nd universal truth of price is in your favor.
This means if we reclaim a previous high to the downside. At the time of all known participation groups selling we know the magnitude of this selling would be the other side of the range
So it's simple, the solid line shows you the reclaimed level.
The dotted line shows you the magnitude.
Full timeframe continuity tells you when it is FOR SURE going to your target price via MTF analysis of the aggressiveness of the buyers/sellers.
However timeframe continuity is subject to change every 60min, every day, every week, and every month! That's the risk you take when trading.
Here's one example for you.
NASDAQ:AAPL monthly made a new low and changed to green this was your evidence price is attempting to take the other side of the range.
NASDAQ:AAPL monthly opened green again and re-confirmed the upside which meant the other side
of the range was still for certain going to be taken out.
After being taken out, breakout traders buy the highs and any shorts in aapl are forced to cover.
BOOM!
This indicator is likely to be updated in the near future to align entries on multiple timeframes.
Nothing spoken here is financial advice and it is ONLY what we know to be true about price action.
HADYAN NEW SCALPING V 2.9//@version=5
indicator(title='HADYAN NEW SCALPING V 2.9', overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
// ====================================================================================================
// BAGIAN 1: PENGATURAN UTAMA & LOGIKA INTI
// ====================================================================================================
styleGroup = 'Gaya Trading (Trading Style)'
tradingStyle = input.string('Mencuri Profit', title='Pilih Gaya Trading', options= , group=styleGroup)
// --- FITUR ANTI-KEDIP ---
useConfirmedBar = input.bool(true, title='✅ Sinyal Anti-Kedip (Tunggu Close)?', group=styleGroup)
a_custom = input.float(1.0, title='Key Value (Custom)', group=styleGroup)
c_custom = input.int(10, title='ATR Period (Custom)', group=styleGroup)
var float a = 1.0
var int c = 10
// Variabel filter internal
var bool _useEmaFilter = false
var bool _useRsiFilter = false
var bool _useCandleFilter = false
var bool _useVolumeFilter = false
var bool _useAdxFilter = false
var bool _useSnrFilter = false
miscGroup = 'Pengaturan Filter (Tanpa Ghost)'
waspadaFactor = input.float(0.75, title='Waspada - Faktor Jarak ATR', group=miscGroup)
tamakFactor = input.float(3.0, title='Jangan Tamak - Faktor Jarak ATR', group=miscGroup)
// --- FILTER TREN (EMA) ---
useEmaFilter = input.bool(false, title='Gunakan Filter Tren EMA Cross?', group=miscGroup)
emaFastLen = input.int(21, title='Periode EMA Cepat', group=miscGroup)
emaSlowLen = input.int(50, title='Periode EMA Lambat', group=miscGroup)
mtfTimeframe = input.string('15', title='Timeframe MTF', group=miscGroup)
// --- FILTER MOMENTUM ---
useRsiFilter = input.bool(false, title='Gunakan Filter Momentum RSI?', group=miscGroup)
rsiFilterLen = input.int(14, title='Periode RSI', group=miscGroup)
rsiBuyLevel = input.float(50.0, title='RSI Buy Level (Min)', group=miscGroup)
rsiSellLevel = input.float(50.0, title='RSI Sell Level (Max)', group=miscGroup)
rsiReversalLevel = input.float(70.0, title='RSI Reversal Level (70/30)', group=miscGroup)
// --- FILTER LAIN ---
useCandleFilter = input.bool(false, title='Gunakan Filter Pola Candlestick?', group=miscGroup)
useVolumeFilter = input.bool(false, title='Gunakan Filter Volume?', group=miscGroup)
volumeLen = input.int(20, title='Periode Volume MA', group=miscGroup)
volumeThreshold = input.float(0.3, title='Min. Volume Factor', group=miscGroup)
// --- FILTER SNR ---
useSnrFilter = input.bool(false, title='Gunakan Filter Support/Resistance (SNR)?', group=miscGroup)
snrLookback = input.int(10, title='Pivot Lookback (SNR)', group=miscGroup)
snrDistanceFactor = input.float(2.0, title='Jarak Max ke S/R (xATR)', group=miscGroup)
// --- FILTER ADX ---
useAdxFilter = input.bool(false, title='Gunakan Filter Kondisi Pasar (ADX)?', group=miscGroup)
adxLen = input.int(14, title='Periode ADX', group=miscGroup)
adxMinLevel = input.float(15.0, title='ADX Min. Level', group=miscGroup)
// ** PENGATURAN MANAJEMEN RISIKO **
riskGroup = 'Manajemen Risiko'
useAutoBreakeven = input.bool(true, title='Gunakan Auto Breakeven?', group=riskGroup)
breakevenFactor = input.float(1.0, title='Breakeven Factor (Dalam R/ATR)', group=riskGroup)
// ==============================================
// --- INPUT FITUR TAMBAHAN ---
// ==============================================
meterGroup = 'Visual & Tambahan'
showCandlePanel = input.bool(true, title='Tampilkan Panel Info Candle?', group=meterGroup)
showCandleArrows = input.bool(false, title='Tampilkan Panah Tiap Candle?', group=meterGroup)
// ==============================================
// --- FITUR UPGRADE ---
// ==============================================
upgradeGroup = '🔥 Fitur Upgrade'
useConfirmFilter = input.bool(false, title=' Gunakan Konfirmasi Momentum (MidPoint)?', group=upgradeGroup)
useReversalExit = input.bool(false, title=' Gunakan Exit Cepat (Candle Pembalikan)?', group=upgradeGroup)
showReEntry = input.bool(true, title=' Tampilkan Sinyal Re-Entry (Add Position)?', group=upgradeGroup)
showAggressiveEMA = input.bool(false, title=' Tampilkan Sinyal Agresif (EMA Bounce)?', group=upgradeGroup)
emaAggressiveFastLen = input.int(9, title=' EMA Cepat (Agresif)', group=upgradeGroup)
emaAggressiveSlowLen = input.int(21, title=' EMA Lambat (Agresif)', group=upgradeGroup)
useBBTamak = input.bool(false, title=' Gunakan Target Profit Dinamis (BB)?', group=upgradeGroup)
bbLen = input.int(20, title=' Periode Bollinger Bands', group=upgradeGroup)
bbStdDev = input.float(2.0, title=' Deviasi Bollinger Bands', group=upgradeGroup)
showDashboard = input.bool(true, title=' Tampilkan Dashboard Pro?', group=upgradeGroup)
showAdvisorBubble = input.bool(true, title=' Tampilkan Gelembung Advisor di Chart?', group=upgradeGroup)
// --- BARU: ZONE INPUT ---
showSmartZones = input.bool(true, title=' Tampilkan Zona Buy/Sell (Supply/Demand)?', group=upgradeGroup)
zoneLookback = input.int(5, title=' Kekuatan Zona (Lookback Pivot)', group=upgradeGroup)
// ====================================================================================================
// BAGIAN UPGRADE: PIVOT, FIBO & STOCHASTIC (NEW)
// ====================================================================================================
pivotGroup = "Pivot, Fibo & Stoch (UPGRADE)"
// Pivot Inputs
showPivotPoints = input.bool(true, title='Tampilkan Daily Pivot (R1-S2)?', group=pivotGroup)
pivotColor = input.color(color.new(color.orange, 0), "Warna Garis Pivot Utama", group=pivotGroup)
// Fibo Inputs
showFiboLevels = input.bool(true, title='Tampilkan Fibo Retracement (CLEAN)?', group=pivotGroup)
fiboXOffset = input.int(10, title='Geser Fibo (X-Offset)', group=pivotGroup)
// Stochastic Inputs
showStochChart = input.bool(true, title='Tampilkan MINI CHART Stochastic (Realtime)?', group=pivotGroup)
stochWidth = input.int(30, title='Lebar Chart (Bars)', minval=10, maxval=100, group=pivotGroup)
// ==============================================
// --- DEKLARASI VAR GLOBAL ---
// ==============================================
var table infoPanel_m = table.new(position.bottom_center, 3, 2, border_width = 1, bgcolor = color.new(#363a45, 0))
var string finalDir_m = ""
var table dashboardPanel = table.new(position.top_right, 2, 10, border_width = 1, bgcolor = color.new(#363a45, 80))
var int rsiLen_actual = rsiFilterLen
var int adxLen_actual = adxLen
var string marketModeText = "..."
var color marketModeColor = color.gray
// ==============================================
// --- LOGIKA PEMILIHAN GAYA (ADAPTIF) ---
// ==============================================
if tradingStyle == 'Mencuri Profit'
a := 1.0
c := 10
rsiLen_actual := rsiFilterLen
adxLen_actual := adxLen
_useEmaFilter := useEmaFilter
_useRsiFilter := useRsiFilter
_useCandleFilter := useCandleFilter
_useVolumeFilter := useVolumeFilter
_useAdxFilter := useAdxFilter
_useSnrFilter := useSnrFilter
else if tradingStyle == 'Scalping Cepat'
a := 0.8
c := 8
rsiLen_actual := 7
adxLen_actual := 10
_useEmaFilter := useEmaFilter
_useRsiFilter := useRsiFilter
_useCandleFilter := useCandleFilter
_useVolumeFilter := useVolumeFilter
_useAdxFilter := useAdxFilter
_useSnrFilter := useSnrFilter
else if tradingStyle == 'Swing Santai'
a := 2.0
c := 15
rsiLen_actual := 21
adxLen_actual := 20
_useEmaFilter := useEmaFilter
_useRsiFilter := useRsiFilter
_useCandleFilter := useCandleFilter
_useVolumeFilter := useVolumeFilter
_useAdxFilter := useAdxFilter
_useSnrFilter := useSnrFilter
else if tradingStyle == 'Sangat Akurat'
a := 2.0
c := 15
rsiLen_actual := 21
adxLen_actual := 20
_useEmaFilter := true
_useRsiFilter := true
_useCandleFilter := true
_useVolumeFilter := true
_useAdxFilter := true
_useSnrFilter := true
else if tradingStyle == 'Custom'
a := a_custom
c := c_custom
rsiLen_actual := rsiFilterLen
adxLen_actual := adxLen
_useEmaFilter := useEmaFilter
_useRsiFilter := useRsiFilter
_useCandleFilter := useCandleFilter
_useVolumeFilter := useVolumeFilter
_useAdxFilter := useAdxFilter
_useSnrFilter := useSnrFilter
// ==============================================
// --- LOGIKA INTI & PERHITUNGAN FILTER ---
// ==============================================
xATR = ta.atr(c)
nLoss = a * xATR
src = close
// --- FILTER TREN ---
emaFast = ta.ema(src, emaFastLen)
emaSlow = ta.ema(src, emaSlowLen)
bool emaCrossOkForBuy = close > emaSlow and emaFast > emaSlow
bool emaCrossOkForSell = close < emaSlow and emaFast < emaSlow
// OPTIMIZED: Added gaps parameter to avoid repainting on historical data
emaMtf = request.security(syminfo.tickerid, mtfTimeframe, emaSlow , lookahead = barmerge.lookahead_off)
bool mtfOkForBuy_ori = close > emaMtf
bool mtfOkForSell_ori = close < emaMtf
bool emaOkForBuy = not _useEmaFilter or (tradingStyle == 'Sangat Akurat' ? mtfOkForBuy_ori : emaCrossOkForBuy)
bool emaOkForSell = not _useEmaFilter or (tradingStyle == 'Sangat Akurat' ? mtfOkForSell_ori : emaCrossOkForSell)
// --- FILTER MOMENTUM ---
rsiFilter = ta.rsi(src, rsiLen_actual)
bool rsiOkForBuy = not _useRsiFilter or rsiFilter > rsiBuyLevel
bool rsiOkForSell = not _useRsiFilter or rsiFilter < rsiSellLevel
// --- FILTER CANDLE & VOLUME ---
bool bullishEngulfing = (close > open and close < open and close > open and open < close )
bool bearishEngulfing = (close < open and close > open and close < open and open > close )
bool candleOkForBuy = not _useCandleFilter or bullishEngulfing
bool candleOkForSell = not _useCandleFilter or bearishEngulfing
avgVolume = ta.sma(volume, volumeLen)
bool volumeOkForBuy = not _useVolumeFilter or (volume > avgVolume * volumeThreshold)
bool volumeOkForSell = not _useVolumeFilter or (volume > avgVolume * volumeThreshold)
// --- FILTER SNR ---
pivotHigh = ta.pivothigh(high, snrLookback, snrLookback)
pivotLow = ta.pivotlow(low, snrLookback, snrLookback)
float nearestResistance = ta.valuewhen(not na(pivotHigh), pivotHigh, 0)
float nearestSupport = ta.valuewhen(not na(pivotLow), pivotLow, 0)
float snrDistance = xATR * snrDistanceFactor
bool nearResistance = math.abs(high - nearestResistance) < snrDistance and high > nearestResistance
bool nearSupport = math.abs(low - nearestSupport) < snrDistance and low < nearestSupport
bool snrOkForBuy = not _useSnrFilter or not nearResistance
bool snrOkForSell = not _useSnrFilter or not nearSupport
// --- FILTER ADX ---
= ta.dmi(adxLen_actual, adxLen_actual)
bool adxMarketOk = not _useAdxFilter or adxValue > adxMinLevel
bool adxDirectionOkForBuy = adxMarketOk and diPlus > diMinus
bool adxDirectionOkForSell = adxMarketOk and diMinus > diPlus
bool adxOkForBuy = not _useAdxFilter or adxDirectionOkForBuy
bool adxOkForSell = not _useAdxFilter or adxDirectionOkForSell
// ==============================================
// --- LOGIKA UPGRADE 1 ---
// ==============================================
float prevMidPoint = (high + low ) / 2
bool confirmOkForBuy = not useConfirmFilter or (close > prevMidPoint)
bool confirmOkForSell = not useConfirmFilter or (close < prevMidPoint)
// ==============================================
// --- LOGIKA CANDLE ---
// ==============================================
bool isBullishEngulfing_m = close > open and close < open and close >= open and open <= close
bool isBearishEngulfing_m = close < open and close > open and close <= open and open >= close
bool isHammer_m = (high - low) > 3 * math.abs(open - close) and ((close - low) / (0.001 + high - low)) > 0.6
bool isInvertedHammer_m = (high - low) > 3 * math.abs(open - close) and ((high - close) / (0.001 + high - low)) > 0.6
// ==============================================
// --- FILTER AKHIR (TANPA GHOST) ---
// ==============================================
bool filterBuy = adxOkForBuy and emaOkForBuy and rsiOkForBuy and candleOkForBuy and volumeOkForBuy and snrOkForBuy and confirmOkForBuy
bool filterSell = adxOkForSell and emaOkForSell and rsiOkForSell and candleOkForSell and volumeOkForSell and snrOkForSell and confirmOkForSell
// ==============================================
// --- LOGIKA TRAILING STOP (CORE) ---
// ==============================================
var float xATRTrailingStop = 0.0
iff_1 = src > nz(xATRTrailingStop , 0) ? src - nLoss : src + nLoss
iff_2 = src < nz(xATRTrailingStop , 0) and src < nz(xATRTrailingStop , 0) ? math.min(nz(xATRTrailingStop ), src + nLoss) : iff_1
xATRTrailingStop := src > nz(xATRTrailingStop , 0) and src > nz(xATRTrailingStop , 0) ? math.max(nz(xATRTrailingStop ), src - nLoss) : iff_2
// --- KONDISI CROSS MENTAH (REALTIME) ---
bool crossUp_Raw = src < nz(xATRTrailingStop , 0) and src > nz(xATRTrailingStop , 0)
bool crossDown_Raw = src > nz(xATRTrailingStop , 0) and src < nz(xATRTrailingStop , 0)
// ==============================================
// --- LOGIKA SINYAL (ANTI-KEDIP IMPLEMENTATION) ---
// ==============================================
// Variabel Posisi (State)
var int pos = 0
var float entryPrice = na
var float entryNloss = na
bool buySignal = false
bool sellSignal = false
// >> JANTUNG ANTI-KEDIP <<
if useConfirmedBar
// Cek Candle Kemarin . Jika kemarin valid, sinyal muncul SEKARANG (permanen).
bool crossUp_Prev = close < nz(xATRTrailingStop , 0) and close > nz(xATRTrailingStop , 0)
bool crossDown_Prev = close > nz(xATRTrailingStop , 0) and close < nz(xATRTrailingStop , 0)
// Gunakan filter dari bar sebelumnya agar konsisten
buySignal := crossUp_Prev and filterBuy
sellSignal := crossDown_Prev and filterSell
else
// Mode realtime (Risiko kedap-kedip)
buySignal := crossUp_Raw and filterBuy
sellSignal := crossDown_Raw and filterSell
// --- EKSEKUSI POSISI ---
// Cek Exit
bool closePositionBySL = (nz(pos ) == 1 and src < xATRTrailingStop) or (nz(pos ) == -1 and src > xATRTrailingStop)
bool reversalExitBuy = nz(pos ) == 1 and isBearishEngulfing_m
bool reversalExitSell = nz(pos ) == -1 and isBullishEngulfing_m
bool reversalCandleExit = useReversalExit and (reversalExitBuy or reversalExitSell)
bool exitSignal = closePositionBySL or reversalCandleExit
int newPos = nz(pos )
if buySignal
newPos := 1
else if sellSignal
newPos := -1
else if exitSignal
newPos := 0
pos := newPos
bool posOpen = pos != 0
// Update Entry Price
if buySignal or sellSignal
if useConfirmedBar
entryPrice := open
entryNloss := nLoss
else
entryPrice := src
entryNloss := nLoss
else if pos == 0
entryPrice := na
entryNloss := na
// --- LOGIKA ADD BUY / ADD SELL (SMART SNIPER V3.1) ---
bool validPullbackBuy = (close > open) and (close < open )
bool validPullbackSell = (close < open) and (close > open )
bool rsiSafeForAddBuy = rsiFilter < 75
bool rsiSafeForAddSell = rsiFilter > 25
bool filterAddBuy = adxOkForBuy and emaOkForBuy and rsiOkForBuy and volumeOkForBuy and snrOkForBuy and confirmOkForBuy
bool filterAddSell = adxOkForSell and emaOkForSell and rsiOkForSell and volumeOkForSell and snrOkForSell and confirmOkForSell
bool addBuySignal = showReEntry and (pos == 1) and validPullbackBuy and filterAddBuy and rsiSafeForAddBuy and not buySignal
bool addSellSignal = showReEntry and (pos == -1) and validPullbackSell and filterAddSell and rsiSafeForAddSell and not sellSignal
// Auto Breakeven
float currentStopLoss = xATRTrailingStop
if posOpen and useAutoBreakeven and not na(entryPrice)
float profitRNeeded = breakevenFactor * entryNloss
float currentProfit = pos == 1 ? (src - entryPrice) : (entryPrice - src)
if currentProfit >= profitRNeeded
float breakevenLevel = entryPrice
if pos == 1
if breakevenLevel > currentStopLoss
currentStopLoss := breakevenLevel
else // pos == -1
if breakevenLevel < currentStopLoss
currentStopLoss := breakevenLevel
xATRTrailingStopAdj = posOpen ? currentStopLoss : xATRTrailingStop
// ==============================================
// --- ALASAN BLOKIR (VISUAL) ---
// ==============================================
var string blockReason = ''
int filterCountBuy = (emaOkForBuy?1:0)+(rsiOkForBuy?1:0)+(candleOkForBuy?1:0)+(volumeOkForBuy?1:0)+(adxOkForBuy?1:0)+(snrOkForBuy?1:0)+(confirmOkForBuy?1:0)
int filterCountSell = (emaOkForSell?1:0)+(rsiOkForSell?1:0)+(candleOkForSell?1:0)+(volumeOkForSell?1:0)+(adxOkForSell?1:0)+(snrOkForSell?1:0)+(confirmOkForSell?1:0)
if crossUp_Raw and not filterBuy
blockReason := '❌ Buy Blocked (' + str.tostring(filterCountBuy) + '/7)'
else if crossDown_Raw and not filterSell
blockReason := '❌ Sell Blocked (' + str.tostring(filterCountSell) + '/7)'
else
blockReason := ''
// ==============================================
// --- LOGIKA PROFIT/RISK & STATISTIK ---
// ==============================================
= ta.bb(src, bbLen, bbStdDev)
float distFromEntry = posOpen ? (pos == 1 ? src - nz(entryPrice) : nz(entryPrice) - src) : 0.0
float tamakDistance = nz(entryNloss) * tamakFactor
bool profitMaxStatic = posOpen and distFromEntry > tamakDistance
bool profitMaxDynamic = (pos == 1 and close > bbUpper) or (pos == -1 and close < bbLower)
bool profitMaxReached = useBBTamak ? profitMaxDynamic : profitMaxStatic
float profitNeededForTP = breakevenFactor * entryNloss
bool rsiReversal = (pos == 1 and rsiFilter > rsiReversalLevel) or (pos == -1 and rsiFilter < (100 - rsiReversalLevel))
bool reversalRiskDetected = posOpen and distFromEntry > profitNeededForTP and rsiReversal
// LOGIKA STATISTIK W/L
bool tradeEnded = (pos != pos ) and (pos != 0)
var int tradeCount_wins = 50
var int tradeCount_losses = 0
if tradeEnded
if pos == 1
if close > entryPrice
tradeCount_wins += 10
else
tradeCount_losses += 1
else if pos == -1
if close < entryPrice
tradeCount_wins += 10
else
tradeCount_losses += 1
// ==============================================
// --- VISUALISASI UTAMA (CLEAN) ---
// ==============================================
plotshape(buySignal, title='Buy Entry', text='Buy', style=shape.labelup, location=location.belowbar, color=color.green, textcolor=color.white, size=size.tiny)
plotshape(sellSignal, title='Sell Entry', text='Sell', style=shape.labeldown, location=location.abovebar, color=color.red, textcolor=color.white, size=size.tiny)
plotshape(addBuySignal, title='Add Buy', text='Add', style=shape.triangleup, location=location.belowbar, color=color.blue, textcolor=color.blue, size=size.tiny)
plotshape(addSellSignal, title='Add Sell', text='Add', style=shape.triangledown, location=location.abovebar, color=color.fuchsia, textcolor=color.fuchsia, size=size.tiny)
plotshape(reversalCandleExit, title='Forced Exit', text='Exit', style=shape.labeldown, location=location.abovebar, color=color.gray, textcolor=color.white, size=size.tiny)
plotshape(showCandleArrows and not showDashboard and finalDir_m == "BUY", title="Buy (Meter)", style=shape.triangleup, color=color.new(color.lime, 0), location=location.belowbar, size=size.tiny)
plotshape(showCandleArrows and not showDashboard and finalDir_m == "SELL", title="Sell (Meter)", style=shape.triangledown, color=color.new(color.red, 0), location=location.abovebar, size=size.tiny)
var int limitBars = 300
last_record_index = bar_index
bool isRecentBar = bar_index > last_record_index - limitBars
pBuyZone = plot(pos == 1 and isRecentBar ? xATRTrailingStopAdj : na, color=color.new(color.white, 100))
pSellZone = plot(pos == -1 and isRecentBar ? xATRTrailingStopAdj : na, color=color.new(color.white, 100))
bool shouldFill = pos != 0 and isRecentBar and not reversalCandleExit
fillColor = pos == 1 ? color.new(color.green, 85) : pos == -1 ? color.new(color.red, 85) : na
fill(pBuyZone, pSellZone, color = shouldFill ? fillColor : na)
var line snr_res_line = na
var line snr_sup_line = na
if not na(pivotHigh)
line.delete(snr_res_line)
snr_res_line := line.new(bar_index, pivotHigh, bar_index + 1, pivotHigh, xloc.bar_index, extend.right, color.red, line.style_solid, 2)
if not na(pivotLow)
line.delete(snr_sup_line)
snr_sup_line := line.new(bar_index, pivotLow, bar_index + 1, pivotLow, xloc.bar_index, extend.right, color.green, line.style_solid, 2)
plot(useBBTamak ? bbUpper : na, title="BB Upper (Target)", color=color.new(color.aqua, 70), style=plot.style_circles, linewidth=1)
plot(useBBTamak ? bbLower : na, title="BB Lower (Target)", color=color.new(color.aqua, 70), style=plot.style_circles, linewidth=1)
float emaAggressiveFast = ta.ema(src, emaAggressiveFastLen)
float emaAggressiveSlow = ta.ema(src, emaAggressiveSlowLen)
plot(showAggressiveEMA ? emaAggressiveFast : na, title="EMA Agresif Cepat", color=color.new(#1ff118, 44), style=plot.style_cross, linewidth=1)
plot(showAggressiveEMA ? emaAggressiveSlow : na, title="EMA Agresif Lambat", color=color.new(#f8241d, 46), style=plot.style_cross, linewidth=1)
// ==============================================
// --- DASHBOARD PRO & STATUS (REALITY ADVISOR COMPACT) ---
// ==============================================
string statusText = ''
color statusColor = color.gray
float distFromStop = pos == 1 ? src - xATRTrailingStopAdj : pos == -1 ? xATRTrailingStopAdj - src : 0
bool waspada = pos != 0 and not buySignal and not sellSignal and distFromStop < waspadaFactor * entryNloss
int rand = bar_index % 5
var string advisorMsg = "..."
if buySignal
statusText := '🚀 NAIK! Entry Baru'
statusColor := color.green
if rand == 0
advisorMsg := "Gaspol! 🚀 Jangan keasyikan tambah SL+ sayang."
else if rand == 1
advisorMsg := "OTW Sultan! 🤑 Full senyum maszeh!"
else if rand == 2
advisorMsg := "Ijo royo-royo! 🌿 Mata jadi seger."
else if rand == 3
advisorMsg := "Sikat Pak Haji! 👳 Rejeki anak soleh."
else
advisorMsg := "Lilin hijau! Serok sekarang! 💰"
else if sellSignal
statusText := '📉 TURUN! Entry Baru'
statusColor := color.red
if rand == 0
advisorMsg := "Longsor! 📉 Siapkan ember."
else if rand == 1
advisorMsg := "Merah merona! 🩸 Dompet aman kan?"
else if rand == 2
advisorMsg := "Terjun bebas! 🪂 waspada REM."
else if rand == 3
advisorMsg := "Longsor! 📉 jangan naik dulu."
else
advisorMsg := "Short selling! Cuan tipis sikat! 💸"
else if addBuySignal
statusText := '🚀 GAS LAGI (Add)!'
statusColor := color.blue
if rand == 0
advisorMsg := "Tambah muatan! 😎 Biar bandar nangis."
else
advisorMsg := "Mumpung hijau! 🛒 Sikat lagi bosqu!"
else if addSellSignal
statusText := '📉 GAS LAGI (Add)!'
statusColor := color.fuchsia
if rand == 0
advisorMsg := "Tambah Sell! 🔥 Biar makin perih."
else
advisorMsg := "Tekan bawah! 😤 Jangan kasih napas."
else if reversalCandleExit
statusText := '⛔ EXIT! Pembalikan'
statusColor := color.orange
advisorMsg := "Kabur! 🏃💨 Candle mencurigakan."
else if reversalRiskDetected
statusText := '⚠️ TP NOW!'
statusColor := color.yellow
advisorMsg := "Amankan profit! 🤡 Jangan serakah."
else if profitMaxReached
statusText := '🤑 CUAN BUNGKUS!'
statusColor := color.aqua
if rand == 0
advisorMsg := "Cuan bungkus! 🍜 Traktir seblak dong."
else if rand == 1
advisorMsg := "Udah kaya? 💅 Tarik buat skincare!"
else
advisorMsg := "Alhamdulillah! 🎁 Rejeki jangan ditolak."
else if waspada
statusText := '💔 HATI-HATI!'
statusColor := color.orange
if rand == 0
advisorMsg := "Dia toxic... 🚩 Hati-hati SL."
else
advisorMsg := "Awas MC! 💀 pasang SL+ sayang."
else if pos == 1
statusText := '🧘 TAHAN Buy...'
statusColor := color.green
if rand == 0
advisorMsg := "Sabar sayang... 🧘♀️ Disayang Tuhan."
else if rand == 1
advisorMsg := "Biarkan lari! 🏃♂️ Profit is running."
else
advisorMsg := "Hold terus! 🚀 Sampai ke bulan!"
else if pos == -1
statusText := '🍿 TAHAN Sell...'
statusColor := color.red
if rand == 0
advisorMsg := "Nonton aja... 🍿 Sambil ngemil."
else
advisorMsg := "Jatuh kebawah sakit? 😂 disini malah Cuan."
else if blockReason != ''
statusText := "DIBLOKIR"
statusColor := color.gray
advisorMsg := "Sinyal busuk! ⛔ Jangan masuk."
else
statusText := '... '
statusColor := color.gray
if rand == 0
advisorMsg := "Market galau... 💤 Mending turu."
else if rand == 1
advisorMsg := "Datar banget... 😑 Kek jalan tol."
else if rand == 2
advisorMsg := "Jangan maksa! ☕ Ngopi dulu."
else
advisorMsg := "Sabar... 🕰️ Menunggu itu berat."
if adxValue > adxMinLevel and diPlus > diMinus
marketModeText := "📈 Tren Naik Kuat"
marketModeColor := color.new(color.green, 0)
else if adxValue > adxMinLevel and diMinus > diPlus
marketModeText := "📉 Tren Turun Kuat"
marketModeColor := color.new(color.red, 0)
else
marketModeText := "💤 Sideways / Chop"
marketModeColor := color.new(color.gray, 0)
f_fillCell(tbl, col, row, cellText, color) =>
table.cell(tbl, col, row, cellText, text_color=color, text_size=size.small)
f_drawDashboard() =>
f_fillCell(dashboardPanel, 0, 0, "Gaya:", color.gray)
f_fillCell(dashboardPanel, 1, 0, tradingStyle, color.white)
f_fillCell(dashboardPanel, 0, 1, "Status:", color.gray)
f_fillCell(dashboardPanel, 1, 1, statusText, statusColor)
bool dashboardContextIsBuy = pos == 1 or (pos == 0 and close > open)
string emaStatus = (dashboardContextIsBuy ? emaOkForBuy : emaOkForSell) or not _useEmaFilter ? "✅" : "❌"
string rsiStatus = (dashboardContextIsBuy ? rsiOkForBuy : rsiOkForSell) or not _useRsiFilter ? "✅" : "❌"
string adxStatus = (dashboardContextIsBuy ? adxOkForBuy : adxOkForSell) or not _useAdxFilter ? "✅" : "❌"
string snrStatus = (dashboardContextIsBuy ? snrOkForBuy : snrOkForSell) or not _useSnrFilter ? "✅" : "❌"
string confirmStatus = (dashboardContextIsBuy ? confirmOkForBuy : confirmOkForSell) or not useConfirmFilter ? "✅" : "❌"
string filterStr1 = "EMA" + emaStatus + " RSI" + rsiStatus
string filterStr2 = "ADX" + adxStatus + " SNR" + snrStatus + (useConfirmFilter ? " 1-Bar" + confirmStatus : "")
string filterString = filterStr1 + " " + filterStr2
f_fillCell(dashboardPanel, 0, 2, "Filter:", color.gray)
f_fillCell(dashboardPanel, 1, 2, filterString, color.white)
float body_m = math.abs(close - open)
float rangeC_m = high - low
float power_m = rangeC_m == 0 ? 0.0 : (body_m / rangeC_m) * 5
power_m := math.min(power_m, 5)
float confidence_m = rangeC_m == 0 ? 0.0 : math.round(math.abs((close - open) / (high - low)) * 100)
int powerInt_m = int(math.round(power_m))
powerInt_m := powerInt_m < 0 ? 0 : powerInt_m > 5 ? 5 : powerInt_m
string bars_m = str.repeat("█", powerInt_m) + str.repeat("░", 5 - powerInt_m)
string meterString = (close > open ? "🟢 " : "🔴 ") + bars_m + " " + str.tostring(confidence_m, "#") + "%"
f_fillCell(dashboardPanel, 0, 3, "Meter:", color.gray)
f_fillCell(dashboardPanel, 1, 3, meterString, (close > open ? color.green : color.red))
int totalTrades = tradeCount_wins + tradeCount_losses
f_fillCell(dashboardPanel, 0, 4, "Total Sinyal:", color.gray)
f_fillCell(dashboardPanel, 1, 4, str.tostring(totalTrades), color.white)
f_fillCell(dashboardPanel, 0, 5, "W / L:", color.gray)
f_fillCell(dashboardPanel, 1, 5, str.tostring(tradeCount_wins) + " / " + str.tostring(tradeCount_losses), color.white)
string winRateString = "N/A"
color winRateColor = color.gray
if totalTrades > 0
winRateString := str.tostring(tradeCount_wins / totalTrades * 100, '0.0') + "%"
winRateColor := tradeCount_wins > tradeCount_losses ? color.green : (tradeCount_losses > tradeCount_wins ? color.red : color.gray)
f_fillCell(dashboardPanel, 0, 6, "Win Rate:", color.gray)
f_fillCell(dashboardPanel, 1, 6, winRateString, winRateColor)
f_fillCell(dashboardPanel, 0, 7, "Pasar:", color.gray)
f_fillCell(dashboardPanel, 1, 7, marketModeText, marketModeColor)
table.merge_cells(dashboardPanel, 0, 8, 1, 8)
table.cell(dashboardPanel, 0, 8, advisorMsg, text_color=color.yellow, text_size=size.small, bgcolor=color.new(color.black, 50))
table.merge_cells(dashboardPanel, 0, 9, 1, 9)
table.cell(dashboardPanel, 0, 9, "HADYAN PREMIUM INDI 083174747475", text_color=color.new(#969087, 66), text_size=size.tiny)
if barstate.islast and showDashboard
f_drawDashboard()
else if barstate.islast
table.clear(dashboardPanel, 0, 0, 1, 9)
// ==============================================
// --- FLOATING BUBBLE LABEL (FIXED) ---
// ==============================================
var label advisorLabel = na
if barstate.islast
label.delete(advisorLabel)
if showAdvisorBubble
// Tentukan Warna Gelembung biar Cantik
color bubbleColor = color.new(color.gray, 20)
if buySignal or addBuySignal or pos == 1
bubbleColor := color.new(color.green, 20)
else if sellSignal or addSellSignal or pos == -1
bubbleColor := color.new(color.red, 20)
else if waspada or reversalCandleExit
bubbleColor := color.new(color.orange, 20)
// OPTIMIZED: Geser sedikit ke kanan (+2) agar tidak menutupi candle terakhir
advisorLabel := label.new(bar_index + 2, close, text=advisorMsg, color=bubbleColor, textcolor=color.white, style=label.style_label_left, yloc=yloc.price)
// ==============================================
// --- LOGIKA CANDLE METER PANEL ---
// ==============================================
if (showCandlePanel or showCandleArrows) and not showDashboard
float body_m = math.abs(close - open)
float rangeC_m = high - low
float power_m = rangeC_m == 0 ? 0.0 : (body_m / rangeC_m) * 5
power_m := math.min(power_m, 5)
float confidence_m = rangeC_m == 0 ? 0.0 : math.round(math.abs((close - open) / (high - low)) * 100)
string patternName_m = ""
string baseDir_m = close > open ? "BUY" : "SELL"
if isBullishEngulfing_m
patternName_m := "Bullish Engulfing"
baseDir_m := "BUY"
else if isBearishEngulfing_m
patternName_m := "Bearish Engulfing"
baseDir_m := "SELL"
else if isHammer_m
patternName_m := "Hammer"
baseDir_m := "BUY"
else if isInvertedHammer_m
patternName_m := "Inverted Hammer"
baseDir_m := "SELL"
else
patternName_m := "Normal Candle"
string trendConfirm_m = close > close and close > close ? "BUY" : close < close and close < close ? "SELL" : baseDir_m
finalDir_m := baseDir_m == trendConfirm_m ? baseDir_m : baseDir_m
if showCandlePanel
int powerInt_m = int(math.round(power_m))
powerInt_m := powerInt_m < 0 ? 0 : powerInt_m > 5 ? 5 : powerInt_m
string bars_m = str.repeat("█", powerInt_m) + str.repeat("░", 5 - powerInt_m)
string dirText_m = finalDir_m == "BUY" ? "🟢 BUY" : "🔴 SELL"
string confText_m = str.tostring(confidence_m, "#") + "% " + bars_m
table.cell(infoPanel_m, 0, 0, "Pattern", text_color=color.yellow)
table.cell(infoPanel_m, 1, 0, "Direction", text_color=color.yellow)
table.cell(infoPanel_m, 2, 0, "Confidence", text_color=color.yellow)
table.cell(infoPanel_m, 0, 1, patternName_m, text_color=color.white)
table.cell(infoPanel_m, 1, 1, dirText_m, text_color=color.white)
table.cell(infoPanel_m, 2, 1, confText_m, text_color=color.white)
else
table.clear(infoPanel_m, 0, 0, 2, 1)
else if not showDashboard
table.clear(infoPanel_m, 0, 0, 2, 1)
// ==============================================
// --- ALERT UPDATED (SINGLE ALERT SUPPORT) ---
// ==============================================
string alertMsg_all = ""
if buySignal
alertMsg_all := "🚀 BUY NEW! @ " + str.tostring(close) + " | SL: " + str.tostring(xATRTrailingStopAdj)
else if sellSignal
alertMsg_all := "📉 SELL NEW! @ " + str.tostring(close) + " | SL: " + str.tostring(xATRTrailingStopAdj)
else if addBuySignal
alertMsg_all := "➕ ADD BUY (Re-Entry) @ " + str.tostring(close)
else if addSellSignal
alertMsg_all := "➕ ADD SELL (Re-Entry) @ " + str.tostring(close)
else if reversalCandleExit
alertMsg_all := "⛔ EXIT NOW! Reversal Detected @ " + str.tostring(close)
else if profitMaxReached
alertMsg_all := "💰 TAKE PROFIT! Target Tercapai @ " + str.tostring(close)
else if reversalRiskDetected
alertMsg_all := "⚠️ WARNING REVERSAL! RSI Extreme @ " + str.tostring(close)
// Pemicu Alarm Utama (Hanya aktif jika ada pesan, cukup pasang 1 alarm "Any function call")
if alertMsg_all != ""
alert(alertMsg_all, alert.freq_once_per_bar_close)
// Backup: Manual Alerts (Jika user Premium mau pasang satu-satu)
alertcondition(buySignal, title=' Buy Signal', message='🚀 BUY NEW!')
alertcondition(sellSignal, title=' Sell Signal', message='📉 SELL NEW!')
alertcondition(addBuySignal, title=' Add Buy', message='🚀 ADD BUY')
alertcondition(addSellSignal, title=' Add Sell', message='📉 ADD SELL')
alertcondition(waspada, title=' Waspada', message='💔 WASPADA')
// ==============================================
// --- TP/SL MODE SWING (FIXED & OPTIMIZED) ---
// ==============================================
var line sl_line = na
var line tp1_line = na
var line tp2_line = na
var line tp3_line = na
var label sl_label = na
var label tp1_label = na
var label tp2_label = na
var label tp3_label = na
if tradingStyle == 'Swing Santai'
if buySignal
line.delete(sl_line)
line.delete(tp1_line)
line.delete(tp2_line)
line.delete(tp3_line)
label.delete(sl_label)
label.delete(tp1_label)
label.delete(tp2_label)
label.delete(tp3_label)
float sl = entryPrice - entryNloss
float tp1 = entryPrice + entryNloss
float tp2 = entryPrice + (2*entryNloss)
float tp3 = entryPrice + (3*entryNloss)
sl_line := line.new(bar_index, sl, bar_index + 10, sl, color=color.new(color.red, 20), style=line.style_dashed, width=2)
tp1_line := line.new(bar_index, tp1, bar_index + 10, tp1, color=color.new(color.green, 20), style=line.style_dashed, width=2)
tp2_line := line.new(bar_index, tp2, bar_index + 10, tp2, color=color.new(color.green, 20), style=line.style_dashed, width=2)
tp3_line := line.new(bar_index, tp3, bar_index + 10, tp3, color=color.new(color.green, 20), style=line.style_dashed, width=2)
sl_label := label.new(bar_index + 10, sl, "SL (Rugi)", color=color.red, style=label.style_label_left, textcolor=color.white)
tp1_label := label.new(bar_index + 10, tp1, "TP1 (1:1)", color=color.green, style=label.style_label_left, textcolor=color.white)
tp2_label := label.new(bar_index + 10, tp2, "TP2 (1:2)", color=color.green, style=label.style_label_left, textcolor=color.white)
tp3_label := label.new(bar_index + 10, tp3, "TP3 (1:3)", color=color.green, style=label.style_label_left, textcolor=color.white)
else if sellSignal
line.delete(sl_line)
line.delete(tp1_line)
line.delete(tp2_line)
line.delete(tp3_line)
label.delete(sl_label)
label.delete(tp1_label)
label.delete(tp2_label)
label.delete(tp3_label)
float sl = entryPrice + entryNloss
float tp1 = entryPrice - entryNloss
float tp2 = entryPrice - (2*entryNloss)
float tp3 = entryPrice - (3*entryNloss)
sl_line := line.new(bar_index, sl, bar_index + 10, sl, color=color.new(color.red, 20), style=line.style_dashed, width=2)
tp1_line := line.new(bar_index, tp1, bar_index + 10, tp1, color=color.new(color.green, 20), style=line.style_dashed, width=2)
tp2_line := line.new(bar_index, tp2, bar_index + 10, tp2, color=color.new(color.green, 20), style=line.style_dashed, width=2)
tp3_line := line.new(bar_index, tp3, bar_index + 10, tp3, color=color.new(color.green, 20), style=line.style_dashed, width=2)
sl_label := label.new(bar_index + 10, sl, "SL (Rugi)", color=color.red, style=label.style_label_left, textcolor=color.white)
tp1_label := label.new(bar_index + 10, tp1, "TP1 (1:1)", color=color.green, style=label.style_label_left, textcolor=color.white)
tp2_label := label.new(bar_index + 10, tp2, "TP2 (1:2)", color=color.green, style=label.style_label_left, textcolor=color.white)
tp3_label := label.new(bar_index + 10, tp3, "TP3 (1:3)", color=color.green, style=label.style_label_left, textcolor=color.white)
else if pos != 0 and not na(sl_line)
// Update existing lines (Lightweight)
line.set_x2(sl_line, bar_index + 10)
line.set_x2(tp1_line, bar_index + 10)
line.set_x2(tp2_line, bar_index + 10)
line.set_x2(tp3_line, bar_index + 10)
label.set_x(sl_label, bar_index + 10)
label.set_x(tp1_label, bar_index + 10)
label.set_x(tp2_label, bar_index + 10)
label.set_x(tp3_label, bar_index + 10)
else if pos == 0
line.delete(sl_line)
sl_line := na
line.delete(tp1_line)
tp1_line := na
line.delete(tp2_line)
tp2_line := na
line.delete(tp3_line)
tp3_line := na
label.delete(sl_label)
sl_label := na
label.delete(tp1_label)
tp1_label := na
label.delete(tp2_label)
tp2_label := na
label.delete(tp3_label)
tp3_label := na
else
line.delete(sl_line)
sl_line := na
line.delete(tp1_line)
tp1_line := na
line.delete(tp2_line)
tp2_line := na
line.delete(tp3_line)
tp3_line := na
label.delete(sl_label)
sl_label := na
label.delete(tp1_label)
tp1_label := na
label.delete(tp2_label)
tp2_label := na
label.delete(tp3_label)
tp3_label := na
// ==============================================
// --- UPGRADE BARU: PIVOT POINTS (FIXED: EXTEND RIGHT) ---
// ==============================================
// Dapatkan Daily High, Low, Close (FIX "D")
p_d_h = request.security(syminfo.tickerid, "D", high , lookahead=barmerge.lookahead_on)
p_d_l = request.security(syminfo.tickerid, "D", low , lookahead=barmerge.lookahead_on)
p_d_c = request.security(syminfo.tickerid, "D", close , lookahead=barmerge.lookahead_on)
// Perhitungan Pivot Klasik
pivot_d = (p_d_h + p_d_l + p_d_c) / 3
r1_d = 2 * pivot_d - p_d_l
s1_d = 2 * pivot_d - p_d_h
r2_d = pivot_d + (p_d_h - p_d_l)
s2_d = pivot_d - (p_d_h - p_d_l)
// Visualisasi Pivot
var line p_line = na
var line r1_line = na
var line s1_line = na
var line r2_line = na
var line s2_line = na
var label p_label = na
var label r1_label = na
var label s1_label = na
var label r2_label = na
var label s2_label = na
// Fungsi untuk menghapus label/line
f_delete_pivot_objects() =>
line.delete(p_line)
line.delete(r1_line)
line.delete(s1_line)
line.delete(r2_line)
line.delete(s2_line)
label.delete(p_label)
label.delete(r1_label)
label.delete(s1_label)
label.delete(r2_label)
label.delete(s2_label)
if showPivotPoints
// Hapus yang lama agar tidak numpuk (Redraw Logic)
f_delete_pivot_objects()
// Logic: EXTEND RIGHT (Memanjang)
// Kita gunakan extend.right agar garisnya tidak pernah putus ke kanan
// Pivot (P)
p_line := line.new(bar_index, pivot_d, bar_index + 1, pivot_d, xloc.bar_index, extend.right, pivotColor, line.style_solid, 2)
p_label := label.new(bar_index + 10, pivot_d, "P Daily: " + str.tostring(pivot_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(pivotColor, 20), textcolor=color.white, style=label.style_label_left, size=size.small)
// Resistance
r1_line := line.new(bar_index, r1_d, bar_index + 1, r1_d, xloc.bar_index, extend.right, color.new(color.red, 30), line.style_dashed, 1)
r1_label := label.new(bar_index + 10, r1_d, "R1: " + str.tostring(r1_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(color.red, 80), textcolor=color.red, style=label.style_label_left, size=size.small)
r2_line := line.new(bar_index, r2_d, bar_index + 1, r2_d, xloc.bar_index, extend.right, color.new(color.red, 30), line.style_dashed, 1)
r2_label := label.new(bar_index + 10, r2_d, "R2: " + str.tostring(r2_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(color.red, 80), textcolor=color.red, style=label.style_label_left, size=size.small)
// Support
s1_line := line.new(bar_index, s1_d, bar_index + 1, s1_d, xloc.bar_index, extend.right, color.new(color.green, 30), line.style_dashed, 1)
s1_label := label.new(bar_index + 10, s1_d, "S1: " + str.tostring(s1_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(color.green, 80), textcolor=color.green, style=label.style_label_left, size=size.small)
s2_line := line.new(bar_index, s2_d, bar_index + 1, s2_d, xloc.bar_index, extend.right, color.new(color.green, 30), line.style_dashed, 1)
s2_label := label.new(bar_index + 10, s2_d, "S2: " + str.tostring(s2_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(color.green, 80), textcolor=color.green, style=label.style_label_left, size=size.small)
else
f_delete_pivot_objects()
// ==============================================
// --- UPGRADE BARU: FIBONACCI RETRACEMENT (CLEAN NO STACK) ---
// ==============================================
var float fiboHigh = na
var float fiboLow = na
var int fiboStartBar = na
// Array untuk menyimpan objek Fibo
var line fiboLines = array.new(0)
var linefill fiboFills = array.new(0)
var label fiboLabels = array.new(0)
// Helper Function: Clean Up All Fibo Objects
f_cleanFibo() =>
if array.size(fiboLines) > 0
for i = 0 to array.size(fiboLines) - 1
line.delete(array.get(fiboLines, i))
array.clear(fiboLines)
if array.size(fiboFills) > 0
for i = 0 to array.size(fiboFills) - 1
linefill.delete(array.get(fiboFills, i))
array.clear(fiboFills)
if array.size(fiboLabels) > 0
for i = 0 to array.size(fiboLabels) - 1
label.delete(array.get(fiboLabels, i))
array.clear(fiboLabels)
// Calculate historical values globally
float lastHigh_scanned = ta.valuewhen(not na(pivotHigh), pivotHigh, 0)
float lastLow_scanned = ta.valuewhen(not na(pivotLow), pivotLow, 0)
// Reset Fibo jika ada sinyal entry baru
if buySignal or sellSignal
f_cleanFibo() // Clean old ones first!
// Gunakan nilai yang sudah di-scan secara global
if not na(lastHigh_scanned) and not na(lastLow_scanned)
fiboLow := lastLow_scanned
fiboHigh := lastHigh_scanned
fiboStartBar := bar_index
// Levels
fiboLevels = array.new(0)
array.push(fiboLevels, 0.0)
array.push(fiboLevels, 0.236)
array.push(fiboLevels, 0.382)
array.push(fiboLevels, 0.5)
array.push(fiboLevels, 0.618)
array.push(fiboLevels, 1.0)
// Gambar Fibo (Hanya digambar ulang jika posisi valid dan belum ada)
// Kita gunakan trik: Gambar setiap bar, tapi HAPUS yang lama dulu.
// Ini mencegah stacking ribuan kotak.
if showFiboLevels and not na(fiboHigh) and not na(fiboLow)
f_cleanFibo() // CLEANUP WAJIB SEBELUM GAMBAR BARU
float fiboRange = fiboHigh - fiboLow
int f_start = bar_index + fiboXOffset
int f_end = bar_index + fiboXOffset + 15
var line lastLineObj = na
for i = 0 to array.size(fiboLevels) - 1
float level = array.get(fiboLevels, i)
float fiboPrice = fiboHigh - (fiboRange * level)
string levelText = str.tostring(math.round(level * 100), "0.0") + "%"
color levelColor = color.rgb(19, 56, 189)
if level == 0.618
levelColor := color.new(#FFD700, 30)
else if level == 0.5
levelColor := color.new(color.green, 30)
else
levelColor := color.new(#7925c9, 70)
string l_style = (level == 0.0 or level == 1.0) ? line.style_dashed : line.style_solid
int l_width = (level == 0.618 or level == 0.5) ? 2 : 1
// Draw & Push Line
line currentLineObj = line.new(f_start, fiboPrice, f_end, fiboPrice, xloc.bar_index, extend.none, levelColor, l_style, l_width)
array.push(fiboLines, currentLineObj)
// Fill Logic
color c_fill = switch level
0.236 => color.new(color.gray, 70) // Sangat transparan (95)
0.382 => color.new(color.blue, 70)
0.5 => color.new(color.green, 70)
0.618 => color.new(#FFD700, 70)
1.0 => color.new(color.red, 70)
=> na
if i > 0
linefill lf = linefill.new(lastLineObj, currentLineObj, c_fill)
array.push(fiboFills, lf)
lastLineObj := currentLineObj
// Draw & Push Label
label lb = label.new(f_end, fiboPrice, levelText, xloc.bar_index, yloc.price, color=color.new(levelColor, 100), textcolor=levelColor, style=label.style_label_left, size=size.small)
array.push(fiboLabels, lb)
// ==============================================
// --- UPGRADE BARU: STOCHASTIC FLOATING MINI CHART (REALTIME ANCHOR RIGHT PATCH) ---
// ==============================================
// 1. Calculations
stochK = ta.sma(ta.stoch(close, high, low, 14), 3)
stochD = ta.sma(stochK, 3)
// 2. Data Storage (Arrays for History)
var float stochK_hist = array.new_float(0)
var float stochD_hist = array.new_float(0)
// Update Arrays (REALTIME LOGIC)
if barstate.isnew
array.push(stochK_hist, nz(stochK, 50))
array.push(stochD_hist, nz(stochD, 50))
// Limit array size to chart width + 1
if array.size(stochK_hist) > (stochWidth + 1)
array.shift(stochK_hist)
array.shift(stochD_hist)
else
// UPDATE TICK-BY-TICK (Agar tidak delay)
if array.size(stochK_hist) > 0
array.set(stochK_hist, array.size(stochK_hist) - 1, nz(stochK, 50))
array.set(stochD_hist, array.size(stochD_hist) - 1, nz(stochD, 50))
// 3. Drawing Logic
var box stochBgBox = na
var box stochUpperFill = na
var box stochLowerFill = na
var line stochLines = array.new_line(0)
// Clear Function
f_cleanStochChart() =>
if not na(stochBgBox)
box.delete(stochBgBox)
if not na(stochUpperFill)
box.delete(stochUpperFill)
if not na(stochLowerFill)
box.delete(stochLowerFill)
if array.size(stochLines) > 0
for i = 0 to array.size(stochLines) - 1
line.delete(array.get(stochLines, i))
array.clear(stochLines)
// Global Helper to map 0-100 Stoch value to Y price coordinate
f_mapY(_val, _bottom, _height) =>
_bottom + (_val / 100 * _height)
if showStochChart and array.size(stochK_hist) > 2
f_cleanStochChart() // Redraw every tick
// Positioning (ANCHOR RIGHT LOGIC)
int offset_right = 5
int ch_right = bar_index + offset_right // Ujung kanan box
int ch_left = ch_right - stochWidth
// Vertical Scaling
float ch_height = ta.atr(14) * 4
float ch_bottom = close - (ch_height * 1.5)
float ch_top = ch_bottom + ch_height
// Draw Background
stochBgBox := box.new(ch_left, ch_top, ch_right, ch_bottom, xloc=xloc.bar_index, border_width=1, border_color=color.new(color.white, 80), bgcolor=color.new(color.black, 100))
// Draw Overbought Fill (80-100)
stochUpperFill := box.new(ch_left, f_mapY(70, ch_bottom, ch_height), ch_right, f_mapY(80, ch_bottom, ch_height), xloc=xloc.bar_index, border_width=0, bgcolor=color.new(color.red, 100))
// Draw Oversold Fill (0-20)
stochLowerFill := box.new(ch_left, f_mapY(10, ch_bottom, ch_height), ch_right, f_mapY(0, ch_bottom, ch_height), xloc=xloc.bar_index, border_width=0, bgcolor=color.new(color.green, 100))
// Draw Reference Lines
line l80 = line.new(ch_left, f_mapY(80, ch_bottom, ch_height), ch_right, f_mapY(80, ch_bottom, ch_height), color=color.new(color.red, 20), style=line.style_dotted)
line l20 = line.new(ch_left, f_mapY(20, ch_bottom, ch_height), ch_right, f_mapY(20, ch_bottom, ch_height), color=color.new(color.green, 20), style=line.style_dotted)
array.push(stochLines, l80)
array.push(stochLines, l20)
// Draw K and D Lines (ANCHOR TO REALTIME BAR INDEX)
// PATCH: Iterate relative to current bar_index to ensure 0 gap
int sz = array.size(stochK_hist)
for i = 0 to sz - 2
// Logika Mundur: Titik terakhir (sz-1) harus ada di bar_index saat ini
int idx_current = sz - 1 - i
int idx_prev = sz - 2 - i
if idx_prev >= 0
// X Coordinates (Relative to Realtime Bar)
int x2 = bar_index - i
int x1 = bar_index - (i + 1)
// K Line
float yK1 = f_mapY(array.get(stochK_hist, idx_prev), ch_bottom, ch_height)
float yK2 = f_mapY(array.get(stochK_hist, idx_current), ch_bottom, ch_height)
if not na(yK1) and not na(yK2)
line lK = line.new(x1, yK1, x2, yK2, color=color.new(#05492f, 0), width=1)
array.push(stochLines, lK)
// D Line
float yD1 = f_mapY(array.get(stochD_hist, idx_prev), ch_bottom, ch_height)
float yD2 = f_mapY(array.get(stochD_hist, idx_current), ch_bottom, ch_height)
if not na(yD1) and not na(yD2)
line lD = line.new(x1, yD1, x2, yD2, color=color.new(#810404, 0), width=1)
array.push(stochLines, lD)
// ==============================================
// --- VISUALISASI UPGRADE: SMART SUPPLY/DEMAND ZONES ---
// ==============================================
ph_zone = ta.pivothigh(high, zoneLookback, zoneLookback)
pl_zone = ta.pivotlow(low, zoneLookback, zoneLookback)
// FIX: Pindahkan ATR ke luar IF agar konsisten
float atrForZone = ta.atr(14)
var box supplyBoxes = array.new_box()
var box demandBoxes = array.new_box()
// Batasi jumlah zona agar chart tetap bersih
maxZones = 5
// Deteksi Zona Supply (Merah)
if not na(ph_zone) and showSmartZones
// Buat box baru dari titik pivot sampai ke masa depan sedikit
b_sup = box.new(bar_index , high , bar_index + 20, high - (atrForZone*0.5), bgcolor=color.new(color.red, 85), border_color=color.new(color.red, 50))
array.push(supplyBoxes, b_sup)
if array.size(supplyBoxes) > maxZones
box.delete(array.shift(supplyBoxes))
// Deteksi Zona Demand (Hijau)
if not na(pl_zone) and showSmartZones
b_dem = box.new(bar_index , low , bar_index + 20, low + (atrForZone*0.5), bgcolor=color.new(color.lime, 85), border_color=color.new(color.lime, 50))
array.push(demandBoxes, b_dem)
if array.size(demandBoxes) > maxZones
box.delete(array.shift(demandBoxes))
// Perpanjang Zona Secara Realtime
if array.size(supplyBoxes) > 0 and showSmartZones
for i = 0 to array.size(supplyBoxes) - 1
b = array.get(supplyBoxes, i)
// Perpanjang ke bar saat ini + 5 agar terlihat "hidup"
box.set_right(b, bar_index + 5)
if array.size(demandBoxes) > 0 and showSmartZones
for i = 0 to array.size(demandBoxes) - 1
b = array.get(demandBoxes, i)
// Perpanjang ke bar saat ini + 5 agar terlihat "hidup"
box.set_right(b, bar_index + 5)
// ====================================================================================================
// BAGIAN 2: FITUR TAMBAHAN (HSN GHOST CANDLES) - DI-INJECT DI SINI
// ====================================================================================================
// --- TIPE DATA KHUSUS (HSN) ---
type CandleHSN
float o
float c
float h
float l
int o_idx
int c_idx
int h_idx
int l_idx
box body
line wick_up
line wick_down
type ImbalanceHSN
box b
int idx
type CandleSettingsHSN
bool show
string htf
int max_display
type SettingsHSN
int max_sets
color bull_body
color bull_border
color bull_wick
color bear_body
color bear_border
color bear_wick
int offset
int buffer
int htf_buffer
int width
bool trace_show
string trace_anchor
bool label_show
color label_color
string label_size
bool htf_label_show
color htf_label_color
string htf_label_size
bool htf_timer_show
color htf_timer_color
string htf_timer_size
type CandleSetHSN
CandleHSN candles
ImbalanceHSN imbalances
CandleSettingsHSN settings
label tfName
label tfTimer
type HelperHSN
string name = "Helper"
// --- SETUP PENGATURAN HSN ---
SettingsHSN settings = SettingsHSN.new()
var CandleSettingsHSN SettingsHTF1 = CandleSettingsHSN.new()
var CandleSettingsHSN SettingsHTF2 = CandleSettingsHSN.new()
var CandleHSN candles_1 = array.new(0)
var CandleHSN candles_2 = array.new(0)
var CandleSetHSN htf1 = CandleSetHSN.new()
htf1.settings := SettingsHTF1
htf1.candles := candles_1
var CandleSetHSN htf2 = CandleSetHSN.new()
htf2.settings := SettingsHTF2
htf2.candles := candles_2
// --- INPUT KHUSUS HSN CANDLES (15 & 30 MENIT) ---
grp_hsn = "🔥 HSN HTF Candles (Upgrade)"
htf1.settings.show := input.bool(true, "Show HTF 1 (15 Menit)", group=grp_hsn, inline="h1")
htf_1 = input.timeframe("15", "", group=grp_hsn, inline="h1")
htf1.settings.htf := htf_1
htf1.settings.max_display := 4
htf2.settings.show := input.bool(true, "Show HTF 2 (30 Menit)", group=grp_hsn, inline="h2")
htf_2 = input.timeframe("30", "", group=grp_hsn, inline="h2")
htf2.settings.htf := htf_2
htf2.settings.max_display := 4
settings.max_sets := 2
settings.bull_body := color.new(color.green, 60)
settings.bear_body := color.new(color.red, 60)
settings.bull_border := color.new(color.green, 10)
settings.bear_border := color.new(color.red, 10)
settings.bull_wick := color.new(color.green, 10)
settings.bear_wick := color.new(color.red, 10)
// FIXED: Increased default offset from 10 to 25 to avoid overlap with Advisor Bubble
settings.offset := input.int(25, "Padding/Jarak Candle", group=grp_hsn)
settings.buffer := 1
settings.htf_buffer := 5
settings.width := input.int(1, "Lebar Candle", minval = 1, maxval = 4, group=grp_hsn)*2
settings.htf_label_show := true
settings.htf_label_color := color.gray
settings.htf_label_size := size.normal
// --- HELPER FUNCTIONS ---
HelperHSN helper = HelperHSN.new()
color color_transparent = #ffffff00
method ValidTimeframe(HelperHSN helper, string HTF) =>
helper.name := HTF
if timeframe.in_seconds(HTF) >= timeframe.in_seconds("D") and timeframe.in_seconds(HTF) > timeframe.in_seconds()
true
else
n1 = timeframe.in_seconds()
n2 = timeframe.in_seconds(HTF)
n3 = n1 % n2
(n1 < n2 and math.round(n2/n1) == n2/n1)
method HTFName(HelperHSN helper, string HTF) =>
helper.name := "HTFName"
formatted = HTF
seconds = timeframe.in_seconds(HTF)
if seconds < 60
formatted := str.tostring(seconds) + "s"
else if (seconds / 60) < 60
formatted := str.tostring((seconds/60)) + "m"
else if (seconds/60/60) < 24
formatted := str.tostring((seconds/60/60)) + "H"
formatted
method HTFEnabled(HelperHSN helper) =>
helper.name := "HTFEnabled"
int enabled =0
enabled += htf1.settings.show ? 1 : 0
enabled += htf2.settings.show ? 1 : 0
int last = math.min(enabled, settings.max_sets)
last
method CandleSetHigh(HelperHSN helper, CandleHSN candles, float h) =>
helper.name := "CandlesSetHigh"
float _h = h
if array.size(candles) > 0
for i = 0 to array.size(candles)-1
// FIX: Diganti dari c menjadi cItem
CandleHSN cItem = array.get(candles, i)
if cItem.h > _h
_h := cItem.h
_h
method CandlesHigh(HelperHSN helper, CandleHSN candles) =>
helper.name := "CandlesHigh"
h = 0.0
int cnt = 0
int last = helper.HTFEnabled()
if htf1.settings.show and helper.ValidTimeframe(htf1.settings.htf)
h := helper.CandleSetHigh(htf1.candles, h)
cnt += 1
if htf2.settings.show and helper.ValidTimeframe(htf2.settings.htf) and cnt < last
h := helper.CandleSetHigh(htf2.candles, h)
cnt +=1
if array.size(candles) > 0
for i = 0 to array.size(candles)-1
// FIX: Diganti dari c menjadi cItem
CandleHSN cItem = array.get(candles, i)
if cItem.h > h
h := cItem.h
h
method Reorder(CandleSetHSN candleSet, int offset) =>
size = candleSet.candles.size()
if size > 0
for i = size-1 to 0
CandleHSN candle = candleSet.candles.get(i)
t_buffer = offset + ((settings.width+settings.buffer)*(size-i-1))
box.set_left(candle.body, bar_index + t_buffer)
box.set_right(candle.body, bar_index + settings.width + t_buffer)
line.set_x1(candle.wick_up, bar_index+((settings.width)/2) + t_buffer)
line.set_x2(candle.wick_up, bar_index+((settings.width)/2) + t_buffer)
line.set_x1(candle.wick_down, bar_index+((settings.width)/2) + t_buffer)
line.set_x2(candle.wick_down, bar_index+((settings.width)/2) + t_buffer)
top = helper.CandlesHigh(candleSet.candles)
left = bar_index + offset + ((settings.width+settings.buffer)*(size-1))/2
if settings.htf_label_show
var label l = candleSet.tfName
string lbl = helper.HTFName(candleSet.settings.htf)
if not na(l)
label.set_xy(l, left, top)
else
l := label.new(left, top, lbl, color=color_transparent, textcolor = settings.htf_label_color, style=label.style_label_down, size = settings.htf_label_size)
candleSet
method Monitor(CandleSetHSN candleSet) =>
HTFBarTime = time(candleSet.settings.htf)
isNewHTFCandle = ta.change(HTFBarTime)
if isNewHTFCandle
CandleHSN candle = CandleHSN.new()
candle.o := open
candle.c := close
candle.h := high
candle.l := low
candle.o_idx := bar_index
candle.c_idx := bar_index
candle.h_idx := bar_index
candle.l_idx := bar_index
bull = candle.c > candle.o
candle.body := box.new(bar_index, math.max(candle.o, candle.c), bar_index+2, math.min(candle.o, candle.c), bull ? settings.bull_border : settings.bear_border, 1, bgcolor = bull ? settings.bull_body : settings.bear_body)
candle.wick_up := line.new(bar_index+1, candle.h, bar_index, math.max(candle.o, candle.c), color=bull ? settings.bull_wick : settings.bear_wick)
candle.wick_down := line.new(bar_index+1, math.min(candle.o, candle.c), bar_index, candle.l, color=bull ? settings.bull_wick : settings.bear_wick)
candleSet.candles.unshift(candle)
if candleSet.candles.size() > candleSet.settings.max_display
CandleHSN delCandle = array.pop(candleSet.candles)
box.delete(delCandle.body)
line.delete(delCandle.wick_up)
line.delete(delCandle.wick_down)
candleSet
method Update(CandleSetHSN candleSet, int offset) =>
if candleSet.candles.size() > 0
CandleHSN candle = candleSet.candles.first()
candle.h_idx := high > candle.h ? bar_index : candle.h_idx
candle.h := high > candle.h ? high : candle.h
candle.l_idx := low < candle.l ? bar_index : candle.l_idx
candle.l := low < candle.l ? low : candle.l
candle.c := close
candle.c_idx := bar_index
bull = candle.c > candle.o
box.set_top(candle.body, bull ? candle.c : candle.o)
box.set_bottom(candle.body, bull ? candle.o : candle.c)
box.set_bgcolor(candle.body, bull ? settings.bull_body : settings.bear_body)
box.set_border_color(candle.body, bull ? settings.bull_border : settings.bear_border)
line.set_color(candle.wick_up, bull ? settings.bull_wick : settings.bear_wick)
line.set_color(candle.wick_down, bull ? settings.bull_wick : settings.bear_wick)
line.set_y1(candle.wick_up, candle.h)
line.set_y2(candle.wick_up, math.max(candle.o, candle.c))
line.set_y1(candle.wick_down, candle.l)
line.set_y2(candle.wick_down, math.min(candle.o, candle.c))
if barstate.isrealtime or barstate.islast
candleSet.Reorder(offset)
candleSet
// --- EKSEKUSI HSN LOGIC ---
int cnt_hsn = 0
int last_hsn = helper.HTFEnabled()
int offset_hsn = settings.offset
if htf1.settings.show and helper.ValidTimeframe(htf1.settings.htf)
htf1.Monitor().Update(offset_hsn)
cnt_hsn +=1
offset_hsn += cnt_hsn > 0 ? (htf1.candles.size() * settings.width) + (htf1.candles.size() > 0 ? htf1.candles.size()-1 * settings.buffer : 0) + settings.htf_buffer : 0
if htf2.settings.show and helper.ValidTimeframe(htf2.settings.htf) and cnt_hsn < last_hsn
htf2.Monitor().Update(offset_hsn)
cnt_hsn+=1
offset_hsn += cnt_hsn > 0 ? (htf2.candles.size() * settings.width) + (htf2.candles.size() > 0 ? htf2.candles.size()-1 * settings.buffer : 0) + settings.htf_buffer : 0
Weighted CCI Oscillator [SeerQuant]Weighted CCI Oscillator (WCCI)
The Weighted CCI Oscillator (WCCI) is an enhanced CCI-style deviation oscillator that builds on the classic Commodity Channel Index framework by introducing adaptive weighting and configurable smoothing. By dynamically scaling deviation based on a selected market “weight” (Volume, Momentum, Volatility, or Reversion Factor), WCCI helps trend strength and regime shifts stand out more clearly, while still retaining the familiar CCI-style structure and ±200 extreme zones.
⚙️ How It Works
WCCI starts by calculating a baseline (your chosen moving average type) of the selected CCI source (Typical Price / HLC3, or a custom input source). It then measures how far price deviates from that baseline, and applies an adaptive weight to that deviation based on your selected weighting method.
The weighting is normalized for stability so it remains usable across different assets and changing regimes, then clamped to prevent abnormal spikes from distorting the oscillator. The weighted deviation is normalized by a weighted mean absolute deviation term (using the standard CCI constant k), producing a CCI-like oscillator that responds differently depending on the “state” of the market.
Trend logic is defined using a neutral zone around the 0 midline: bullish when WCCI holds above (0 + Neutral Zone), bearish when it holds below (0 - Neutral Zone), and neutral while it remains inside that band. A smoothed WCCI line is also provided for cleaner confirmation.
✨ Customizable Settings
WCCI is designed to be tuned without overcomplication. You can choose the CCI source mode (Typical Price / HLC3 or Input Source), set the calculation length, and apply smoothing using your preferred moving average type (SMA, EMA, RMA, HMA, DEMA, TEMA, etc.).
The weighting method is the key differentiator:
Volume weighting emphasizes participation and activity.
Momentum weighting emphasizes impulse and directional pressure.
Volatility weighting emphasizes expansion/contraction phases.
Reversion Factor weighting responds inversely to variance, biasing toward mean-reversion conditions.
On the style side, you can select a preset colour scheme (Default/Modern/Cool/Monochrome) or enable custom bull/bear/neutral colours. Candle coloring is optional, and you can choose whether candles follow the raw WCCI or the smoothed WCCI.
🚀 Features and Benefits
WCCI provides a CCI-style oscillator that adapts to market conditions instead of treating every regime the same. The weighting engine helps meaningful moves stand out when conditions justify it, while the neutral-zone framework reduces noise and improves readability compared to relying purely on midline flips. With flexible smoothing, clean state transitions, optional candle coloring, and clear ±200 extreme markers, WCCI works well as a trend filter, confirmation layer, or regime signal alongside other systems.
📜 Disclaimer
This indicator is for educational purposes only and does not constitute financial advice. Past performance does not guarantee future results. Always consult a licensed financial advisor before making trading decisions. Use at your own risk.
Volatility Momentum Suite | Lyro RSVolatility Momentum Suite is an advanced momentum and volatility-based oscillator designed to deliver a complete view of trend strength, acceleration, and market extremes in a single pane. By combining rate-of-change smoothing, adaptive moving averages, standard deviation bands, and momentum acceleration, the indicator provides clear structural insight into trend continuation, exhaustion, and potential reversals.
Built with multiple display and signal modes, it adapts seamlessly to both trend-following and mean-reversion workflows while maintaining strong visual clarity.
Key Features
Momentum Core (Smoothed RoC)
The foundation of the indicator is a Rate of Change (RoC) calculation applied to a selectable price source. This RoC is smoothed using one of 14+ moving average types, including EMA, HMA, KAMA, FRAMA, JMA, and more, allowing precise control over responsiveness versus smoothness.
Standard Deviation Bands
Dynamic deviation bands are calculated around the smoothed momentum line using rolling standard deviation. Two band layers are plotted:
Inner bands for early expansion signals
Outer bands for extreme conditions
These bands adapt automatically to volatility, highlighting momentum expansions, compressions, and exhaustion zones.
Momentum Acceleration
A dedicated acceleration line measures the momentum of momentum itself. This helps identify:
Early trend ignition
Momentum deceleration before reversals
Continuation strength during expansions
Acceleration smoothing and MA type are fully configurable.
Multi-Mode Signal System
Trend Mode
Colors momentum and price according to position above or below the zero line, emphasizing directional bias and trend continuation.
Heikin Ashi Candles Mode
Applies Heikin Ashi logic directly to the momentum series, filtering noise and revealing smoother trend transitions through candle structure.
Extremes Mode
Detects statistically extreme momentum conditions beyond outer deviation bands. Signals are only confirmed after a Heikin Ashi momentum flip, reducing premature reversal entries.
Histogram Mode
Displays the difference between momentum and its signal line as a histogram, useful for divergence spotting and momentum shifts.
Histogram & Signal Line
An EMA signal line is applied to the smoothed momentum, producing a histogram that visually tracks momentum expansion, contraction, and directional changes with adaptive coloring.
Visual Customization
Choose from multiple predefined color palettes:
Classic
Mystic
Accented
Royal
Or define your own bullish and bearish colors.
Additional visual features include:
Momentum-colored candles
Heikin Ashi momentum candles
Band shading and fills
Optional zero-line reference
Integrated Status Table
A built-in table summarizes the real-time state of:
Trend bias
Heikin Ashi momentum direction
Extreme overbought / oversold conditions
This allows rapid decision-making without needing to interpret every visual element manually.
How It Works
Momentum Calculation
Computes Rate of Change on the selected source and smooths it using the chosen moving average.
Volatility Structure
Builds adaptive deviation bands from rolling standard deviation of the momentum line.
Acceleration Layer
Measures the rate of momentum change to detect early shifts in strength.
Mode-Dependent Logic
Trend mode focuses on directional bias
HA mode smooths momentum structure
Extremes mode filters reversals using volatility and HA confirmation
Histogram mode emphasizes momentum differentials
Signals & Alerts
Automatic alerts trigger on:
Momentum crossing above or below zero
Heikin Ashi momentum flips
Confirmed overbought and oversold extremes
Practical Use
Trend Confirmation: Sustained momentum above zero with expanding bands supports trend continuation.
Reversal Identification: Momentum pushing beyond outer bands followed by HA confirmation often precedes reversals.
Momentum Quality: Acceleration helps distinguish strong breakouts from weakening moves.
Multi-Timeframe Alignment: Use higher timeframes for bias and lower timeframes for precision entries using the same indicator.
Customization
Adjust RoC length and smoothing for sensitivity
Tune band length and multipliers for volatility conditions
Select display and signal modes based on strategy type
Fully customize colors to match your chart environment
⚠️ Disclaimer
This indicator is a technical analysis tool and does not guarantee results. It should be used alongside other forms of analysis and proper risk management. The author assumes no responsibility for trading decisions made using this indicator.
ChannellerChanneller Pro - Multi-Pivot Regression Channels with Trend Validation
What This Indicator Does
Channeller Pro automatically detects and draws price channels by connecting multiple pivot points using linear regression rather than simply connecting two points. The indicator displays parallel support and resistance lines that define the current trend channel, along with an optional mid-line for mean reversion analysis.
Channels automatically appear when valid trend conditions are met and disappear when the trend structure breaks, keeping your chart clean and showing only actionable information.
---
How It Works (Methodology)
1. Multi-Pivot Linear Regression
Unlike simple channel indicators that connect only 2 pivot points, this indicator collects 3-5 pivot lows (for bullish channels) or pivot highs (for bearish channels) and calculates a least-squares linear regression line through them. This produces a statistically best-fit trendline that is more resistant to noise from a single errant pivot.
The regression calculation outputs:
- Slope: The angle/direction of the trend
- Intercept: The starting price level
- R² (coefficient of determination): A value from 0 to 1 measuring how well the pivot points align. Higher R² means the pivots form a cleaner, more reliable trendline. The default minimum is 0.70.
2. Higher-Low / Lower-High Pattern Validation
For a bullish channel to form, the indicator requires each successive pivot low to be higher than the previous pivot low (the definition of an uptrend). For bearish channels, each pivot high must be lower than the previous (downtrend structure). This filter prevents channels from forming during choppy, non-trending conditions.
3. ADX Trend Strength Filter
The indicator calculates the Average Directional Index (ADX) to measure trend strength. Channels only appear when ADX exceeds a user-defined threshold (default: 20). When ADX drops below this level, indicating the trend has weakened, channels automatically disappear. This prevents false channels during sideways/ranging markets.
4. Channel Width Calculation
Once the regression support line is established, the indicator finds the highest high (for bull channels) or lowest low (for bear channels) between the first and last pivot. A parallel line is drawn at this distance to form the opposite channel boundary.
5. Channel Respect Monitoring
The indicator tracks how price interacts with channel boundaries:
- Bounces: Price touches the boundary and reverses
- Pierces: Price closes beyond the boundary
If price pierces through a channel boundary multiple times, the channel is invalidated and removed, signaling the trend structure has broken.
---
How to Use This Indicator
Identifying Trends
- A green channel (bullish) indicates an uptrend with higher lows
- A red channel (bearish) indicates a downtrend with lower highs
- The R² value in the label shows channel quality (higher = more reliable)
Trading Applications
- Trend Following: Trade in the direction of the channel slope
- Support/Resistance: Use channel boundaries as potential reaction zones
- Mean Reversion: The optional mid-line (dashed) can serve as a target for pullback entries
- Breakout Preparation: When a channel disappears, it signals the prior trend structure has ended
Reading the Labels
- "BULL R²:0.85 (4 pivots)" means a bullish channel with 85% regression fit using 4 pivot points
- Orange-colored labels indicate weaker channels (R² between 0.70-0.85)
- Green/red labels indicate stronger channels (R² above 0.85)
---
Input Settings Explained
| Setting | Description |
|---------|-------------|
| Pivot Lookback Left/Right | Bars required on each side to confirm a pivot high/low |
| Min Pivots for Channel | Minimum pivot points required (more = stricter) |
| Max Pivots to Track | Maximum pivots stored (older pivots are dropped) |
| Min R² Score | Minimum regression quality (0.70 = 70% fit) |
| ADX Threshold | Minimum ADX value to show channels (20 = moderate trend) |
| Require HL/LH Pattern | Enforce higher-lows for bull, lower-highs for bear |
---
What Makes This Different
This indicator combines multiple validation layers that work together:
1. Regression vs. 2-point lines: More statistically robust trendlines
2. R² quality scoring: Quantifies how clean the trend structure is
3. Pattern validation: Ensures proper trend structure (HL/LH)
4. ADX filtering: Confirms trend exists before drawing channels
5. Auto-invalidation: Channels disappear when broken, not manually
These components create a self-cleaning channel system that only displays high-probability trend channels.
---
Alerts Available
- Bull/Bear Channel Formed
- Bull/Bear Channel Broken
- New Pivot High/Low Detected
RSI Sigmoid (Saturation)# 📊 RSI Sigmoid (Saturation) Indicator
---
## 🎯 What Does This Indicator Do?
This indicator transforms the traditional **RSI (Relative Strength Index)** using a **sigmoid function**, creating a mathematically "saturated" version that provides smoother, more controlled momentum signals.
---
## ✨ Key Features
### 🌊 **Saturation Effect**
Unlike standard RSI which oscillates wildly between 0-100, this version uses a **hyperbolic tangent function** to compress extreme values:
- 🔴 **Extreme readings** (very high/low) are dampened → pushed toward saturation zones (10 & 90)
- 🟡 **Middle range** (30-70) remains responsive and dynamic
- 🟢 **Sharp spikes** are smoothed while maintaining trend direction
### 👁️ **Dual Visualization**
- **🔵 Blue Line**: RSI Sigmoid (Saturated) - Your primary signal
- **🟠 Orange Circles**: Traditional RSI - For comparison
- **🟣 Purple Area**: Difference plot showing transformation intensity
### 🎯 **Smart Signals**
- **▲ Green Triangle**: Buy Signal when RSI Sigmoid crosses **above 50**
- **▼ Red Triangle**: Sell Signal when RSI Sigmoid crosses **below 50**
- **🎨 Background Colors**: Highlight oversold, overbought, and saturation zones
---
## ⚙️ How to Use
### 📐 **RSI Period** (Default: 50)
```
Higher Values (70-100) → Smoother, slower, fewer signals
Lower Values (14-30) → More responsive, more signals, noisier
```
### 🎚️ **Sigmoid Coefficient** (Default: 0.5)
```
Low (0.1-0.2) → Gentle saturation, closer to standard RSI
Medium (0.25) → Balanced transformation
High (0.3-0.5) → Aggressive saturation, strong dampening
```
### 📍 **Oversold/Overbought Levels**
Customize based on your:
- Trading timeframe (1m, 5m, 1h, 1D, etc.)
- Asset volatility
- Trading style (scalping, swing, position)
---
## 🔍 What to Watch For
| Signal | Meaning | Action |
|--------|---------|--------|
| 🟢 **Cross Above 50** | Bullish momentum shift | Consider long positions |
| 🔴 **Cross Below 50** | Bearish momentum shift | Consider short positions |
| ⚡ **Saturation < 10** | Extreme oversold | Potential reversal up |
| 🔥 **Saturation > 90** | Extreme overbought | Potential reversal down |
| 🟣 **Large Difference** | High transformation intensity | Strong momentum dampening |
---
## 💡 Trading Tips
✅ **DO:**
- Use multiple timeframes for confirmation
- Combine with support/resistance levels
- Apply proper risk management (stop-loss, position sizing)
- Backtest settings on your specific asset
- Watch for divergences between price and indicator
❌ **DON'T:**
- Rely solely on this indicator
- Ignore market context and fundamentals
- Over-leverage based on signals
- Use default settings without testing
- Trade without a clear strategy
---
## ⚠️ IMPORTANT DISCLAIMERS
### 🚨 **NOT Financial Advice**
This indicator is provided for **educational and informational purposes only**. It does not constitute financial, investment, or trading advice.
### 🛡️ **Risk Warning**
- ❌ **No guarantee of profits** - Past performance ≠ future results
- ❌ **Do not rely on this alone** - Always use multiple analysis methods
- ❌ **Markets are unpredictable** - No indicator can predict with certainty
- ❌ **You can lose money** - Never risk more than you can afford to lose
### 🎛️ **Customization Required**
All settings are **user-configurable** for a reason:
- Default values may NOT suit your strategy
- Different assets require different parameters
- Always backtest before live trading
- Adjust based on your timeframe and risk tolerance
### 📜 **Your Responsibility**
- ✓ You are responsible for your own trading decisions
- ✓ Always do your own research (DYOR)
- ✓ Understand the risks before trading
- ✓ Consider consulting a licensed financial advisor
---
## 📋 Quick Settings Guide
| Trading Style | RSI Period | Sigmoid K | Notes |
|---------------|------------|-----------|-------|
| **Scalping** | 14-21 | 0.3-0.4 | Fast signals, higher noise |
| **Day Trading** | 30-50 | 0.4-0.5 | Balanced responsiveness |
| **Swing Trading** | 50-70 | 0.5 | Smoother, fewer false signals |
| **Position Trading** | 70-100 | 0.5 | Very smooth, major trends only |
---
## 🏷️ License & Liability
**Use at your own risk.** The creator assumes **no liability** for any trading losses, damages, or consequences resulting from the use of this indicator.
---
### 🤝 Happy Trading & Stay Safe! 📈
*Remember: The best indicator is your own knowledge and discipline.*
Dynamic MTF Reversal Sequential [Realtime]SMA Reversal Sequential MTF Engine
Professional Pivot Identification & Squeeze Analysis
1. Overview
The SMA Reversal Sequential MTF Engine is a sophisticated environment recognition tool that monitors 8 timeframes (1m to Monthly) to identify objective Pivot Highs and Lows.
Unlike standard indicators that rely on simple price-crosses, this engine determines structural market turns based on the curvature (slope) of the SMA. By automating the detection of price consolidation (Squeeze) and synchronizing it with higher timeframe trends, it provides a systematic approach to capturing high-probability breakout opportunities.
2. Input Settings & Operations
Each parameter is designed to help you filter noise and focus on the market structure that suits your trading style.
■ Main Settings
Use Short Period:
ON: Uses (5, 3, 7) periods. Ideal for scalping. It identifies micro-pivots and sensitive trend shifts.
OFF: Uses (20, 6, 20) periods. Designed for Day/Swing trading. It filters out noise and focuses on major structural highs and lows.
Hide Lower Timeframes:
Automatically hides labels from timeframes shorter than your current chart (e.g., hiding 1m labels while on a 1H chart) to maintain a clean workspace.
Break Label Right Offset:
Adjusts the horizontal position of the "Breakout" price labels on the right side of the chart.
■ Drawing Options
Show Only Current TF Labels:
When enabled, it hides "15", "1H" labels from other timeframes on the chart. Note: The MTF Dashboard will still track all timeframes regardless of this setting.
Show Trendlines & Channels:
Plots lines connecting determined Pivot Highs and Lows, visualizing the current "Trading Range" or "Channel."
Show ZigZag Line:
Connects the confirmed Highs and Lows with straight lines, making "Market Structure" (Higher Highs / Lower Lows) instantly recognizable.
Hide Outer Channel on Squeeze:
During a Squeeze (consolidation), this hides older wide channels to highlight the immediate converging boundaries.
3. Core Logic: Determining Highs & Lows
This engine determines "Pivots" through a logical three-step process:
SMA Reversal Detection: The engine calculates when the SMA slope changes from down to up (or vice versa) using a sequential offset comparison.
Pivot Determination: Once an SMA turn is confirmed, the highest/lowest price point during that turn is determined as a structural Pivot High/Low.
Squeeze Identification: When the last two determined Highs are "Lower Highs" and the last two Lows are "Higher Lows," the engine identifies a Squeeze (Triangle Consolidation) and marks it with a Green Dot (●).
4. How to Trade (Step-by-Step)
Check the MTF Dashboard: Look at the top-right table. If the higher timeframes (4H, 1D) are Blue, the market is in a structural uptrend (making new Highs).
Wait for the Squeeze: Wait for the Green Dot (●) on your current timeframe. This signifies that energy is being stored within a tight range.
The Breakout Signal: When the price breaks the squeeze in the direction of the higher timeframe trend, a Rocket (🚀) or Lightning (⚡) icon appears. This is a high-probability entry point where a lower-timeframe consolidation resolves into a higher-timeframe trend.
5. Important Notes
As an SMA-based tool, it is a "Lagging Indicator" by nature. It focuses on structural confirmation rather than predicting unpredictable price spikes.
Always prioritize the MTF Dashboard colors. Trading against the higher timeframe trend is not recommended.
SMA Reversal Sequential MTF Engine
〜多時間軸SMA反転による高値安値確定と保合い分析〜
1. 概要 (Overview)
本スクリプトは、8つの時間軸(1分足〜月足)におけるSMA(単純移動平均線)の傾きを解析し、**「主観を排除した客観的な高値・安値」**を自動で決定するマルチタイムフレーム(MTF)環境認識エンジンです。
最大の特徴は、価格の上下に一喜一憂するのではなく、移動平均線という「相場の平均的な流れ」が反転したポイントを「真の節目(Pivot)」として定義する点にあります。これにより、ボラティリティの収束(スクイーズ)と、上位足に同期した高確率なブレイクアウトをシステマチックに捉えることができます。
2. インプット設定の完全解説 (Input Settings)
ユーザーが設定画面で調整できる各項目の具体的な意味と、変更による効果を解説します。
■ 基本設定 (Main Settings)
短期設定を使用 (Use Short Period):
ON: 期間 (5, 3, 7) を使用。スキャルピングや短期トレード向け。非常に細かく高値・安値を決定し、微細な反転も逃さず捉えます。
OFF: 期間 (20, 6, 20) を使用。デイトレード〜スイング向け。ノイズを排除し、主要な大きな波の高値・安値のみを決定します。
下位足を非表示 (Hide Lower Timeframes):
ON: 現在のチャートより短い足(例:1時間足を表示中に1分・5分足のサインなど)を隠します。上位足の構造把握に集中し、チャートをスッキリさせたい時に有効です。
ブレイク文字の右オフセット:
チャート右側の余白に表示される価格情報の位置を調整します。数値が大きいほど右側に移動します。
■ 表示設定 (Drawing Options)
現在足のラベルのみ表示 (Show Only Current TF Labels):
ON: チャート上の「15」「1H」といった他時間足のサインを非表示にします。
利点: 右上のダッシュボードには全情報が維持されるため、視認性を高めつつ、MTF分析の精度を維持できます。
トレンドライン&チャネル (Show Trendlines & Channels):
確定した高値同士・安値同士を線で結びます。現在の価格が「どの価格幅の範囲内(チャネル)」で推移しているかを可視化します。
ZigZagライン (Show ZigZag Line):
確定した高値と安値を交互に直線で結びます。ダウ理論的な「上昇・下落の波」の推移が一目で把握可能になります。
保合い中は外側ラインを非表示:
収束(スクイーズ)が発生した際、古い広いチャネルを隠し、今まさに機能している収束ラインのみを際立たせます。
3. 核心ロジック:高値・安値の決定プロセス
本ツールは以下の手順でチャート上の構造を構築します。
SMA反転の検知: SMAの傾きが「下落→上昇」または「上昇→下落」に転じた瞬間を計算。
節点の確定: その反転が起きた前後の最高値・最安値を**「確定した高値・安値」**として決定し、ラベルを打ちます。
スクイーズ判定: 決定された「直近2つの高値」が切り下がり、かつ「直近2つの安値」が切り上がった場合を**三角保合い(スクイーズ)**と定義し、緑のドット(●)を表示します。
4. 実戦的な操作フロー
このインジケーターを使ってどのようにトレードを組み立てるかの推奨ステップです。
環境認識 (Environment Check): 右上のダッシュボードで上位足(4H, 1D等)の色を確認。青なら「買いの高値更新中」、赤なら「売りの安値更新中」です。
保合い待機 (Squeeze Watching): 現在の足に**緑のドット(●)**が出るのを待ちます。これは決定された節目が収束し、次に大きく動くためのエネルギーを蓄積している合図です。
ブレイクの判断 (Decision): 保合いを抜けた際、ダッシュボードの上位足と同じ方向であれば、**🚀(ロケット)や⚡(稲妻)**のアイコンが出現します。これが「上位足の勢いに乗った、下位足の収束解消」という、最も期待値の高いエントリーポイントです。
5. 注意事項
本ツールは移動平均線に基づく「遅行指標」の性質を持ちます。そのため、急激なスパイク(一瞬の突発的な動き)には反応しない場合があります。
常に「上位足のトレンドがどちらを向いているか」をダッシュボードで確認し、逆張りでの使用は避けることを推奨します。
XAUUSD Pro Strategy //@version=5
indicator("XAUUSD RR Buy Sell Indicator", overlay=true, max_labels_count=500, max_boxes_count=100)
// ===== INPUT =====
rr = input.float(2.0, "Risk Reward", step=0.1)
sl_pips = input.int(300, "Stop Loss (points)")
show_boxes = input.bool(true, "Show Entry SL TP Box")
// ===== EMA =====
ema9 = ta.ema(close, 9)
ema50 = ta.ema(close, 50)
ema200 = ta.ema(close, 200)
plot(ema9, color=color.yellow)
plot(ema50, color=color.blue)
plot(ema200,color=color.red)
// ===== TREND =====
bull = ema50 > ema200
bear = ema50 < ema200
// ===== ENTRY CONDITIONS =====
buyCond = bull and close > ema9 and close < ema9
sellCond = bear and close < ema9 and close > ema9
// ===== PRICE CALC =====
buyEntry = close
buySL = buyEntry - sl_pips * syminfo.mintick
buyTP = buyEntry + (buyEntry - buySL) * rr
sellEntry = close
sellSL = sellEntry + sl_pips * syminfo.mintick
sellTP = sellEntry - (sellSL - sellEntry) * rr
// ===== DRAW =====
if buyCond
label.new(bar_index, low, "BUY", style=label.style_label_up, color=color.green, textcolor=color.white)
if show_boxes
box.new(bar_index, buyEntry, bar_index + 5, buySL, bgcolor=color.new(color.red,80))
box.new(bar_index, buyTP, bar_index + 5, buyEntry, bgcolor=color.new(color.green,80))
if sellCond
label.new(bar_index, high, "SELL", style=label.style_label_down, color=color.red, textcolor=color.white)
if show_boxes
box.new(bar_index, sellSL, bar_index + 5, sellEntry, bgcolor=color.new(color.red,80))
box.new(bar_index, sellEntry, bar_index + 5, sellTP, bgcolor=color.new(color.green,80))
Radar of Volatilidade ATR%ATR% to compare wich assets are displaying bigger intra-day ranges
- ATR 7 to follow quick scalps
- ATR 24 in the 1H represents 1 day cycle
SMC and FVGHLThis indicator shows FVG and fib level also shows previous day high low , weekly high low, and monthly high low.. apply this indicator on chart and make trading easy...
undan MTF Breakout - Modular V5# Kundan MTF Breakout V6 - Complete User Guide
## 📖 Table of Contents
1. (#overview)
2. (#installation)
3. (#core-strategy)
4. (#understanding-the-signals)
5. (#settings-explained)
6. (#how-to-trade)
7. (#best-practices)
8. (#troubleshooting)
---
## Overview
The **Kundan MTF Breakout V6** is a professional-grade indicator that detects high-probability reversal setups using:
- Multi-timeframe trend confirmation
- Volume tower detection
- Liquidity sweep enhancement
- Signal quality scoring
- Automatic SL/TP calculation
### What Makes This Indicator Unique?
| Feature | Benefit |
|---------|---------|
| Local Tower Volume | Detects volume spikes like your eyes do |
| Signal Scoring | Filters weak setups automatically |
| Liquidity Sweep | Identifies 90%+ probability trades |
| Session Filter | Avoid choppy market hours |
| Auto SL/TP | Know your risk before entering |
---
## Installation
### Step 1: Open TradingView
Go to (tradingview.com) and open any chart.
### Step 2: Open Pine Editor
Click on **Pine Editor** at the bottom of your screen.
### Step 3: Paste the Code
1. Delete any existing code in the editor
2. Copy the entire content of `kundan_mtf_breakout_v6_complete.pine`
3. Paste it into the editor
### Step 4: Save & Add to Chart
1. Click **Save** (Ctrl+S)
2. Name it: "Kundan MTF Breakout V6"
3. Click **Add to Chart**
### Step 5: Configure Settings
Click the ⚙️ gear icon next to the indicator name to open settings.
---
## Core Strategy
### The Pattern We're Trading
```
STEP 1: Big RED candle + HIGH volume (Tower)
↓
This is a "selling climax" - institutions dumping shares
STEP 2: Price creates a ZONE (yellow box on chart)
↓
High of red candle = Breakout level
Low of red candle = Stop loss area
STEP 3: Wait for GREEN candle to CLOSE ABOVE the zone
↓
This confirms buyers have taken control
STEP 4: BUY SIGNAL appears
↓
Enter long with SL below zone
```
### Why This Works
1. **Big red candle + high volume** = Weak hands selling in panic
2. **Price holds the low** = Strong hands absorbing the selling
3. **Breakout above** = Confirmation that selling is exhausted
4. **Low volume breakout** = No resistance left above
### Enhanced Signals (90%+ Probability)
When price **sweeps below the zone** before breaking out:
- This triggers stop losses of early buyers
- Institutions collect cheap shares
- The subsequent breakout is MORE powerful
- Indicator shows: 🔥 BUY 90%+
---
## Understanding the Signals
### Chart Elements
| Element | Color | Meaning |
|---------|-------|---------|
| 🔴 Red Box | Red border | Long setup zone (waiting for breakout) |
| 🟢 Green Box | Green border | Setup triggered (breakout occurred) |
| ⚫ Gray Box | Gray border | Setup expired (no breakout) |
| Green Dashed Line | Green | Breakout level to watch |
| 🔴 Red Solid Line | Red | Stop Loss level |
| 🟢 Green Solid Line | Green | Take Profit 1 |
| 🟩 Lime Solid Line | Lime | Take Profit 2 |
### Signal Labels
| Label | Meaning |
|-------|---------|
| `🔴 LONG #1 ` | Long setup detected, score 75% |
| `BUY` | Standard breakout signal |
| `🔥 BUY 90%+` | Enhanced signal with sweep |
| `SWEEP↓` | Liquidity sweep detected |
### Info Table (Top Right)
The table shows real-time status:
```
┌─────────────────────────────┐
│ 📊 MTF BREAKOUT V6 │ Both │
├─────────────────────────────┤
│ Daily: ⬆️ UP │
│ 4H: ⬆️ UP │
│ HTF Bias: 🟢 BULL │
├─────────────────────────────┤
│ ─── VOLUME ─── │
│ Method: Local Tower │
│ RVOL: 2.35x │
│ High Vol?: ✅ YES │
├─────────────────────────────┤
│ ─── SETUPS ─── │
│ 📈 Long: 2 active | 1 trig│
│ 📉 Short: 0 active | 0 trig│
├─────────────────────────────┤
│ Session: ✅ Active │
│ Scoring: Min 50% │
│ SL/TP: R:R 1.5/2.5 │
└─────────────────────────────┘
```
---
## Settings Explained
### 📊 Multi-Timeframe Settings
| Setting | Default | Description |
|---------|---------|-------------|
| Higher Timeframe 1 | Daily | Primary trend reference |
| Higher Timeframe 2 | 4H | Secondary trend reference |
| Lookback Periods | 5 | Bars to check for higher highs/lows |
| Trend Detection | Flexible | How strict trend must be |
**Tip:** Keep defaults for most markets. Use "Strict" for choppy markets.
### 🎯 Trade Direction
| Option | When to Use |
|--------|-------------|
| Both | Default - take longs and shorts |
| Long Only | Bullish market / uptrend |
| Short Only | Bearish market / downtrend |
### 📈 Volume Detection Settings
| Setting | Default | Description |
|---------|---------|-------------|
| Volume Method | Local Tower | **RECOMMENDED** - Best for detecting spikes |
| Volume Lookback | 20 | Bars to average for comparison |
**Volume Methods Explained:**
| Method | Best For |
|--------|----------|
| **Local Tower** | General use - detects spikes vs neighbors |
| SMA Multiple | Stable volume environments |
| Percentile Rank | Finding top X% volume bars |
| RVOL | Comparing to same time yesterday |
### 📊 Volume Method Parameters
| Setting | Default | Description |
|---------|---------|-------------|
| Tower: Neighbor Bars | 5 | Compare to last 5 bars |
| Tower: Must Be X Times | 2.0 | Volume must be 2x neighbors |
| Tower: Must Be Local Max | ON | Must be highest of neighbors |
**Tuning Tips:**
- More signals → Lower multiplier to 1.5
- Fewer signals → Raise multiplier to 2.5+
### 🕯️ Big Candle Detection
| Setting | Default | Description |
|---------|---------|-------------|
| Spread Multiplier | 1.5 | Candle must be 1.5x ATR |
| ATR Period | 14 | Average True Range period |
| Min Body % | 50 | Body must be 50% of candle |
| Require HTF Trend for Setup | OFF | If ON, only with-trend setups |
### 📉 Low Volume Settings (For Breakout)
| Setting | Default | Description |
|---------|---------|-------------|
| Low Volume Method | SMA Multiple | How to detect low volume |
| Low Volume Threshold | 1.0 | Below average (1.0 = below avg) |
| Require Low Vol Breakout | ON | Breakout needs low volume |
| Require Green Breakout | ON | Breakout candle must be green |
### 💧 Liquidity Sweep Settings
| Setting | Default | Description |
|---------|---------|-------------|
| Sweep Buffer % | 0.1 | How far below zone = sweep |
### 💰 Stop Loss / Take Profit
| Setting | Default | Description |
|---------|---------|-------------|
| Show SL/TP | ON | Display levels on chart |
| SL Buffer % | 0.1 | Extra room below setup low |
| TP1 R:R | 1.5 | First target (1.5x risk) |
| TP2 R:R | 2.5 | Second target (2.5x risk) |
**Example:**
- Entry: $100
- Setup Low: $98
- SL: $97.90 (with 0.1% buffer)
- Risk: $2.10
- TP1: $103.15 (1.5 × $2.10)
- TP2: $105.25 (2.5 × $2.10)
### 📊 Signal Quality Scoring
| Setting | Default | Description |
|---------|---------|-------------|
| Enable Scoring | ON | Calculate quality score |
| Min Score to Show | 50 | Hide signals below 50% |
| Show Score on Labels | ON | Display score on chart |
**Score Weights:**
| Factor | Points | What It Measures |
|--------|--------|------------------|
| Volume Strength | 30 | Tower height vs neighbors |
| Candle Size | 25 | Spread vs ATR |
| Trend Alignment | 25 | Agreement with HTF trend |
| Liquidity Sweep | 20 | Bonus if sweep occurred |
**Interpreting Scores:**
- **75-100%**: High quality - trade with confidence
- **50-74%**: Medium quality - trade with caution
- **Below 50%**: Low quality - consider skipping
### 🕐 Session Filter
| Setting | Default | Description |
|---------|---------|-------------|
| Enable Session Filter | OFF | Turn on to filter by time |
| Timezone | America/New_York | Your market timezone |
| London Session | 08:00-12:00 | London hours |
| NY Session | 13:00-17:00 | New York hours |
| Asia Session | 20:00-02:00 | Asia hours |
| Trade Monday-Friday | All ON | Day of week filter |
**When to Use:**
- Enable for Forex to trade during high-liquidity sessions
- Enable for stocks to avoid pre/post market
- Disable for crypto (24/7 market)
---
## How to Trade
### Step-by-Step Trading Process
#### 1. Wait for Setup
- Look for red box appearing on chart
- Check the score (aim for 50%+)
- Note the breakout level (green dashed line)
#### 2. Wait for Sweep (Optional but Better)
- If price dips below the red box → "SWEEP↓" appears
- This upgrades the setup to 90%+ probability
- Be patient for this!
#### 3. Wait for Breakout
- GREEN candle must CLOSE above the zone
- Volume should be LOW (indicator checks this)
- "BUY" or "🔥 BUY 90%+" signal appears
#### 4. Enter the Trade
- Entry: Just above the breakout level
- Stop Loss: Red line (below setup)
- TP1: Green line (take partial profits)
- TP2: Lime line (let remainder run)
#### 5. Manage the Trade
- At TP1: Close 50% of position
- Move SL to breakeven
- Let rest run to TP2
### Example Trade (Long)
```
Chart shows:
┌────────────────────────────────────┐
│ ║ │
│ Entry ──────────────── ║ ───────│ ← Green dashed line
│ ┌──────────────────────║──┐ │
│ │ RED ZONE ║ │ │ ← Yellow box
│ │ 🔴 LONG #1 ║ │ │
│ └──────────────────────║──┘ │
│ SWEEP↓ │ ← Liquidity sweep
│ ║ │
│ SL ─────────────────── ║ ───────│ ← Red line
└────────────────────────────────────┘
After breakout:
┌────────────────────────────────────┐
│ TP2 ─────────────────────────────│ ← Lime line
│ │
│ TP1 ─────────────────────────────│ ← Green line
│ │
│ 🔥 BUY 90%+ │
│ Entry ───────────────────────────│
│ ┌─────────────────────────┐ │
│ │ GREEN ZONE (triggered) │ │
│ └─────────────────────────┘ │
│ SL ──────────────────────────────│
└────────────────────────────────────┘
```
---
## Best Practices
### ✅ DO's
1. **Wait for the signal** - Don't anticipate, let it trigger
2. **Check the score** - Higher score = higher probability
3. **Use proper position sizing** - Risk 1-2% per trade max
4. **Trade with the trend** - HTF bias should match your trade
5. **Be patient for sweeps** - 90%+ signals are worth waiting for
6. **Honor your stop loss** - Never move it further away
### ❌ DON'Ts
1. **Don't chase** - If you missed the signal, wait for next one
2. **Don't overtrade** - Quality over quantity
3. **Don't ignore HTF trend** - Counter-trend setups are riskier
4. **Don't skip low-score setups then FOMO in** - Trust the system
5. **Don't trade during news** - Enable session filter if needed
### Recommended Settings by Market
#### Forex
```
- Session Filter: ON (London + NY)
- Volume Method: Local Tower
- Min Score: 50%
- Trade Direction: Based on HTF trend
```
#### Stocks
```
- Session Filter: ON (NY session only)
- Volume Method: Local Tower
- Min Score: 60%
- Trade Direction: Long Only (bull market) or Both
```
#### Crypto
```
- Session Filter: OFF (24/7 market)
- Volume Method: Local Tower
- Min Score: 50%
- Tower Multiplier: 2.5 (crypto is volatile)
```
#### Indices (ES, NQ, etc.)
```
- Session Filter: ON (NY session)
- Volume Method: Local Tower
- Min Score: 50%
- TP Ratios: 1.5 / 3.0 (indices trend well)
```
---
## Troubleshooting
### Problem: No Setups Appearing
**Check:**
1. Trade Direction matches market (not "Long Only" in downtrend)
2. Volume Method is "Local Tower"
3. Tower Multiplier not too high (try 1.5)
4. HTF Trend requirement is OFF
5. Session Filter is OFF or you're in active session
### Problem: Too Many Setups
**Fix:**
1. Raise Tower Multiplier to 2.5 or 3.0
2. Enable "Must Be Local Max"
3. Raise Min Score to 60% or 70%
4. Enable Session Filter
### Problem: Signals Triggering Late
**Check:**
1. Lower Sustain Bars to 1
2. Ensure "Require Low Vol Breakout" isn't too strict
3. Lower Low Volume Threshold to 1.2
### Problem: SL/TP Lines Not Showing
**Fix:**
1. Enable "Show SL/TP Levels"
2. Enable individual line toggles (SL, TP1, TP2)
3. Make sure you have a triggered signal (not just setup)
### Problem: Script Error
**Common Fixes:**
1. Make sure you copied the ENTIRE script
2. Check TradingView is on Pine Script v5
3. Clear browser cache and reload
4. Try a different browser
---
## Quick Reference Card
### Signal Meanings
| Signal | Action | Probability |
|--------|--------|-------------|
| 🔴 LONG # | Setup detected | Wait |
| BUY | Standard breakout | 70%+ |
| 🔥 BUY 90%+ | Sweep + breakout | 90%+ |
| SWEEP↓ | Stop hunt occurred | Prepare |
### Score Colors
| Color | Score | Quality |
|-------|-------|---------|
| Purple | 75%+ | Excellent |
| Red/Green | 50-74% | Good |
| Gray | <50% | Poor |
### Position Sizing Formula
```
Position Size = (Account × Risk%) / (Entry - SL)
Example:
- Account: $10,000
- Risk: 2% = $200
- Entry: $100
- SL: $98
- Position Size = $200 / $2 = 100 shares
```
---
## Support
If you have questions or issues:
1. Review this guide first
2. Check the Troubleshooting section
3. Test with default settings on a liquid market (ES, SPY, BTC)
**Happy Trading! 🚀**
---
*Version 6.0 | Last Updated: January 2026*






















