OPEN-SOURCE SCRIPT
Aggiornato

Market Structure Break with Volume & ATR

9 884
#### Indicator Overview:
The *Market Structure Break with Volume & ATR (MSB+VolATR)* indicator is designed to identify significant market structure breakouts and breakdowns using a combination of price action, volume analysis, and volatility (ATR). It is particularly useful for traders who rely on higher timeframes for swing trading or positional trading. The indicator highlights bullish and bearish breakouts, retests, fakeouts, and potential buy/sell signals based on RSI overbought/oversold conditions.

---

### Key Features:
1. *Market Structure Analysis*:
- Identifies swing highs and lows on a user-defined higher timeframe.
- Detects breakouts and breakdowns when price exceeds these levels with volume and ATR validation.

2. *Volume Validation*:
- Ensures breakouts are accompanied by above-average volume, reducing the likelihood of false signals.

3. *ATR Filter*:
- Filters out insignificant breakouts by requiring the breakout size to exceed a multiple of the ATR.

4. *RSI Integration*:
- Adds a momentum filter by considering overbought/oversold conditions using RSI.

5. *Visual Enhancements*:
- Draws colored boxes to highlight breakout zones.
- Labels breakouts, retests, and fakeouts for easy interpretation.
- Displays stop levels for potential trades.

6. *Alerts*:
- Provides alert conditions for buy and sell signals, enabling real-time notifications.

---

### Input Settings and Their Effects:

1. **Timeframe (tf):
- Determines the higher timeframe for market structure analysis.
- *Effect*: A higher timeframe (e.g., 1D) reduces noise and provides more reliable swing points, while a lower timeframe (e.g., 4H) may generate more frequent but less reliable signals.

2. **Lookback Period (length):
- Defines the number of historical bars used to identify significant highs and lows.
- *Effect*: A longer lookback period (e.g., 50) captures broader market structure, while a shorter period (e.g., 20) reacts faster to recent price action.

3. **ATR Length (atr_length):
- Sets the period for ATR calculation.
- *Effect*: A shorter ATR length (e.g., 14) reacts faster to recent volatility, while a longer length (e.g., 21) smooths out volatility spikes.

4. **ATR Multiplier (atr_multiplier):
- Filters insignificant breakouts by requiring the breakout size to exceed ATR × multiplier.
- *Effect*: A higher multiplier (e.g., 0.2) reduces false signals but may miss smaller breakouts.

5. **Volume Multiplier (volume_multiplier):
- Sets the volume threshold for breakout validation.
- *Effect*: A higher multiplier (e.g., 1.0) ensures stronger volume confirmation but may reduce the number of signals.

6. **RSI Length (rsi_length):
- Defines the period for RSI calculation.
- *Effect*: A shorter RSI length (e.g., 10) makes the indicator more sensitive to recent price changes, while a longer length (e.g., 20) smooths out RSI fluctuations.

7. *RSI Overbought/Oversold Levels*:
- Sets the thresholds for overbought (default: 70) and oversold (default: 30) conditions.
- *Effect*: Adjusting these levels can make the indicator more or less conservative in generating signals.

8. **Stop Loss Multiplier (SL_Multiplier):
- Determines the distance of the stop-loss level from the entry price based on ATR.
- *Effect*: A higher multiplier (e.g., 2.0) provides wider stops, reducing the risk of being stopped out prematurely but increasing potential losses.

---

### How It Works:
1. *Breakout Detection*:
- A bullish breakout occurs when the close exceeds the highest high of the lookback period, with volume above the threshold and breakout size exceeding ATR × multiplier.
- A bearish breakout occurs when the close falls below the lowest low of the lookback period, with similar volume and ATR validation.

2. *Retest Logic*:
- After a breakout, if price retests the breakout zone without closing beyond it, a retest label is displayed.

3. *Fakeout Detection*:
- If price briefly breaks out but reverses back into the range, a fakeout label is displayed.

4. *Buy/Sell Signals*:
- A sell signal is generated when price reverses below a bullish breakout zone and RSI is overbought.
- A buy signal is generated when price reverses above a bearish breakout zone and RSI is oversold.

5. *Stop Levels*:
- Stop-loss levels are plotted based on ATR × SL_Multiplier, providing a visual guide for risk management.

---

### Who Can Use It and How:
1. *Swing Traders*:
- Use the indicator on daily or 4-hour timeframes to identify high-probability breakout trades.
- Combine with other technical analysis tools (e.g., trendlines, Fibonacci levels) for confirmation.

2. *Positional Traders*:
- Apply the indicator on weekly or daily charts to capture long-term trends.
- Use the stop-loss levels to manage risk over extended periods.

3. *Algorithmic Traders*:
- Integrate the buy/sell signals into automated trading systems.
- Use the alert conditions to trigger trades programmatically.

4. *Risk-Averse Traders*:
- Adjust the ATR and volume multipliers to filter out low-probability trades.
- Use wider stop-loss levels to avoid premature exits.

---

### Where to Use It:
- *Forex*: Identify breakouts in major currency pairs.
- *Stocks*: Spot trend reversals in high-volume stocks.
- *Commodities*: Trade breakouts in gold, oil, or other commodities.
- *Crypto*: Apply to Bitcoin, Ethereum, or other cryptocurrencies for volatile breakout opportunities.

---

### Example Use Case:
- *Timeframe*: 1D
- *Lookback Period*: 50
- *ATR Length*: 14
- *ATR Multiplier*: 0.1
- *Volume Multiplier*: 0.5
- *RSI Length*: 14
- *RSI Overbought/Oversold*: 70/30
- *SL Multiplier*: 1.5

In this setup, the indicator will:
1. Identify significant swing highs and lows on the daily chart.
2. Validate breakouts with volume and ATR filters.
3. Generate buy/sell signals when price reverses and RSI confirms overbought/oversold conditions.
4. Plot stop-loss levels for risk management.

---

### Conclusion:
The *MSB+VolATR* indicator is a versatile tool for traders seeking to capitalize on market structure breakouts with added confirmation from volume and volatility. By customizing the input settings, traders can adapt the indicator to their preferred trading style and risk tolerance. Whether you're a swing trader, positional trader, or algorithmic trader, this indicator provides actionable insights to enhance your trading strategy.
Note di rilascio
Equilibrium Zone added.

// === Equilibrium Zone Description ===
// EQ Zone represents the transition zone between bullish and bearish structures.
// 1. Function: Shows the potential consolidation area of ​​the price
// 2. Features:
// - Can signal trend continuation or reversal
// - Can be used as a support/resistance level
// - Price rally zone in case of decreasing volatility
// 3. Usage Scenarios:
// - Bearish reaction from EQ upper limit = Potential short
// - Bullish reaction from EQ lower limit = Potential long
// - Volume increase within EQ = Forerunner of the upcoming breakout

// === EQ Zone Calculation Logic ===
// [Bull Box Upper Limit + Bear Box Upper Limit] / 2 = EQ Upper Limit
// [Bull Box Lower Limit + Bear Box Lower Limit] / 2 = EQ Lower Limit
// EQ Width = (Bull Box Height + Bear Box Height) / 2
Note di rilascio
### Key Improvements in Version 2:

1. *Script Metadata & Organization*
- Added proper indicator() declaration with title, shorttitle, overlay, and max_labels_count parameters
- Organized inputs into logical groups using group parameter
- Added descriptive tooltip parameters for all inputs

2. *Input Structure*
- Added timeframe input for higher timeframe analysis
- Added ATR and volume multipliers for breakout validation
- Incorporated RSI settings for overbought/oversold conditions
- Added stop loss multiplier for risk management
- Included visual customization options (colors, widths)

3. *Advanced Filter System*
- Added toggle switches for EMA, Volume, RSI, and Wick conditions
- Implemented configurable thresholds for each filter:
- Volume spike detection
- Wick length requirements
- EMA positioning

4. *Market Structure Logic*
- Improved HTF calculations using request.security()
- Added proper box management with var declarations
- Implemented comprehensive label management system
- Added equilibrium zone visualization between structures

5. *Signal Validation*
- Added volume spike detection
- Implemented wick length analysis
- Added RSI condition checking
- Included EMA position filtering
- Added candle close direction check

6. *Test/Retest System*
- Added distinct labeling for:
- Initial tests (pre-signal)
- Retests (post-signal)
- Fakeouts (failed breakouts)
- Implemented bar counters to track signal age

7. *Risk Management*
- Added dynamic stop loss lines based on ATR
- Made SL distance configurable via multiplier

8. *Visual Improvements*
- Added color-coded boxes for different zones
- Implemented proper label styling
- Added line width customization
- Included transparency controls

9. *Alert System*
- Added proper alertcondition() declarations
- Included descriptive alert messages

### TradingView Compliance Notes:

1. *Security Best Practices*
- All HTF data properly wrapped in request.security()
- No repainting issues - only uses confirmed closes
- No future leaks in calculations

2. *Resource Management*
- Added max_labels_count to prevent performance issues
- Implemented proper cleanup of drawing objects (boxes/labels/lines)
- Used var for persistent variables

3. *Input Validation*
- Added minval/maxval constraints on numeric inputs
- Included proper step values for float inputs
- Set reasonable default values

4. *Documentation*
- Comprehensive tooltips for all user inputs
- Clear grouping of related parameters
- Descriptive variable naming

5. *Visual Clarity*
- Color-coding follows TradingView best practices
- Transparency used appropriately for overlay elements
- Text contrasts ensured for readability

The second version represents a significant improvement in functionality, customization, and reliability while fully complying with TradingView's Pine Script standards. The code is better organized, more feature-complete, and includes proper documentation for all user-facing elements.
Note di rilascio
1. Updates and new additions made to the second code are as follows:

New Parameters:

checkATR: Parameter used to enable the ATR (Average True Range) condition.
atr_length: Setting the number of periods used in the ATR calculation.
atr_multiplier: Multiplier value used for matching with ATR.
checkAdx: Parameter used to enable the ADX (Average Directional Index) condition.
adxlen: Setting the number of periods used in the ADX calculation.
dilen: Setting the number of periods used in the DI (Directional Index) calculation.
adx_trendThreshold: Threshold value used to determine trend strength.
use_trend: Parameter used to enable the trend filter.
ma_type: Parameter used to select the moving average type used in the trend calculation.
trend_length: Setting the number of periods used in the trend calculation.
New Variables and Calculations:

trend: Variable used to calculate the trend value.
adxValue: Variable used to calculate ADX value.

strongTrend: Variable used to determine strong trend condition.

bull_retest_condition and bear_retest_condition: Variables used to determine test and retest conditions.
Updated Conditions:

bullish_break and bearish_break conditions have been updated. They now include ATR, ADX and trend conditions.
sell_condition and buy_condition conditions have been updated. They now include trend, RSI, volume and wick conditions.
New Functions:

dirmov function: Function used to calculate DI (Directional Index) value.
adx function: Function used to calculate ADX (Average Directional Index) value.
Appearance Changes:

box_color_bull, box_color_bear, line_width, show_equilibrium and box_color_eq parameters have been moved to "Customized Settings" group.
These updates aim to make the indicator more sensitive and flexible. By adding new parameters and conditions, users are able to adapt the indicator according to their own strategies.

2. The changes affect the behavior and output of the code as follows:

ATR Condition:

When the checkATR parameter is enabled, it adds the condition that breakouts must exceed the ATR value. This makes breakouts more robust and reliable.
The atr_length and atr_multiplier parameters are used to set the ATR calculation and the condition that breakouts must exceed the ATR value.
ADX Condition:

When the checkAdx parameter is enabled, it adds the condition that breakouts must meet strong trend conditions. This makes breakouts more robust and reliable.
The adxlen, dilen, and Adx_trendThreshold parameters are used to set the ADX calculation and the strong trend condition.
Trend Filter:

When the use_trend parameter is enabled, it adds the condition that breakouts must be consistent with the trend. This makes breakouts more robust and reliable.
The ma_type and trend_length parameters are used to set the trend calculation.
Test and Retest Conditions:

The variables bull_retest_condition and bear_retest_condition are used to specify test and retest conditions. This makes breakouts more robust and reliable.
Appearance Changes:

The box_color_bull, box_color_bear, line_width, show_equilibrium, and box_color_eq parameters have been moved to the "Customized Settings" group. This allows users to more easily customize the appearance.

These changes make the code more precise and flexible. Users can customize the indicator according to their own strategies and achieve better results.

For example, a user can enable the checkATR and checkAdx parameters and set the atr_length and adxlen parameters. This makes breakouts more robust and reliable. They can also enable the use_trend parameter and set the ma_type and trend_length parameters. This makes breakouts trend-compatible.

This way, users can customize the indicator according to their own strategies and achieve better results.
Note di rilascio
1. User Inputs and Customization:
ATR Multiplier: Increased from 0.3 to 0.5, making the breakout condition stricter.
Volume Multiplier: Increased from 0.5 to 0.8, requiring a higher volume increase for breakout confirmation.
Fibonacci Levels: Added Fibonacci retracement levels and provided additional technical analysis tools.
Moving Averages: Added options for fast and slow moving averages (SMA, EMA, WMA, HMA) with customizable lengths, and improved trend analysis.
Candlestick Patterns: Added detection for various candlestick patterns (e.g. Hammer, Engulfing, Doji), providing more detailed buy/sell signals.
2. Technical Indicators and Conditions:
Moving Average Crossover: Added conditions for moving average crossovers (fast MA vs. slow MA) to improve trend detection.
Candlestick Patterns: Integrated multiple candlestick patterns for buy/sell signals and added a pattern recognition layer.
Fibonacci Retracement Levels: Added Fibonacci levels to identify potential support and resistance areas.

3. Visual Enhancements:
Fibonacci Lines: Added visual representation of Fibonacci retracement levels on the chart.
Manipulation Zones: Added detection and visualization of potential manipulation zones, highlighting potential stop hunts or liquidity grab areas.

4. Signal Conditions:
Improved Buy/Sell Conditions: Signals are more robust by including candlestick charts and moving average crossovers in buy/sell conditions.
Volume Increase Threshold: Increased volume increase threshold, ensuring signals are confirmed by significant volume changes.

5. Alerts and Notifications:
Alerts for Fake Accounts: Added alerts for fake account detection and notified users when a potential fake account is created.
Confirmed Signals: Added alerts for confirmed buy/sell signals at candle close and provided timely notifications.
6. Manipulation Detection:
Manipulation Zones: Added the ability to detect and highlight manipulation zones to help traders detect potential market manipulation.

Improvement Summary:
Advanced Technical Analysis: Added moving averages, candlestick patterns, and Fibonacci levels.

Improved Signal Validation: Stricter requirements for volume spikes, ATR multipliers, and candlestick charts.

Visual Enhancements: Added Fibonacci lines and manipulation zones for better visual analysis.

6. Fixed visuals to prevent the deletion of retrospective Trading signals and allow for customization of your own strategy.

Additional Alerts: Added alerts for fake outs and confirmed signals.
Note di rilascio
1. ADL (Accumulation/Distribution Line) was used for the breakout
2. CMF (Chaikin Money Flow) was used for the breakout.

These two indicators help determine trend strength and potential reversal points by analyzing the combination of volume and price action.

1. ADL (Accumulation/Distribution Line) – Accumulation/Distribution Line
What Does It Do?
Measures buying (accumulation) and selling (distribution) pressure.

Checks price-volume convergence (for example, if ADL is rising while price is rising, the trend is strong).

Detects divergence (for example, if ADL is falling while price is making new highs, the trend may be weakening).

How Does It Work?
CLV (Close Location Value) calculates the price’s position in the range of the current day with the formula:

CLV = [(Close - Low) - (High - Close)] / (High - Low)
Close to +1: Close at the highest level → Buying pressure

Close to -1: Close at the lowest level → Selling pressure

ADL = Previous ADL + (CLV × Volume) → Creates a volume-weighted accumulation/distribution line.

Why is it used in TradingView?
Trend confirmation: Rising ADL supports an uptrend.

Breakout confirmation: If ADL is increasing at the time of the breakout, the move is reliable.

Filters out weak breakouts: If ADL is falling while the price is breaking up, it could be a fake move.

2. CMF (Chaikin Money Flow) – What is Chaikin Money Flow used for?
It measures the inflow/outflow of money supported by volume.

Determines trend strength (CMF above +0.05 → Strong uptrend, below -0.05 → Strong downtrend).

Shows buying and selling pressure.

How Does It Work?
Uses Money Flow Multiplier (same as CLV):

CMF = (20-period SMA of Money Flow Volume) / (20-period SMA of Volume)
Positive CMF: Buying pressure (money is entering the market).

Negative CMF: Selling pressure (money is leaving the market).

Why Use It on TradingView?
Confirms trend continuation:

If CMF is positive on a bullish breakout → Trend is strong.

If CMF is negative on a bearish breakout → Selling pressure is continuing.

Eliminate weak breakouts:

If CMF is falling while price is breaking up → Possible fakeout.

Intended Use in the Scenario (Code Example)
pinescript
// Bullish Breakout
bullish_break = close_tf > highest_high_tf[1] and
(not checkAdl or adlIncreasing) and // If ADL is rising, the trend is strong
(not checkCmf or cmfIncreasing) // If CMF is rising, there is buying pressure

// Bearish Breakout
bearish_break = close_tf < lowest_low_tf[1] and
(not checkAdl or adlDecreasing) and // If ADL is falling, there is selling pressure
(not checkCmf or cmfDecreasing) // If CMF is negative, the distribution continues
What Does It Provide?

✅ Filters out fake breakouts:

If ADL/CMF is falling while the price is breaking upwards, the breakout may be weak.

If the price is breaking down and ADL/CMF is rising, there may be a backlash.

✅ Confirms that the trend is supported by volume:

If CMF and ADL are rising, there is real buying interest.

✅ Generates more reliable signals:

Creates a more robust strategy by looking not only at the price breakout, but also at volume and money flow.

Conclusion: Why are CMF and ADL Important?
Price alone is not enough! Volume and money flow indicate the sustainability of the trend.

Tests the validity of breakouts:

If ADL is rising → Breakout is reliable.

If CMF is positive → Buyers are in control.

Reduces false signals: The combination of Volume + CMF + ADL allows you to build more consistent strategies.

📌 Using these indicators on TradingView, you can:

✔ Create more reliable breakout strategies.

✔ Filter out weak trends and avoid unnecessary trades.
✔ You can achieve a higher success rate by capturing trends supported by volume.

Declinazione di responsabilità

Le informazioni ed i contenuti pubblicati non costituiscono in alcun modo una sollecitazione ad investire o ad operare nei mercati finanziari. Non sono inoltre fornite o supportate da TradingView. Maggiori dettagli nelle Condizioni d'uso.