High/Low LabelsThis simple Version 6 script labels each bar on the chart with Green labels noting HH for higher highs and HL for higher lows. And Red labels noting LH for lower highs and LL for lower lows. Works on any Trading View chart and any time frame. Any comments or suggestions, please do!
Indicators and strategies
Gold Pro StrategyHere’s the strategy description in a chat format:
---
**Gold (XAU/USD) Trend-Following Strategy**
This **trend-following strategy** is designed for trading gold (XAU/USD) by combining moving averages, MACD momentum indicators, and RSI filters to capture sustained trends while managing volatility risks. The strategy uses volatility-adjusted stops to protect gains and prevent overexposure during erratic price movements. The aim is to take advantage of trending markets by confirming momentum and ensuring entries are not made at extreme levels.
---
**Key Components**
1. **Trend Identification**
- **50 vs 200 EMA Crossover**
- **Bullish Trend:** 50 EMA crosses above 200 EMA, and the price closes above the 200 EMA
- **Bearish Trend:** 50 EMA crosses below 200 EMA, and the price closes below the 200 EMA
2. **Momentum Confirmation**
- **MACD (12,26,9)**
- **Buy Signal:** MACD line crosses above the signal line
- **Sell Signal:** MACD line crosses below the signal line
- **RSI (14 Period)**
- **Bullish Zone:** RSI between 50-70 to avoid overbought conditions
- **Bearish Zone:** RSI between 30-50 to avoid oversold conditions
3. **Entry Criteria**
- **Long Entry:** Bullish trend, MACD bullish crossover, and RSI between 50-70
- **Short Entry:** Bearish trend, MACD bearish crossover, and RSI between 30-50
4. **Exit & Risk Management**
- **ATR Trailing Stops (14 Period):**
- Initial Stop: 3x ATR from entry price
- Trailing Stop: Adjusts to lock in profits as price moves favorably
- **Position Sizing:** 100% of equity per trade (high-risk strategy)
---
**Key Logic Flow**
1. **Trend Filter:** Use the 50/200 EMA relationship to define the market's direction
2. **Momentum Confirmation:** Confirm trend momentum with MACD crossovers
3. **RSI Validation:** Ensure RSI is within non-extreme ranges before entering trades
4. **Volatility-Based Risk Management:** Use ATR stops to manage market volatility
---
**Visual Cues**
- **Blue Line:** 50 EMA
- **Red Line:** 200 EMA
- **Green Triangles:** Long entry signals
- **Red Triangles:** Short entry signals
---
**Strengths**
- **Clear Trend Focus:** Avoids counter-trend trades
- **RSI Filter:** Prevents entering overbought or oversold conditions
- **ATR Stops:** Adapts to gold’s inherent volatility
- **Simple Rules:** Easy to follow with minimal inputs
---
**Weaknesses & Risks**
- **Infrequent Signals:** 50/200 EMA crossovers are rare
- **Potential Missed Opportunities:** Strict RSI criteria may miss some valid trends
- **Aggressive Position Sizing:** 100% equity allocation can lead to large drawdowns
- **No Profit Targets:** Relies on trailing stops rather than defined exit targets
---
**Performance Profile**
| Metric | Expected Range |
|----------------------|---------------------|
| Annual Trades | 4-8 |
| Win Rate | 55-65% |
| Max Drawdown | 25-35% |
| Profit Factor | 1.8-2.5 |
---
**Optimization Recommendations**
1. **Increase Trade Frequency**
Adjust the EMAs to shorter periods:
- `emaFastLen = input.int(30, "Fast EMA")`
- `emaSlowLen = input.int(150, "Slow EMA")`
2. **Relax RSI Filters**
Adjust the RSI range to:
- `rsiBullish = rsi > 45 and rsi < 75`
- `rsiBearish = rsi < 55 and rsi > 25`
3. **Add Profit Targets**
Introduce a profit target at 1.5% above entry:
```pine
strategy.exit("Long Exit", "Long",
stop=longStopPrice,
profit=close*1.015, // 1.5% target
trail_offset=trailOffset)
```
4. **Reduce Position Sizing**
Risk a smaller percentage per trade:
- `default_qty_value=25`
---
**Best Use Case**
This strategy excels in **strong trending markets** such as gold rallies during economic or geopolitical crises. However, during sideways or choppy market conditions, the strategy might require manual intervention to avoid false signals. Additionally, integrating fundamental analysis—like monitoring USD weakness or geopolitical risks—can enhance its effectiveness.
---
This strategy offers a balanced approach for trading gold, combining trend-following principles with risk management tailored to the volatility of the market.
Zero Lag Signals (Pine Script) - CorrectedZero-Lag EMA: It calculates a zero-lag EMA using a custom function. This type of EMA aims to reduce lag compared to a traditional EMA, providing a more responsive indicator of price movement.
Volatility: It calculates volatility using the Average True Range (ATR) indicator and a user-defined multiplier.
Angle: It calculates the angle of the zero-lag EMA by comparing its current value to its value 10 bars ago. This helps determine the trend and momentum of the price.
Buy/Sell Signals:
Buy Signal: Triggered when the angle of the zero-lag EMA is above a certain threshold and the current price is above the EMA.
Sell Signal: Triggered when the angle of the zero-lag EMA is below a certain threshold and the current price is below the EMA.
Key Features:
Zero-Lag EMA: Reduces lag for a more responsive indicator.
Volatility Bands: Helps identify potential entry and exit points based on volatility.
Angle Calculation: Provides insights into the trend and momentum of the price.
Customizable Parameters: Allows users to adjust the length of the EMA, volatility multiplier, and signal angle threshold.
Visual Signals and Alerts: Displays buy and sell signals on the chart and triggers alerts.
This indicator can be used to:
Identify potential buy and sell opportunities in trending markets.
Filter out false signals in choppy markets.
Confirm the strength of a trend.
Time entries and exits based on momentum and volatility.
Trend & ADX by Gideon for Indian MarketsThis indicator is designed to help traders **identify strong trends** using the **Kalman Filter** and **ADX** (Average Directional Index). It provides **Buy/Sell signals** based on trend direction and ADX strength. I wanted to create something for Indian markets since there are not much available.
In a nut-shell:
✅ **Buy when the Kalman Filter turns green, and ADX is strong.
❌ **Sell when the Kalman Filter turns red, and ADX is strong.
📌 **Ignore signals if ADX is weak (below threshold).
📊 Use on 5-minute timeframes for intraday trading.
------------------------------------------------------------------------
1. Understanding the Indicator Components**
- **Green Line:** Indicates an **uptrend**.
- **Red Line:** Indicates a **downtrend**.
- The **line color change** signals a potential **trend reversal**.
**ADX Strength Filter**
- The **ADX (orange line)** measures trend strength.
- The **blue horizontal line** marks the **ADX threshold** (default: 20).
- A **Buy/Sell signal is only valid if ADX is above the threshold**, ensuring a strong trend.
**Buy & Sell Signals**
- **Buy Signal (Green Up Arrow)**
- Appears **one candle before** the Kalman line turns green.
- ADX must be **above the threshold** (default: 20).
- Suggests entering a **long position**.
- **Sell Signal (Red Down Arrow)**
- Appears **one candle before** the Kalman line turns red.
- ADX must be **above the threshold** (default: 20).
- Suggests entering a **short position**.
2. Best Settings for 5-Minute Timeframe**
For day trading on the **5-minute chart**, the following settings work best:
- **Kalman Filter Length:** `50`
- **Process Noise (Q):** `0.1`
- **Measurement Noise (R):** `0.01`
- **ADX Length:** `14`
- **ADX Threshold:** `20`
- **(Increase to 25-30 for more reliable signals in volatile markets)**
3. How to Trade with This Indicator**
**Entry Rules**
✅ **Buy Entry**
- Wait for a **green arrow (Buy Signal).
- Kalman Line must **turn green**.
- ADX must be **above the threshold** (strong trend confirmed).
- Enter a **long position** on the next candle.
❌ **Sell Entry**
- Wait for a **red arrow (Sell Signal).
- Kalman Line must **turn red**.
- ADX must be **above the threshold** (strong trend confirmed).
- Enter a **short position** on the next candle.
**Exit & Risk Management**
📌 **Stop Loss**:
- Place stop-loss **below the previous swing low** (for buys) or **above the previous swing high** (for sells).
📌 **Take Profit:
- Use a **Risk:Reward Ratio of 1:2 or 1:3.
- Exit when the **Kalman Filter color changes** (opposite trend signal).
📌 **Avoid Weak Trends**:
- **No trades when ADX is below the threshold** (low trend strength).
4. Additional Tips
- Works best on **liquid assets** like **Bank Nifty, Nifty 50, and large-cap stocks**.
- **Avoid ranging markets** with low ADX values (<20).
- Use alongside **volume analysis and support/resistance levels** for confirmation.
- Experiment with **ADX Threshold (increase for stronger signals, decrease for more trades).**
Best of Luck traders ! 🚀
Volume with EMA and Coloring RulesSummary
This indicator plots the market’s volume as a histogram in a separate panel (not overlaid on the main price chart). An EMA (Exponential Moving Average) is then calculated based on the volume. The color of each volume bar switches dynamically:
• Blue when the bar’s volume is higher than the EMA
• White when the bar’s volume is lower than or equal to the EMA
This simple visual cue allows you to quickly see if the market’s current volume is above or below its average trend.
How to Use
1. Add to Chart
Apply the indicator to your TradingView chart, and it will open in a separate panel beneath the price.
2. Adjust EMA Length
Modify the “EMA Length” to control how quickly the average volume adapts to changes.
3. Interpretation
• Blue bars may indicate stronger-than-usual participation.
• White bars indicate volume is relatively lower compared to its recent average.
This indicator provides an at-a-glance way to see if trading activity is intensifying or easing, which can be paired with other technical or fundamental tools to help confirm market shifts or potential opportunities.
Johnny's Machine Learning Moving Average (MLMA) w/ Trend Alerts📖 Overview
Johnny's Machine Learning Moving Average (MLMA) w/ Trend Alerts is a powerful adaptive moving average indicator designed to capture market trends dynamically. Unlike traditional moving averages (e.g., SMA, EMA, WMA), this indicator incorporates volatility-based trend detection, Bollinger Bands, ADX, and RSI, offering a comprehensive view of market conditions.
The MLMA is "machine learning-inspired" because it adapts dynamically to market conditions using ATR-based windowing and integrates multiple trend strength indicators (ADX, RSI, and volatility bands) to provide an intelligent moving average calculation that learns from recent price action rather than being static.
🛠 How It Works
1️⃣ Adaptive Moving Average Selection
The MLMA automatically selects one of four different moving averages:
📊 EMA (Exponential Moving Average) – Reacts quickly to price changes.
🔵 HMA (Hull Moving Average) – Smooth and fast, reducing lag.
🟡 WMA (Weighted Moving Average) – Gives recent prices more importance.
🔴 VWAP (Volume Weighted Average Price) – Accounts for volume impact.
The user can select which moving average type to use, making the indicator customizable based on their strategy.
2️⃣ Dynamic Trend Detection
ATR-Based Adaptive Window 📏
The Average True Range (ATR) determines the window size dynamically.
When volatility is high, the moving average window expands, making the MLMA more stable.
When volatility is low, the window shrinks, making the MLMA more responsive.
Trend Strength Filters 📊
ADX (Average Directional Index) > 25 → Indicates a strong trend.
RSI (Relative Strength Index) > 70 or < 30 → Identifies overbought/oversold conditions.
Price Position Relative to Upper/Lower Bands → Determines bullish vs. bearish momentum.
3️⃣ Volatility Bands & Dynamic Support/Resistance
Bollinger Bands (BB) 📉
Uses standard deviation-based bands around the MLMA to detect overbought and oversold zones.
Upper Band = Resistance, Lower Band = Support.
Helps traders identify breakout potential.
Adaptive Trend Bands 🔵🔴
The MLMA has built-in trend envelopes.
When price breaks the upper band, bullish momentum is confirmed.
When price breaks the lower band, bearish momentum is confirmed.
4️⃣ Visual Enhancements
Dynamic Gradient Fills 🌈
The trend strength (ADX-based) determines the gradient intensity.
Stronger trends = More vivid colors.
Weaker trends = Lighter colors.
Trend Reversal Arrows 🔄
🔼 Green Up Arrow: Bullish reversal signal.
🔽 Red Down Arrow: Bearish reversal signal.
Trend Table Overlay 🖥
Displays ADX, RSI, and Trend State dynamically on the chart.
📢 Trading Signals & How to Use It
1️⃣ Bullish Signals 📈
✅ Conditions for a Long (Buy) Trade:
The MLMA crosses above the lower band.
The ADX is above 25 (confirming trend strength).
RSI is above 55, indicating positive momentum.
Green trend reversal arrow appears (confirmation of a bullish reversal).
🔹 How to Trade It:
Enter a long trade when the MLMA turns bullish.
Set stop-loss below the lower Bollinger Band.
Target previous resistance levels or use the upper band as take-profit.
2️⃣ Bearish Signals 📉
✅ Conditions for a Short (Sell) Trade:
The MLMA crosses below the upper band.
The ADX is above 25 (confirming trend strength).
RSI is below 45, indicating bearish pressure.
Red trend reversal arrow appears (confirmation of a bearish reversal).
🔹 How to Trade It:
Enter a short trade when the MLMA turns bearish.
Set stop-loss above the upper Bollinger Band.
Target the lower band as take-profit.
💡 What Makes This a Machine Learning Moving Average?
📍 1️⃣ Adaptive & Self-Tuning
Unlike static moving averages that rely on fixed parameters, this MLMA automatically adjusts its sensitivity to market conditions using:
ATR-based dynamic windowing 📏 (Expands/contracts based on volatility).
Adaptive smoothing using EMA, HMA, WMA, or VWAP 📊.
Multi-indicator confirmation (ADX, RSI, Volatility Bands) 🏆.
📍 2️⃣ Intelligent Trend Confirmation
The MLMA "learns" from recent price movements instead of blindly following a fixed-length average.
It incorporates ADX & RSI trend filtering to reduce noise & false signals.
📍 3️⃣ Dynamic Color-Coding for Trend Strength
Strong trends trigger more vivid colors, mimicking confidence levels in machine learning models.
Weaker trends appear faded, suggesting uncertainty.
🎯 Why Use the MLMA?
✅ Pros
✔ Combines multiple trend indicators (MA, ADX, RSI, BB).
✔ Automatically adjusts to market conditions.
✔ Filters out weak trends, making it more reliable.
✔ Visually intuitive (gradient colors & reversal arrows).
✔ Works across all timeframes and assets.
⚠️ Cons
❌ Not a standalone strategy → Best used with volume confirmation or candlestick analysis.
❌ Can lag slightly in fast-moving markets (due to smoothing).
Volume Delta with Bollinger Bands [EMA]TL;DR
This indicator displays a “Volume Delta” candle chart based on a lower timeframe approximation of up vs. down volume. Bollinger Bands (using an EMA and a configurable standard deviation multiplier) highlight when Volume Delta exceeds typical volatility thresholds. Green bars will darken when Volume Delta is above the upper Bollinger band, and red bars will darken when Volume Delta is below the lower Bollinger band. You can optionally include wicks in the Bollinger calculations. Note : TradingView uses tick-based volume data, so these values may not precisely match true market orders.
What Is Volume Delta ?
• Volume Delta is a metric that identifies buying vs. selling activity in a market by distinguishing between orders transacting at the ask (buy volume) and orders transacting at the bid (sell volume).
• A positive Volume Delta indicates more buy volume during a bar, while a negative Volume Delta indicates more sell volume.
How TradingView Calculates Volume Delta
• TradingView relies on tick data to approximate up/down volume. This may not perfectly capture true order-flow distribution, particularly on higher timeframes or illiquid symbols.
• While it can provide useful insights into volume flow, keep in mind the underlying data’s limitations.
Key Features of This Indicator
1. Automatic or Custom Lower Timeframe Data
• The script can automatically select a lower timeframe for Volume Delta, or you can manually specify one in the settings.
2. Bollinger Bands on Volume Delta
• Uses an EMA of the Volume Delta (or a wick-based average) and calculates a standard deviation.
• The upper and lower bands highlight when activity deviates from typical volatility.
3. Configurable Wick Inclusion
• Decide whether to use only the “close” (lastVolume) of the Volume Delta bar or the average of its wicks ((maxVolume + minVolume) / 2) for Bollinger calculations.
4. Dynamic Bar Colors
• Positive Volume Delta bars turn dark green if they exceed the upper Bollinger band, otherwise lighter green .
• Negative Volume Delta bars turn dark red if they fall below the lower Bollinger band, otherwise lighter red .
How To Use
1. Add the Indicator to Your Chart
• Apply it to any symbol and timeframe in TradingView.
• Configure the lower timeframe for Volume Delta if desired.
2. Adjust Bollinger Settings
• Bollinger Length defines the EMA and standard deviation period.
• Bollinger Multiplier sets how far the bands lie from the EMA.
3. Choose Whether To Use Wicks
• Toggle to use the average of high/low for a potentially more volatile reading.
• Turn it off to rely solely on the Volume Delta “close.”
4. Interpret the Signals
• Dark Green Above the Upper Band : Suggests strong buying pressure above normal.
• Lighter Green : Positive but within typical volatility bounds.
• Dark Red Below the Lower Band : Suggests strong selling pressure below normal.
• Lighter Red : Negative but within typical volatility.
Important Caveats
• TradingView Volume Data : Tick-based and aggregated data may not reflect actual order-flow precisely.
• Context Matters : Combine Volume Delta with other forms of analysis (price action, support/resistance, etc.) to form a more comprehensive strategy.
VWAP Bands with ML [CryptoSea]VWAP Machine Learning Bands is an advanced indicator designed to enhance trading analysis by integrating VWAP with a machine learning-inspired adaptive smoothing approach. This tool helps traders identify trend-based support and resistance zones, predict potential price movements, and generate dynamic trade signals.
Key Features
Adaptive ML VWAP Calculation: Uses a dynamically adjusted SMA-based VWAP model with volatility sensitivity for improved trend analysis.
Forecasting Mechanism: The 'Forecast' parameter shifts the ML output forward, providing predictive insights into potential price movements.
Volatility-Based Band Adjustments: The 'Sigma' parameter fine-tunes the impact of volatility on ML smoothing, adapting to market conditions.
Multi-Tier Standard Deviation Bands: Includes two levels of bands to define potential breakout or mean-reversion zones.
Dynamic Trend-Based Colouring: The VWAP and ML lines change colour based on their relative positions, visually indicating bullish and bearish conditions.
Custom Signal Detection Modes: Allows traders to choose between signals from Band 1, Band 2, or both, for more tailored trade setups.
In the image below, you can see an example of the bands on higher timeframe showing good mean reversion signal opportunities, these tend to work better in ranging markets rather than strong trending ones.
How It Works
VWAP & ML Integration: The script computes VWAP and applies a machine learning-inspired adjustment using SMA smoothing and volatility-based adaptation.
Forecasting Impact: The 'Forecast' setting shifts the ML output forward in time, allowing for anticipatory trend analysis.
Volatility Scaling (Sigma): Adjusts the ML smoothing sensitivity based on market volatility, providing more responsive or stable trend lines.
Trend Confirmation via Colouring: The VWAP line dynamically switches colour depending on whether it is above or below the ML output.
Multi-Level Band Analysis: Two standard deviation-based bands provide a framework for identifying breakouts, trend reversals, or continuation patterns.
In the example below, we can see some of the most reliable signals where we have mean reversion signals from the band whilst the price is also pulling back into the VWAP, these signals have the additional confluence which can give you a higher probabilty move.
Alerts
Bullish Signal Band 1: Alerts when the price crosses above the lower ML Band 1.
Bearish Signal Band 1: Alerts when the price crosses below the upper ML Band 1.
Bullish Signal Band 2: Alerts when the price crosses above the lower ML Band 2.
Bearish Signal Band 2: Alerts when the price crosses below the upper ML Band 2.
Filtered Bullish Signal: Alerts when a bullish signal is triggered based on the selected signal detection mode.
Filtered Bearish Signal: Alerts when a bearish signal is triggered based on the selected signal detection mode.
Application
Trend & Momentum Analysis: Helps traders identify key market trends and potential momentum shifts.
Dynamic Support & Resistance: Standard deviation bands serve as adaptive price zones for potential breakouts or reversals.
Enhanced Trade Signal Confirmation: The integration of ML smoothing with VWAP provides clearer entry and exit signals.
Customizable Risk Management: Allows users to adjust parameters for fine-tuned signal detection, aligning with their trading strategy.
The VWAP Machine Learning Bands indicator offers traders an innovative tool to improve market entries, recognize potential reversals, and enhance trend analysis with intelligent data-driven signals.
Instantaneous Trendline with Cloud Instantaneous Trendline with Cloud
Introduction & History
The Instantaneous Trendline was introduced by John Ehlers, a well-known figure in the field of technical analysis, particularly for applying digital signal processing concepts to financial markets. Ehlers aimed to create an indicator that reacts to market price changes more quickly than traditional moving averages, yet remains smooth enough to avoid excessive noise. By incorporating concepts from digital filtering, he devised a formula that calculates a trendline with minimal lag—hence the term “instantaneous.”
Purpose
The primary purpose of the Instantaneous Trendline with Cloud is to provide traders and analysts with a responsive, smoothed line that closely follows market price movements. Additionally, this script enhances the visual cues by adding a cloud fill to highlight bullish and bearish zones:
Trend Identification
The ITL (Instantaneous Trendline) is plotted alongside the price. When price consistently stays above the ITL, it may signal an uptrend. Conversely, when price dips below the ITL, it can suggest a downtrend.
Signal Generation
Crossover points between the price and the ITL can serve as potential entry or exit signals. A bullish crossover (price moving above the ITL) often indicates the start of upward momentum, while a bearish crossover (price dropping below the ITL) may point to downward momentum.
Noise Reduction
By applying digital filtering concepts and smoothing through the alpha (smoothing coefficient), the ITL reduces noise while still responding relatively quickly to price changes. Traders can adjust alpha to make the trendline more reactive (higher alpha) or smoother (lower alpha).
Clarity via Cloud Fill
A color-coded cloud between the price and the ITL provides an at-a-glance view of market bias. The green cloud highlights potentially bullish phases, while the red cloud highlights potentially bearish phases.
Experiment with the alpha value (commonly between 0.2 and 0.3) to find a balance that suits your preference for responsiveness versus smoothness.
This indicator implements John Ehlers’ Instantaneous Trendline concept and plots a smoothed trendline (ITL) alongside the price. The trendline is controlled by a user-defined smoothing coefficient (alpha). A higher alpha makes the trendline respond more quickly to price changes, while a lower alpha produces a smoother line.
A color-filled cloud helps traders identify bullish and bearish conditions:
Green cloud if the price is above the ITL (bullish potential).
Red cloud if the price is below the ITL (bearish potential).
Key Benefits
Trend Visualization: Quickly see if the market is in an uptrend or downtrend based on the position of the price relative to the trendline.
Crossover Signals: Identify potential shifts in trend or momentum when the price crosses the ITL.
Customizable Sensitivity: Adjust the alpha parameter to make the ITL more or less reactive to price moves. Use this tool to better visualize short-term trend changes and potential entry/exit signals in conjunction with other technical analysis methods.
BB ATR Fractal MMThe Bollinger Bands + ATR with Fractal indicator is a powerful combination of Bollinger Bands, ATR (Average True Range), and Fractal to help identify market volatility and potential entry/exit points on the chart.
Bollinger Bands help to assess the market’s volatility by calculating upper and lower bands based on the simple moving average (SMA) and standard deviation. It’s an excellent tool for identifying overbought and oversold conditions.
ATR (Average True Range) is used to measure market volatility. It helps determine how much the price is moving, and it can be used to adjust the Bollinger Bands, creating bands that reflect the current volatility more accurately.
Fractal helps to identify peaks and troughs in the market, supporting decision-making by highlighting potential reversal points. Fractals mark regions where price may reverse direction, making it easier to spot possible trade opportunities.
How to Use:
Bollinger Bands Upper and Lower Bands: These bands help to identify overbought or oversold conditions. If the price breaks above the upper band, the market may be overbought. If the price breaks below the lower band, the market may be oversold.
ATR: It indicates the volatility level of the market. When the market shows large volatility (ATR increases), the Bollinger Bands expand to reflect higher price swings.
Fractal: Arrows appear at the market’s peaks and troughs, helping identify entry points for buying (at fractal lows) or selling (at fractal highs). These signals can help you make trading decisions based on potential price reversals.
TOTAL3/BTC This Pine Script™ code, named "TOTAL3/BTC with Arrow," is designed for cryptocurrency analysis on TradingView.
This script essentially provides a visual tool for traders to gauge when altcoins might be gaining or losing ground relative to Bitcoin through moving average analysis and color-coded trend indication.
Intention was to help the community with a script based on classic TA only.
Use it with SASDv2r indicator.
Feel free to make it better. If you did so, please let me know.
Main elements:
Data Fetching: It retrieves market cap data for all cryptocurrencies excluding Bitcoin and Ethereum (TOTAL3) and for Bitcoin (BTC).
Ratio Calculation: The script calculates the ratio of TOTAL3 to BTC market caps, which indicates how altcoins (excluding ETH) are performing relative to Bitcoin.
Plotting the Ratio: This ratio is plotted on the chart with a blue line, allowing traders to see the relative performance visually.
Moving Averages: Two Simple Moving Averages (SMA) are calculated for this ratio, one for 20 periods (ma20) and another for 50 periods (ma50), though these are not plotted in the current version of the code.
Reference Lines: Horizontal lines are added at ratios of 0.3 and 0.8 to serve as visual equilibrium points or thresholds for analysis.
Complex Moving Average: The script uses constants (len, len2, cc, smoothe) from another script, suggesting it's adapting or simplifying another's logic for multi-timeframe analysis.
Average Calculation: Two SMAs (avg and avg2) are computed using the constants defined, focusing on different lengths for trend analysis.
Direction Determination: It checks if the moving average is trending up or down by comparing the current value with its value smoothe bars earlier.
Color Coding: The color of the plotted moving average changes based on its direction (lime for up, red for down, aqua if no clear direction), aiding in quick visual interpretation of trends.
Plotting: Finally, the script plots this multi-timeframe moving average with a dynamic color to reflect the current market trend of the TOTAL3/BTC ratio, with a thicker line for visibility.
SASDv2rSensitive Altcoin Season Detector V2
This Pine Script™ code, titled "SASDv2r" (Sensitive Altcoin Season Detector version 2 revised), is designed for cryptocurrency trading analysis on the TradingView platform and tailored for those interested in tracking when altcoins might be outperforming Bitcoin, potentially indicating a market shift towards altcoins.
Feel free to use and modify. If you made it better, please let me know. Intention was to help the community with a tool for retail traders have no access to advanced, MV indicators. Solution uses classic TA only.
Use it witl TOTAL3/BTC indicator.
Please check: it gave signal just before last alt season % rose more than 250%.
Market Cap Data Fetching: The script fetches market capitalization data for Bitcoin, Ethereum, and all other altcoins (excluding Bitcoin and Ethereum) using request.security function.
Altcoin to Bitcoin Ratio: It calculates the ratio of total market cap of altcoins to Bitcoin's market cap (altToBtcRatio), which is central to identifying an "altcoin season."
Moving Averages: Several moving averages are computed for different time frames (50-day SMA, 200-day SMA, 20-day SMA, and 10-day EMA) to analyze trends in the altcoin to Bitcoin ratio.
Momentum Indicators: The script uses RSI (Relative Strength Index) and MACD (Moving Average Convergence Divergence) to gauge momentum and potential reversal points in the market.
Custom Indicators: It includes Volume Weighted Moving Average (VWMA) and a custom momentum indicator (altMomentum and altMomentumAvg) to provide additional insights into market movements.
Volatility Measurement: Bollinger Bands are calculated to assess volatility in the altcoin to Bitcoin ratio, which helps identify periods of high or low market activity.
Visual Analysis: Various plots are added to the chart for visual interpretation, including the altcoin to Bitcoin ratio, different moving averages, and Bollinger Bands.
Alt Season Detection: The script defines conditions for detecting when an "altcoin season" might be starting, based on crossovers of moving averages, RSI levels, MACD signals, and other custom criteria.
Performance Tracking: After signaling an alt season, the script evaluates the performance over the next 30 days by checking if there's been an increase in the altcoin to Bitcoin ratio, adding labels for positive or negative trends.(this one is in progress). Logic still gives false signals and aim is to identify failed signals.
Visual Signals: Labels are placed on the chart to visually indicate the beginning of a potential alt season or the performance outcome after a signal, aiding traders in making informed decisions.
Aggregated Volume (Multi-Exchange)Indicator: Aggregated Volume (Multi-Exchange)
Overview:
The Aggregated Volume (Multi-Exchange) indicator is designed to aggregate trading volume data from multiple exchanges for a specific cryptocurrency pair. The goal is to provide a consolidated view of the total trading volume across different platforms, helping traders and analysts gauge the overall market activity for a given asset.
Features:
Multi-Exchange Support: The indicator allows you to aggregate trading volume data from various exchanges. Users can enable or disable volume data from specific exchanges (e.g., Binance, Bybit, Kucoin, etc.).
Spot and Futures Volumes: The indicator can sum the volume for spot trading and futures trading separately if desired. However, in the current version, it only sums the volume for specific pairs across multiple exchanges, without distinguishing between spot and futures volumes (though this feature can be added if necessary).
Customizable Exchange Selection: Users can select which exchanges' volume data to include in the aggregation.
Real-Time Updates: The volume data is updated in real-time as new bars are formed on the chart, providing an up-to-date picture of the trading volume.
Purpose:
The primary purpose of this indicator is to consolidate trading volume information from multiple exchanges for the same trading pair (e.g., BTC/USD). Traders can use this aggregated volume to gain a better understanding of market activity across various platforms, as well as assess the level of liquidity and interest in a particular asset.
By viewing the total aggregated volume, traders can:
Track market trends: Higher aggregated volume can signal increased market interest, making it easier to spot trends or potential breakouts.
Analyze liquidity: This indicator can help traders assess liquidity in the market, especially when using multiple exchanges.
Identify potential market manipulation: If there is a sudden spike in volume on multiple exchanges, it could signal market manipulation or an event-driven surge.
How it Works:
Volume Aggregation: The indicator collects and sums the volume data for a given symbol (e.g., BTC/USD) from different exchanges like Binance, Bybit, Kucoin, and others.
Multiple Exchanges: The volume data is aggregated from each selected exchange and plotted as a single volume value on the chart.
Real-Time Volume Plotting: The total aggregated volume is then plotted as a histogram on the chart, with the color of the bars changing depending on whether the price is rising or falling (typically green for rising prices and red for falling prices).
Inputs/Settings:
Exchange Selection: A list of checkboxes where users can choose which exchanges' volume data to include (e.g., Binance, Bybit, Kucoin, etc.).
Color Settings: Users can set the color for the histogram bars based on price direction (e.g., green for rising and red for falling).
Volume Calculation: The indicator calculates the volume for a specific cryptocurrency pair across selected exchanges in real-time.
Enhanced Volume Profile█ OVERVIEW
The Enhanced Volume Profile (EVP) is an indicator designed to plot a volume profile on the chart based on either the visible chart range or a fixed lookback period. The script helps analyze the distribution of volume at different price levels over time, providing insights into areas of high trading activity and potential support/resistance zones.
█ KEY FEATURES
1. Visible Chart Range vs. Fixed Lookback Depth
Visible Chart Range
- Default analysis mode
- Calculates profile based on visible portion of the chart
- Dynamically updates with chart view changes
Fixed Lookback Depth
- Optional alternative to visible range
- Uses specified number of bars (10-3000)
- Provides consistent analysis depth
- Independent of chart view
2. Custom Resolution
Auto-Resolution Mode
Automatically selects timeframes based on chart's current timeframe:
≤ 1 minute: Uses 1-minute resolution
≤ 5 minutes: Uses 1-minute resolution
≤ 15 minutes: Uses 5-minute resolution
≤ 1 hour: Uses 5-minute resolution
≤ 4 hours: Uses 15-minute resolution
≤ 12 hours: Uses 15-minute resolution
≤ 1 day: Uses 1-hour resolution
≤ 3 days: Uses 2-hours resolution
≤ 1 week: Uses 4-hours resolution
Custom Resolution Override
Optional override of auto-resolution system
Provides control over data granularity
Must be lower than or equal to chart's timeframe
Falls back to auto-resolution if validation fails
3. Volume Profile Resolution
Adjustable number of points (10-400)
Controls profile granularity
Higher resolution provides more detail
Balance between precision and performance
4. Point of Control (PoC)
Identifies price level with highest traded volume
Optional display with customizable appearance
Adjustable line thickness (1-30)
Configurable color
5. Value Area (VA)
Shows price range of majority trading volume
Adjustable coverage (5-95%), default is 68%
Customizable boundary lines
Configurable lines color and thickness (1-20)
█ INPUT PARAMETERS
Lookback Settings
Use Visible Chart Range
- Default: true
- Calculates profile based on visible bars
- Ideal for focused analysis
Fixed Lookback Bars
- Range: 10-3000
- Default: 200
- Used when visible range is disabled
Resolution Settings
Enable Custom Resolution
- Default: false
- Overrides auto-resolution
Custom Resolution
- Default: 1-minute
- Changes automatically when "Enable Custom Resolution" is disabled
Volume Profile Appearance
Profile Resolution
- Range: 10-400
- Default: 200
- Controls detail level
Profile Width Scale
- Range: 1-50
- Default: 15
- Adjusts profile width
Right Offset
- Range: 0-500
- Default: 20
- Controls spacing from price bars
Profile Fill Color
- Default: #5D606B (70% transparency)
Point of Control Settings
Show Point of Control
- Default: true
- Toggles PoC visibility
PoC Line Thickness
- Range: 1-30
- Default: 1
PoC Line Color
- Default: Red
Value Area Settings
Show Value Area
- Default: true
- Toggles VA lines
Value Area Coverage
- Range: 5-95%
- Default: 68%
Value Area Line Color
- Default: Blue
Value Area Line Thickness
- Range: 1-20
- Default: 1
█ TECHNICAL IMPLEMENTATION DETAILS
Exceeding Bars Management
The script dynamically adjusts the number of bars used in the volume profile calculation based on the selected timeframe and the maximum allowed bars (max_bars_back).
If the total number of bars exceeds the predefined threshold (6000 bars), the script reduces the lookback period (lookback_bars) by trimming some of the historical data, ensuring the chart does not become overloaded with data.
The adjustment is made based on the ratio of bars per candle (bars_per_candle), ensuring that the volume profile remains computationally efficient while maintaining its relevance.
█ EXAMPLE USE CASES
1. Visible Range Mode
For analyzing a recent trend and focusing on only the visible part of the chart, enabling the "Use Visible Chart Range" option calculates the profile based on the current view, without considering historical data outside the visible area.
2. Fixed Lookback Depth
For analyzing a specific period in the past (e.g., the last 200 bars), disabling the visible range and setting a fixed lookback depth of 200 bars ensures the profile always considers the last 200 bars, regardless of the visible range.
3. Custom Resolution
If there’s a need for greater control over the timeframe used for volume profile calculations (e.g., using a 5-minute resolution on a 15-minute chart), enabling custom resolution and setting the desired timeframe provides this control.
HAPPY TRADING ✌️
Multi-indicator Signal Builder [Skyrexio]Overview
Multi-Indicator Signal Builder is a versatile, all-in-one script designed to streamline your trading workflow by combining multiple popular technical indicators under a single roof. It features a single-entry, single-exit logic, intrabar stop-loss/take-profit handling, an optional time filter, a visually accessible condition table, and a built-in statistics label. Traders can choose any combination of 12+ indicators (RSI, Ultimate Oscillator, Bollinger %B, Moving Averages, ADX, Stochastic, MACD, PSAR, MFI, CCI, Heikin Ashi, and a “TV Screener” placeholder) to form entry or exit conditions. This script aims to simplify strategy creation and analysis, making it a powerful toolkit for technical traders.
Indicators Overview
1. RSI (Relative Strength Index)
Measures recent price changes to evaluate overbought or oversold conditions on a 0–100 scale.
2. Ultimate Oscillator (UO)
Uses weighted averages of three different timeframes, aiming to confirm price momentum while avoiding false divergences.
3. Bollinger %B
Expresses price relative to Bollinger Bands, indicating whether price is near the upper band (overbought) or lower band (oversold).
4. Moving Average (MA)
Smooths price data over a specified period. The script supports both SMA and EMA to help identify trend direction and potential crossovers.
5. ADX (Average Directional Index)
Gauges the strength of a trend (0–100). Higher ADX signals stronger momentum, while lower ADX indicates a weaker trend.
6. Stochastic
Compares a closing price to a price range over a given period to identify momentum shifts and potential reversals.
7. MACD (Moving Average Convergence/Divergence)
Tracks the difference between two EMAs plus a signal line, commonly used to spot momentum flips through crossovers.
8. PSAR (Parabolic SAR)
Plots a trailing stop-and-reverse dot that moves with the trend. Often used to signal potential reversals when price crosses PSAR.
9. MFI (Money Flow Index)
Similar to RSI but incorporates volume data. A reading above 80 can suggest overbought conditions, while below 20 may indicate oversold.
10. CCI (Commodity Channel Index)
Identifies cyclical trends or overbought/oversold levels by comparing current price to an average price over a set timeframe.
11. Heikin Ashi
A type of candlestick charting that filters out market noise. The script uses a streak-based approach (multiple consecutive bullish or bearish bars) to gauge mini-trends.
12. TV Screener
A placeholder condition designed to integrate external buy/sell logic (like a TradingView “Buy” or “Sell” rating). Users can override or reference external signals if desired.
Unique Features
1. Multi-Indicator Entry and Exit
You can selectively enable any subset of 12+ classic indicators, each with customizable parameters and conditions. A position opens only if all enabled entry conditions are met, and it closes only when all enabled exit conditions are satisfied, helping reduce false triggers.
2. Single-Entry / Single-Exit with Intrabar SL/TP
The script supports a single position at a time. Once a position is open, it monitors intrabar to see if the price hits your stop-loss or take-profit levels before the bar closes, making results more realistic for fast-moving markets.
3. Time Window Filter
Users may specify a start/end date range during which trades are allowed, making it convenient to focus on specific market cycles for backtesting or live trading.
4. Condition Table and Statistics
A table at the bottom of the chart lists all active entry/exit indicators. Upon each closed trade, an integrated statistics label displays net profit, total trades, win/loss count, average and median PnL, etc.
5. Seamless Alerts and Automation
Configure alerts in TradingView using “Any alert() function call.”
The script sends JSON alert messages you can route to your own webhook.
The indicator can be integrated with Skyrexio alert bots to automate execution on major cryptocurrency exchanges
6. Optional MA/PSAR Plots
For added visual clarity, optionally plot the chosen moving averages or PSAR on the chart to confirm signals without stacking multiple indicators.
Methodology
1. Multi-Indicator Entry Logic
When multiple entry indicators are enabled (e.g., RSI + Stochastic + MACD), the script requires all signals to align before generating an entry. Each indicator can be set for crossovers, crossunders, thresholds (above/below), etc. This “AND” logic aims to filter out low-confidence triggers.
2. Single-Entry Intrabar SL/TP
One Position At a Time: Once an entry signal triggers, a trade opens at the bar’s close.
Intrabar Checks: Stop-loss and take-profit levels (if enabled) are monitored on every tick. If either is reached, the position closes immediately, without waiting for the bar to end.
3. Exit Logic
All Conditions Must Agree: If the trade is still open (SL/TP not triggered), then all enabled exit indicators must confirm a closure before the script exits on the bar’s close.
4. Time Filter
Optional Trading Window: You can activate a date/time range to constrain entries and exits strictly to that interval.
Justification of Methodology
Indicator Confluence: Combining multiple tools (RSI, MACD, etc.) can reduce noise and false signals.
Intrabar SL/TP: Capturing real-time spikes or dips provides a more precise reflection of typical live trading scenarios.
Single-Entry Model: Straightforward for both manual and automated tracking (especially important in bridging to bots).
Custom Date Range: Helps refine backtesting for specific market conditions or to avoid known irregular data periods.
How to Use
1. Add the Script to Your Chart
In TradingView, open Indicators , search for “Multi-indicator Signal Builder”.
Click to add it to your chart.
2. Configure Inputs
Time Filter: Set a start and end date for trades.
Alerts Messages: Input any JSON or text payload needed by your external service or bot.
Entry Conditions: Enable and configure any indicators (e.g., RSI, MACD) for a confluence-based entry.
Close Conditions: Enable exit indicators, along with optional SL (negative %) and TP (positive %) levels.
3. Set Up Alerts
In TradingView, select “Create Alert” → Condition = “Any alert() function call” → choose this script.
Entry Alert: Triggers on the script’s entry signal.
Close Alert: Triggers on the script’s close signal (or if SL/TP is hit).
Skyrexio Alert Bots: You can route these alerts via webhook to Skyrexio alert bots to automate order execution on major crypto exchanges (or any other supported broker).
4. Visual Reference
A condition table at the bottom summarizes active signals.
Statistics Label updates automatically as trades are closed, showing PnL stats and distribution metrics.
Backtesting Guidelines
Symbol/Timeframe: Works on multiple assets and timeframes; always do thorough testing.
Realistic Costs: Adjust commissions and potential slippage to match typical exchange conditions.
Risk Management: If using the built-in stop-loss/take-profit, set percentages that reflect your personal risk tolerance.
Longer Test Horizons: Verify performance across diverse market cycles to gauge reliability.
Example of statistic calculation
Test Period: 2023-01-01 to 2025-12-31
Initial Capital: $1,000
Commission: 0.1%, Slippage ~5 ticks
Trade Count: 468 (varies by strategy conditions)
Win rate: 76% (varies by strategy conditions)
Net Profit: +96.17% (varies by strategy conditions)
Disclaimer
This indicator is provided strictly for informational and educational purposes .
It does not constitute financial or trading advice.
Past performance never guarantees future results.
Always test thoroughly in demo environments before using real capital.
Enjoy exploring the Multi-Indicator Signal Builder! Experiment with different indicator combinations and adjust parameters to align with your trading preferences, whether you trade manually or link your alerts to external automation services. Happy trading and stay safe!
Statistical Arbitrage Pairs Trading - Long-Side OnlyThis strategy implements a simplified statistical arbitrage (" stat arb ") approach focused on mean reversion between two correlated instruments. It identifies opportunities where the spread between their normalized price series (Z-scores) deviates significantly from historical norms, then executes long-only trades anticipating reversion to the mean.
Key Mechanics:
1. Spread Calculation: The strategy computes Z-scores for both instruments to normalize price movements, then tracks the spread between these Z-scores.
2. Modified Z-Score: Uses a robust measure combining the median and Median Absolute Deviation (MAD) to reduce outlier sensitivity.
3. Entry Signal: A long position is triggered when the spread’s modified Z-score falls below a user-defined threshold (e.g., -1.0), indicating extreme undervaluation of the main instrument relative to its pair.
4. Exit Signal: The position closes automatically when the spread reverts to its historical mean (Z-score ≥ 0).
Risk management:
Trades are sized as a percentage of equity (default: 10%).
Includes commissions and slippage for realistic backtesting.
Aj's DikFat Adjusted ADXRAj's DikFat Adjusted ADXR
This indicator is designed to plot the Average Directional Index (ADX) and Average Directional Movement Rating (ADXR) on the chart. The ADX and ADXR are both used to measure the strength of a trend in the market. The script allows you to customize several parameters, including the ADX Length and the Moving Average Method used for smoothing the directional movement indicators.
Key Features:
- ADX Length : Defines the number of periods over which the ADX is calculated. This value can be adjusted by the user to suit different trading styles and timeframes.
- Moving Average Method : Choose between several smoothing methods, including Simple Moving Average (SMA), Exponential Moving Average (EMA), Wilder's Moving Average, Weighted Moving Average (WMA), Hull Moving Average (HMA), or a Super Smooth Moving Average.
- Directional Indicators : The script calculates the +DI and -DI, which represent the positive and negative directional indicators respectively. These are then used to calculate the ADX.
- ADXR : The ADXR is calculated as the average of the current ADX value and the ADX value from 14 periods ago, providing a more smoothed representation of the trend strength.
How Traders Use ADX and ADXR:
- ADX : A rising ADX indicates an increasing trend strength, while a falling ADX suggests a weakening trend. A value above 25 is often considered an indication of a strong trend.
- ADXR : This indicator smooths the ADX over time, helping traders identify persistent trends. The ADXR can help filter out noise and provide a clearer picture of the trend's health.
Please note that this script and its indicators are designed to be used as tools for analysis, not as guarantees of market outcomes. Adjustments to the moving average method or ADX length can change the behavior of the indicators based on market conditions.
Onky's DikFat Supreme Supply and Demand
Onky's DikFat Supreme Supply and Demand (DFAT S&D)
This indicator identifies and marks potential Demand and Supply zones based on sharp price movements and volume spikes. It is designed to assist traders in recognizing areas where price could potentially reverse or move impulsively, based on the concept of supply and demand.
Key Features:
- Dynamic Demand and Supply Zones : The indicator uses historical price data and sharp price movements to detect areas where demand or supply may be concentrated. The zones are drawn as boxes on the chart for visual reference.
- Volume Spike Detection : The zones are only marked when a volume spike occurs, indicating increased market activity and potentially stronger support or resistance at those levels.
- Adjustable Parameters : Traders can adjust the Zone Size to control the lookback period for detecting supply and demand zones, and can fine-tune the Volume Multiplier to control the sensitivity of volume spikes.
- Alerts : Alerts are available for both Demand and Supply zones when they are detected, allowing traders to be notified when price enters or reacts to these areas.
How Traders Use Supply and Demand Zones:
Supply and Demand Theory suggests that prices often move in response to the balance between the amount of supply (selling pressure) and demand (buying pressure) at specific price levels. When demand exceeds supply, prices tend to rise, and when supply exceeds demand, prices tend to fall.
1. Demand Zones : These are areas where price has previously fallen to a low point and buyers have stepped in, pushing prices higher. Traders may view these zones as potential areas for price to reverse upward again.
2. Supply Zones : These are areas where price has risen to a high point and sellers have stepped in, pushing prices lower. Traders may see these zones as potential areas for price to reverse downward again.
Traders use these zones to identify potential entry points (for buying in demand zones or selling in supply zones) and exit points (if price reaches these zones in the future). The volume spike further validates the strength of these zones, as it indicates heightened market interest at those levels.
This indicator offers a flexible, visual way to identify and act upon these market dynamics. It is neutral and does not guarantee any specific outcomes, but it may assist traders in recognizing important price levels where price action could change.
Disclaimer:
This indicator is provided for informational purposes only. It is not intended to be trading advice or a recommendation to buy or sell any financial instruments. Trading involves risk, and the use of this tool does not guarantee any specific results or profits. Past performance is not indicative of future results. Users are responsible for their own decisions and should seek independent financial advice before making any investment decisions.
Gap Symbolized on ChartIndicator Description: Gap Analysis with Text Symbols
This indicator analyzes the relationship between the current candle's open price, the previous candle's close price, and the current candle's close price to provide visual insights into price gaps and momentum. It displays text symbols (▼, ▲, ━) above each candle, color-coded to reflect the strength and direction of the gap.
Key Features:
Gap Analysis:
Compares the current candle's open price with the previous candle's close price.
Evaluates the current candle's close price relative to its open price.
Text Symbols:
▼ (Down Arrow): Indicates a bearish movement.
▲ (Up Arrow): Indicates a bullish movement.
━ (Dash): Indicates a neutral or sideways movement.
Color Coding:
Red: Bearish conditions (e.g., price opening lower than the previous close and closing lower than the open).
Orange: Mild bearish or bullish conditions.
Blue: Bullish conditions (e.g., price opening higher than the previous close and closing higher than the open).
Navy: Strong bullish conditions.
Transparent Background:
The text symbols are displayed without any background shape, ensuring they do not obstruct the chart.
Use Cases:
Identify Gaps: Quickly spot gaps between the previous close and the current open.
Momentum Analysis: Assess the strength and direction of price movements.
Visual Clarity: The minimalist design (text symbols only) keeps the chart clean and easy to interpret.
How to Use:
Add the indicator to your chart.
Observe the text symbols above each candle:
Red ▼: Strong bearish momentum.
Blue ▲: Strong bullish momentum.
━: Neutral or consolidation phase.
Use the insights to confirm trends, spot reversals, or identify potential entry/exit points.
Multi Stochastic AlertHello Everyone,
I have created a Multi Stochastic Alert based on Scalping Strategy
The Strategy uses below 4 Stochastic indicator:
1. Stochastic (9,3)
2. Stochastic (14,3)
3. Stochastic (40,4)
4. Stochastic (60,10)
Trade entry become active when all of these goes below 20 or above 80, In this indicator you don't need to use all 4, this will show red and green background whenever all of them goes below 20 or above 80.
As shown in picture below, it works better when script is making a channel, Our indicator shows green or red signal, we wait for RSI Divergence and we enter. We book when blue line (9,3) goes above 80, as shown by arrow, and trail rest at breakeven or your own trailing method
Same Situation shown for Short side. We book 50% when Blue line (9,3) Goes below 20 and trail rest at breakeven or your own trailing method
Happy trading, Let me know if any improvements required.
Donchian Reversal Scanner by Hitesh2603How It Works:
Bearish Side Logic:
If the price is falling with bearish candles and touching the lower Donchian Channel, the bearishCondition flag is set to true.
When a bullish candle appears afterward, the flag is reset, and the bullishReversalSquare condition becomes true.
Bullish Side Logic:
If the price is rising with bullish candles and touching the upper Donchian Channel, the bullishCondition flag is set to true.
When a bearish candle appears afterward, the flag is reset, and the bearishReversalSquare condition becomes true.
Plotting Squares:
A green square is plotted below the candle when bullishReversalSquare is true.
A red square is plotted above the candle when bearishReversalSquare is true.
Scanner Output:
The scanCondition variable is true when either bullishReversalSquare or bearishReversalSquare is true.
How to Use the Script:
On the Chart:
Add the script to your chart.
You will see squares plotted on the chart when the conditions are met:
Green squares below the candle for bullish reversals.
Red squares above the candle for bearish reversals.
In the Scanner:
Open the Scanner tab in TradingView.
Click on "Create New Scanner".
In the "Condition" field, select the script you just created.
Choose the market or watchlist you want to scan (e.g., "NYSE", "NASDAQ", or a custom watchlist).
Run the scan. The Scanner will return a list of instruments where the scanCondition is true.
Why This Works:
The scanCondition variable is now properly declared and used.
The plotchar function explicitly outputs the scanCondition variable as a plot, which the Scanner can recognize.
Price Imbalance as Consecutive Levels of AveragesOverview
The Price Imbalance as Consecutive Levels of Averages indicator is an advanced technical analysis tool designed to identify and visualize price imbalances in financial markets. Unlike traditional moving average (MA) indicators that update continuously with each new price bar, this indicator employs moving averages calculated over consecutive, non-overlapping historical windows. This unique approach leverages comparative historical data to provide deeper insights into trend strength and potential reversals, offering traders a more nuanced understanding of market dynamics and reducing the likelihood of false signals or fakeouts.
Key Features
Consecutive Rolling Moving Averages: Utilizes three distinct simple moving averages (SMAs) calculated over consecutive, non-overlapping windows to capture different historical segments of price data.
Dynamic Color-Coded Visualization: SMA lines change color and style based on the relationship between the averages, highlighting both extreme and normal market conditions.
Median and Secondary Median Lines: Provides additional layers of price distribution insight during normal trend conditions through the plotting of primary and secondary median lines.
Fakeout Prevention: Filters out short-term volatility and sharp price movements by requiring consistent historical alignment of multiple moving averages.
Customizable Parameters: Offers flexibility to adjust SMA window lengths and line extensions to align with various trading strategies and timeframes.
Real-Time Updates with Historical Context: Continuously recalculates and updates SMA lines based on comparative historical windows, ensuring that the indicator reflects both current and past market conditions.
Inputs & Settings
Rolling Window Lengths:
Window 1 Length (Most Recent) Bars: Number of bars used to calculate the most recent SMA. (Default: 5, Range: 2–300)
Window 2 Length (Preceding) Bars: Number of bars for the second SMA, shifted by Window 1. (Default: 8, Range: 2–300)
Window 3 Length (Third Rolling) Bars: Number of bars for the third SMA, shifted by the combined lengths of Window 1 and Window 2. (Default: 13, Range: 2–300)
Horizontal Line Extension:
Horizontal Line Extension (Bars): Determines how far each SMA line extends horizontally on the chart. (Default: 10 bars, Range: 1–100)
Functionality and Theory
1. Calculating Consecutive Simple Moving Averages (SMAs):
The indicator calculates three SMAs, each based on distinct and consecutive historical windows of price data. This approach contrasts with traditional MAs that continuously update with each new price bar, offering a static view of past trends rather than an ongoing one.
Mean1 (SMA1): Calculated over the most recent Window 1 Length bars. Represents the short-term trend.
Mean1=∑i=1N1CloseiN1
Mean1=N1∑i=1N1Closei
Where N1N1 is the length of Window 1.
Mean2 (SMA2): Calculated over the preceding Window 2 Length bars, shifted back by Window 1 Length bars. Represents the medium-term trend.
\text{Mean2} = \frac{\sum_{i=1}^{N_2} \text{Close}_{i + N_1}}}{N_2}
Where N2N2 is the length of Window 2.
Mean3 (SMA3): Calculated over the third rolling Window 3 Length bars, shifted back by the combined lengths of Window 1 and Window 2 bars. Represents the long-term trend.
\text{Mean3} = \frac{\sum_{i=1}^{N_3} \text{Close}_{i + N_1 + N_2}}}{N_3}
Where N3N3 is the length of Window 3.
2. Determining Market Conditions:
The relationship between the three SMAs categorizes the market condition into either extreme or normal states, enabling traders to quickly assess trend strength and potential reversals.
Extreme Bullish:
Mean3Mean2>Mean1
Mean3>Mean2>Mean1
Indicates a strong and sustained downward trend. SMA lines are colored purple and styled as dashed lines.
Normal Bullish:
Mean1>Mean2andnot in extreme bullish condition
Mean1>Mean2andnot in extreme bullish condition
Indicates a standard upward trend. SMA lines are colored green and styled as solid lines.
Normal Bearish:
Mean1Mean2>Mean1
Mean3>Mean2>Mean1
Normal Bullish:
Mean1>Mean2andnot in Extreme Bullish
Mean1>Mean2andnot in Extreme Bullish
Normal Bearish:
Mean1 Mean2 > Mean3
Visualization: All three SMAs are displayed as gold dashed lines.
Median Lines: Not displayed to maintain chart clarity.
Interpretation: Indicates a strong and sustained upward trend. Traders may consider entering long positions, confident in the trend's strength without the distraction of additional lines.
2. Normal Bullish Condition:
SMAs Alignment: Mean1 > Mean2 (not in extreme condition)
Visualization: Mean1 and Mean2 are green solid lines; Mean3 is gray.
Median Lines: A thin blue dotted median line is plotted between Mean1 and Mean2, with two additional thin blue dashed lines as secondary medians.
Interpretation: Confirms an upward trend while providing deeper insights into price distribution. Traders can use the median and secondary median lines to identify optimal entry points and manage risk more effectively.
3. Extreme Bearish Condition:
SMAs Alignment: Mean3 > Mean2 > Mean1
Visualization: All three SMAs are displayed as purple dashed lines.
Median Lines: Not displayed to maintain chart clarity.
Interpretation: Indicates a strong and sustained downward trend. Traders may consider entering short positions, confident in the trend's strength without the distraction of additional lines.
4. Normal Bearish Condition:
SMAs Alignment: Mean1 < Mean2 (not in extreme condition)
Visualization: Mean1 and Mean2 are red solid lines; Mean3 is gray.
Median Lines: A thin blue dotted median line is plotted between Mean1 and Mean2, with two additional thin blue dashed lines as secondary medians.
Interpretation: Confirms a downward trend while providing deeper insights into price distribution. Traders can use the median and secondary median lines to identify optimal entry points and manage risk more effectively.
Customization and Flexibility
The Price Imbalance as Consecutive Levels of Averages indicator is highly adaptable, allowing traders to tailor it to their specific trading styles and market conditions through adjustable parameters:
SMA Window Lengths: Modify the lengths of Window 1, Window 2, and Window 3 to capture different historical trend segments, whether focusing on short-term fluctuations or long-term movements.
Line Extension: Adjust the horizontal extension of SMA and median lines to align with different trading horizons and chart preferences.
Color and Style Preferences: While default colors and styles are optimized for clarity, traders can customize these elements to match their personal chart aesthetics and enhance visual differentiation.
This flexibility ensures that the indicator remains versatile and applicable across various markets, asset classes, and trading strategies, providing valuable insights tailored to individual trading needs.
Conclusion
The Price Imbalance as Consecutive Levels of Averages indicator offers a comprehensive and innovative approach to analyzing price trends and imbalances within financial markets. By utilizing three consecutive, non-overlapping SMAs and incorporating median lines during normal trend conditions, the indicator provides clear and actionable insights into trend strength and price distribution. Its unique design leverages comparative historical data, distinguishing it from traditional moving averages and enhancing its utility in identifying genuine market movements while minimizing false signals. This dynamic and customizable tool empowers traders to refine their technical analysis, optimize their trading strategies, and navigate the markets with greater confidence and precision.
Failed 2D & Failed 2U BarsI created this indicator to plot a triangle when a candle is either 1) a failed 2 down--the candle breaks the low of the prior candle but closes green (or higher than its opening price) and doesn't break the high of the previous candle; and 2) a failed 2 up--high of the prior candle is broken but the bar is red and does not break the low of the prior candle.
It has alerts which you can set up in the alert system.
I think that this candle is one of the most telling and powerful when it comes to candle analysis.
R.I.P. Rob Smith, Creator of The Strat.