Momentum Linear RegressionThe original script was posted on ProRealCode by user Nicolas.
This is an indicator made of the linear regression applied to the rate of change of price (or momentum). I made a simple signal line just by duplicating the first one within a period decay in the past, to make those 2 lines cross. You can add more periods decay to made signal smoother with less false entry.
Komut dosyalarını "entry" için ara
Bilateral Filter For Loop [BackQuant]Bilateral Filter For Loop
The Bilateral Filter For Loop is an advanced technical indicator designed to filter out market noise and smooth out price data, thus improving the identification of underlying market trends. It employs a bilateral filter, which is a sophisticated non-linear filter commonly used in image processing and price time series analysis. By considering both spatial and range differences between price points, this filter is highly effective at preserving significant trends while reducing random fluctuations, ultimately making it suitable for dynamic trend-following strategies.
Please take the time to read the following:
Key Features
1. Bilateral Filter Calculation:
The bilateral filter is the core of this indicator and works by applying a weight to each data point based on two factors: spatial distance and price range difference. This dual weighting process allows the filter to preserve important price movements while reducing the impact of less relevant fluctuations. The filter uses two primary parameters:
Spatial Sigma (σ_d): This parameter adjusts the weight applied based on the distance of each price point from the current price. A larger spatial sigma means more smoothing, as further away values will contribute more heavily to the result.
Range Sigma (σ_r): This parameter controls how much weight is applied based on the difference in price values. Larger price differences result in smaller weights, while similar price values result in larger weights, thereby preserving the trend while filtering out noise.
The output of this filter is a smoothed version of the original price series, which eliminates short-term fluctuations, helping traders focus on longer-term trends. The bilateral filter is applied over a rolling window, adjusting the level of smoothing dynamically based on both the distance between values and their relative price movements.
2. For Loop Calculation for Trend Scoring:
A for-loop is used to calculate the trend score based on the filtered price data. The loop compares the current value to previous values within the specified window, scoring the trend as follows:
+1 for upward movement (when the filtered value is greater than the previous value).
-1 for downward movement (when the filtered value is less than the previous value).
The cumulative result of this loop gives a continuous trend score, which serves as a directional indicator for the market's momentum. By summing the scores over the window period, the loop provides an aggregate value that reflects the overall trend strength. This score helps determine whether the market is experiencing a strong uptrend, downtrend, or sideways movement.
3. Long and Short Conditions:
Once the trend score has been calculated, it is compared against predefined threshold levels:
A long signal is generated when the trend score exceeds the upper threshold, indicating that the market is in a strong uptrend.
A short signal is generated when the trend score crosses below the lower threshold, signaling a potential downtrend or trend reversal.
These conditions provide clear signals for potential entry points, and the color-coding helps traders quickly identify market direction:
Long signals are displayed in green.
Short signals are displayed in red.
These signals are designed to provide high-confidence entries for trend-following strategies, helping traders capture profitable movements in the market.
4. Trend Background and Bar Coloring:
The script offers customizable visual settings to enhance the clarity of the trend signals. Traders can choose to:
Color the bars based on the trend direction: Bars are colored green for long signals and red for short signals.
Change the background color to provide additional context: The background will be shaded green for a bullish trend and red for a bearish trend. This visual feedback helps traders to stay aligned with the prevailing market sentiment.
These features offer a quick visual reference for understanding the market's direction, making it easier for traders to identify when to enter or exit positions.
5. Threshold Lines for Visual Feedback:
Threshold lines are plotted on the chart to represent the predefined long and short levels. These lines act as clear markers for when the market reaches a critical threshold, triggering a potential buy (long) or sell (short) signal. By showing these threshold lines on the chart, traders can quickly gauge the strength of the market and assess whether the trend is strong enough to warrant action.
These thresholds can be adjusted based on the trader's preferences, allowing them to fine-tune the indicator for different market conditions or asset behaviors.
6. Customizable Parameters for Flexibility:
The indicator offers several parameters that can be adjusted to suit individual trading preferences:
Window Period (Bilateral Filter): The window size determines how many past price values are used to calculate the bilateral filter. A larger window increases smoothing, while a smaller window results in more responsive, but noisier, data.
Spatial Sigma (σ_d) and Range Sigma (σ_r): These values control how sensitive the filter is to price changes and the distance between data points. Fine-tuning these parameters allows traders to adjust the degree of noise reduction applied to the price series.
Threshold Levels: The upper and lower thresholds determine when the trend score crosses into long or short territory. These levels can be customized to better match the trader's risk tolerance or asset characteristics.
Visual Settings: Traders can customize the appearance of the chart, including the line width of trend signals, bar colors, and background shading, to make the indicator more readable and aligned with their charting style.
7. Alerts for Trend Reversals:
The indicator includes alert conditions for real-time notifications when the market crosses the defined thresholds. Traders can set alerts to be notified when:
The trend score crosses the long threshold, signaling an uptrend.
The trend score crosses the short threshold, signaling a downtrend.
These alerts provide timely information, allowing traders to take immediate action when the market shows a significant change in direction.
Final Thoughts
The Bilateral Filter For Loop indicator is a robust tool for trend-following traders who wish to reduce market noise and focus on the underlying trend. By applying the bilateral filter and calculating trend scores, this indicator helps traders identify strong uptrends and downtrends, providing reliable entry signals with minimal market noise. The customizable parameters, visual feedback, and alerting system make it a versatile tool for traders seeking to improve their timing and capture profitable market movements.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
INDEX:BTCUSD
INDEX:ETHUSD
CRYPTO:SOLUSD
GER40 BIAS Forecast [ML-Based]🎯 Purpose:
This indicator provides a daily directional bias (LONG / SHORT / FLAT) for the German DAX40 index (GER40) using a statistically optimized scoring model, developed with 6 years of historical data and verified through machine learning analysis.
🧠 How the Score Works (ML-derived):
Each trading day receives a bias score (0–3) for both long and short setups, based on these 3 factors from the daily candle:
Condition Long Score Logic Short Score Logic
1. Candle Direction Close > Open → +1 Close < Open → +1
2. VWAP Slope VWAP > VWAP → +1 VWAP < VWAP → +1
3. Volatility Strength Range > SMA(20) → +1 Close < Yesterday's Low → +1 (Rejection)
➡️ A score of 2 or more triggers a Long or Short Bias for the day.
These scoring rules are derived from a machine learning model trained on 6 years of DAX data, identifying the most predictive features for directional follow-through.
📘 Bias Interpretation:
Score Result Daily Bias Background Color
Long Score ≥ 2 LONG Green
Short Score ≥ 2 SHORT Red
Both < 2 FLAT Gray
📍 Indicator Features:
🎨 Background coloring to visualize daily bias directly on intraday charts
🔢 Optional score labels (e.g. “Long: 2 | Short: 1”) per calendar day
📈 VWAP line plotted for additional intraday context
❌ Entry signals removed – this version focuses solely on forecasting directional bias
💡 Use Case:
Morning planning aid
Filtering for high-probability intraday setups
Combining with session-based entry systems
Volume Point of Control with Fib Based Profile🍀Description:
This indicator is a comprehensive volume profile analysis tool designed to identify key price levels based on trading activity within user-defined timeframes. It plots the Point of Control (POC), Value Area High (VAH), and Value Area Low (VAL), along with dynamically calculated Fibonacci levels derived from the developing period's range. It offers extensive customization for both historical and developing levels.
🍀Core Features:
Volume Profiling (POC, VAH, VAL):
Calculates and plots the POC (price level with the highest volume), VAH, and VAL for a selected timeframe (e.g., Daily, Weekly).
The Value Area percentage is configurable. 70% is common on normal volume profiles, but this script allows you to configure multiple % levels via the fib levels. I recommend using 2 versions of this indicator on a chart, one has Value Area at 1 (100% - high and low of lookback) and the second is a specified VA area (i.e. 70%) like in the chart snapshot above. See examples at the bottom.
Historical Levels:
Plots POC, VAH, and VAL from previous completed periods.
Optionally displays only "Unbroken" levels – historical levels that price has not yet revisited, which can act as stronger magnets or resistance/support.
The user can manage the number of historical lines displayed to prevent chart clutter.
Developing Levels:
Shows the POC, VAH, and VAL as they form in real-time during the current, incomplete period. This provides insight into intraday/intra-period value migration.
Dynamic Fibonacci Levels:
Calculates and plots Fibonacci retracement/extension levels based dynamically on the range between the developing POC and the developing VAH/VAL.
Offers 8 configurable % levels above and below POC that can be toggled on/off.
Visual Customization:
Extensive options for colors, line styles, and widths for all plotted levels.
Optional gradient fill for the Value Area that visualizes current price distance from POC - option to invert the colors as well.
Labels for developing levels and Fibonacci levels for easy identification.
🍀Characteristics:
Volume-Driven: Levels are derived from actual trading volume, reflecting areas of high participation and price agreement/disagreement.
Timeframe Specific: The results are entirely dependent on the chosen profile timeframe.
Dynamic & Static Elements: Developing levels and Fibs update live, while historical levels remain fixed once their period closes.
Lagging (Historical) & Potentially Leading: Historical levels are based on the past, but are often respected by future price action. Developing levels show current dynamics.
🍀How to Use It:
Identifying Support & Resistance: Historical and developing POCs, VAHs, and VALs are often key areas where price may react. Unbroken levels are particularly noteworthy.
Market Context & Sentiment: Trading above the POC suggests bullish strength/acceptance of higher prices, while trading below suggests bearishness/acceptance of lower prices.
Entry/Exit Zones: Interactions with these levels (rejections, breakouts, tests) can provide potential entry or exit signals, especially when confirming with other analysis methods.
Dynamic Targets: The Fibonacci levels calculated from the developing POC-VA range offer potential intraday/intra-period price targets or areas of interest.
Understanding Value Migration: Observing the movement of the developing POC/VAH/VAL throughout the period reveals where value is currently being established.
🍀Potential Drawbacks:
Input Sensitivity: The choice of timeframe, Value Area percentage, and volume resolution heavily influences the generated levels. Experimentation is needed for optimal settings per instrument/market. (I've found that Range Charts can provide very accurate volume levels on TV since the time element is removed. This helps to refine the accuracy of price levels with high volume.)
Volume Data Dependency: Requires accurate volume data. May be less reliable on instruments with sparse or questionable volume reporting.
Chart Clutter: Enabling all features simultaneously can make the chart busy. Utilize the line management inputs and toggle features as needed.
Not a Standalone Strategy: This indicator provides context and key levels. It should be used alongside other technical analysis tools and price action reading for robust decision-making.
Developing Level Fluctuation: Developing POC/VA/Fib levels can shift considerably, especially early in a new period, before settling down as more volume accumulates and time passes.
🍀Recommendations/Examples:
I recommend have this indicator on your chart twice, one has the VA set at 1 (100%) and has the fib levels plotted. The second has the VA set to 0.7 (70%) to highlight the defined VA.
Here is an example with 3 on a chart. VA of 100%, VA of 80%, and VA of 20%
GEEKSDOBYTE IFVG w/ Buy/Sell Signals1. Inputs & Configuration
Swing Lookback (swingLen)
Controls how many bars on each side are checked to mark a swing high or swing low (default = 5).
Booleans to Toggle Plotting
showSwings – Show small triangle markers at swing highs/lows
showFVG – Show Fair Value Gap zones
showSignals – Show “BUY”/“SELL” labels when price inverts an FVG
showDDLine – Show a yellow “DD” line at the close of the inversion bar
showCE – Show an orange dashed “CE” line at the midpoint of the gap area
2. Swing High / Low Detection
isSwingHigh = ta.pivothigh(high, swingLen, swingLen)
Marks a bar as a swing high if its high is higher than the highs of the previous swingLen bars and the next swingLen bars.
isSwingLow = ta.pivotlow(low, swingLen, swingLen)
Marks a bar as a swing low if its low is lower than the lows of the previous and next swingLen bars.
Plotting
If showSwings is true, small red downward triangles appear above swing highs, and green upward triangles below swing lows.
3. Fair Value Gap (3‐Bar) Identification
A Fair Value Gap (FVG) is defined here using a simple three‐bar logic (sometimes called an “inefficiency” in price):
Bullish FVG (bullFVG)
Checks if, two bars ago, the low of that bar (low ) is strictly greater than the current bar’s high (high).
In other words:
bullFVG = low > high
Bearish FVG (bearFVG)
Checks if, two bars ago, the high of that bar (high ) is strictly less than the current bar’s low (low).
In other words:
bearFVG = high < low
When either condition is true, it identifies a three‐bar “gap” or unfilled imbalance in the market.
4. Drawing FVG Zones
If showFVG is enabled, each time a bullish or bearish FVG is detected:
Bullish FVG Zone
Draws a semi‐transparent green box from the bar two bars ago (where the gap began) at low up to the current bar’s high.
Bearish FVG Zone
Draws a semi‐transparent red box from the bar two bars ago at high down to the current bar’s low.
These colored boxes visually highlight the “fair value imbalance” area on the chart.
5. Inversion (Fill) Detection & Entry Signals
An inversion is defined as the price “closing through” that previously drawn FVG:
Bullish Inversion (bullInversion)
Occurs when a bullish FVG was identified on bar-2 (bullFVG), and on the current bar the close is greater than that old bar-2 low:
bullInversion = bullFVG and close > low
Bearish Inversion (bearInversion)
Occurs when a bearish FVG was identified on bar-2 (bearFVG), and on the current bar the close is lower than that old bar-2 high:
bearInversion = bearFVG and close < high
When an inversion is true, the indicator optionally draws two lines and a label (depending on input toggles):
Draw “DD” Line (yellow, solid)
Plots a horizontal yellow line from the current bar’s close price extending five bars forward (bar_index + 5). This is often referred to as a “Demand/Daily Demand” line, marking where price inverted the gap.
Draw “CE” Line (orange, dashed)
Calculates the midpoint (ce) of the original FVG zone.
For a bullish inversion:
ce = (low + high) / 2
For a bearish inversion:
ce = (high + low) / 2
Plots a horizontal dashed orange line at that midpoint for five bars forward.
Plot Label (“BUY” / “SELL”)
If showSignals is true, a green “BUY” label is placed at the low of the current bar when a bullish inversion occurs.
Likewise, a red “SELL” label at the high of the current bar when a bearish inversion happens.
6. Putting It All Together
Swing Markers (Optional):
Visually confirm recent swing highs and swing lows with small triangles.
FVG Zones (Optional):
Highlight areas where price left a 3-bar gap (bullish in green, bearish in red).
Inversion Confirmation:
Wait for price to close beyond the old FVG boundary.
Once that happens, draw the yellow “DD” line at the close, the orange dashed “CE” line at the zone’s midpoint, and place a “BUY” or “SELL” label exactly on that bar.
User Controls:
All of the above elements can be individually toggled on/off (showSwings, showFVG, showSignals, showDDLine, showCE).
In Practice
A bullish FVG forms whenever a strong drop leaves a gap in liquidity (three bars ago low > current high).
When price later “fills” that gap by closing above the old low, the script signals a potential long entry (BUY), draws a demand line at the closing price, and marks the midpoint of that gap.
Conversely, a bearish FVG marks a potential short zone (three bars ago high < current low). When price closes below that gap’s high, it signals a SELL, with similar lines drawn.
By combining these elements, the indicator helps users visually identify inefficiencies (FVGs), confirm when price inverts/fills them, and place straightforward buy/sell labels alongside reference lines for trade management.
Levels Of Interest------------------------------------------------------------------------------------
LEVELS OF INTEREST (LOI)
TRADING INDICATOR GUIDE
------------------------------------------------------------------------------------
Table of Contents:
1. Indicator Overview & Core Functionality
2. VWAP Foundation & Historical Context
3. Multi-Timeframe VWAP Analysis
4. Moving Average Integration System
5. Trend Direction Signal Detection
6. Visual Design & Display Features
7. Custom Level Integration
8. Repaint Protection Technology
9. Practical Trading Applications
10. Setup & Configuration Recommendations
------------------------------------------------------------------------------------
1. INDICATOR OVERVIEW & CORE FUNCTIONALITY
------------------------------------------------------------------------------------
The LOI indicator combines multiple VWAP calculations with moving averages across different timeframes. It's designed to show where institutional money is flowing and help identify key support and resistance levels that actually matter in today's markets.
Primary Functions:
- Multi-timeframe VWAP analysis (Daily, Weekly, Monthly, Yearly)
- Advanced moving average integration (EMA, SMA, HMA)
- Real-time trend direction detection
- Institutional flow analysis
- Dynamic support/resistance identification
Target Users: Day traders, swing traders, position traders, and institutional analysts seeking comprehensive market structure analysis.
------------------------------------------------------------------------------------
2. VWAP FOUNDATION & HISTORICAL CONTEXT
------------------------------------------------------------------------------------
Historical Development: VWAP started in the 1980s when big institutional traders needed a way to measure if they were getting good fills on their massive orders. Unlike regular price averages, VWAP weighs each price by the volume traded at that level. This makes it incredibly useful because it shows you where most of the real money changed hands.
Mathematical Foundation: The basic math is simple: you take each price, multiply it by the volume at that price, add them all up, then divide by total volume. What you get is the true "average" price that reflects actual trading activity, not just random price movements.
Formula: VWAP = Σ(Price × Volume) / Σ(Volume)
Where typical price = (High + Low + Close) / 3
Institutional Behavior Patterns:
- When price trades above VWAP, institutions often look to sell
- When it's below, they're usually buying
- Creates natural support and resistance that you can actually trade against
- Serves as benchmark for execution quality assessment
------------------------------------------------------------------------------------
3. MULTI-TIMEFRAME VWAP ANALYSIS
------------------------------------------------------------------------------------
Core Innovation: Here's where LOI gets interesting. Instead of just showing daily VWAP like most indicators, it displays four different timeframes simultaneously:
**Daily VWAP Implementation**:
- Resets every morning at market open
- Provides clearest picture of intraday institutional sentiment
- Primary tool for day trading strategies
- Most responsive to immediate market conditions
**Weekly VWAP System**:
- Resets each Monday (or first trading day)
- Smooths out daily noise and volatility
- Perfect for swing trades lasting several days to weeks
- Captures weekly institutional positioning
**Monthly VWAP Analysis**:
- Resets at beginning of each calendar month
- Captures bigger institutional rebalancing at month-end
- Fund managers often operate on monthly mandates
- Significant weight in intermediate-term analysis
**Yearly VWAP Perspective**:
- Resets annually for full-year institutional view
- Shows long-term institutional positioning
- Where pension funds and sovereign wealth funds operate
- Critical for major trend identification
Confluence Zone Theory: The magic happens when multiple VWAP levels cluster together. These confluence zones often become major turning points because different types of institutional money all see value at the same price.
------------------------------------------------------------------------------------
4. MOVING AVERAGE INTEGRATION SYSTEM
------------------------------------------------------------------------------------
Multi-Type Implementation: The indicator includes three types of moving averages, each with its own personality and application:
**Exponential Moving Averages (EMAs)**:
- React quickly to recent price changes
- Displayed as solid lines for easy identification
- Optimal performance in trending market conditions
- Higher sensitivity to current price action
**Simple Moving Averages (SMAs)**:
- Treat all historical data points equally
- Appear as dashed lines in visual display
- Slower response but more reliable in choppy conditions
- Traditional approach favored by institutional traders
**Hull Moving Averages (HMAs)**:
- Newest addition to the system (dotted line display)
- Created by Alan Hull in 2005
- Solves classic moving average dilemma: speed vs. accuracy
- Manages to be both responsive and smooth simultaneously
Technical Innovation: Alan Hull's solution addresses the fundamental problem where moving averages are either too slow (missing moves) or too fast (generating false signals). HMAs achieve optimal balance through weighted calculation methodology.
Period Configuration:
- 5-period: Short-term momentum assessment
- 50-period: Intermediate trend identification
- 200-period: Long-term directional confirmation
------------------------------------------------------------------------------------
5. TREND DIRECTION SIGNAL DETECTION
------------------------------------------------------------------------------------
Real-Time Momentum Analysis: One of LOI's best features is its real-time trend detection system. Next to each moving average, visual symbols provide immediate trend assessment:
Symbol System:
- ▲ Rising average (bullish momentum confirmation)
- ▼ Falling average (bearish momentum indication)
- ► Flat average (consolidation or indecision period)
Update Frequency: These signals update in real-time with each new price tick and function across all configured timeframes. Traders can quickly scan daily and weekly trends to assess alignment or conflicting signals.
Multi-Timeframe Trend Analysis:
- Simultaneous daily and weekly trend comparison
- Immediate identification of trend alignment
- Early warning system for potential reversals
- Momentum confirmation for entry decisions
------------------------------------------------------------------------------------
6. VISUAL DESIGN & DISPLAY FEATURES
------------------------------------------------------------------------------------
Color Psychology Framework: The color scheme isn't random but based on psychological associations and trading conventions:
- **Blue Tones**: Institutional neutrality (VWAP levels)
- **Green Spectrum**: Growth and stability (weekly timeframes)
- **Purple Range**: Longer-term sophistication (monthly analysis)
- **Orange Hues**: Importance and attention (yearly perspective)
- **Red Tones**: User-defined significance (custom levels)
Adaptive Display Technology: The indicator automatically adjusts decimal places based on the instrument you're trading. High-priced stocks show 2 decimals, while penny stocks might show 8. This keeps the display incredibly clean regardless of what you're analyzing - no cluttered charts or overwhelming information overload.
Smart Labeling System: Advanced positioning algorithm automatically spaces all elements to prevent overlap, even during extreme zoom levels or multiple timeframe analysis. Every level stays clearly readable without any visual chaos disrupting your analysis.
------------------------------------------------------------------------------------
7. CUSTOM LEVEL INTEGRATION
------------------------------------------------------------------------------------
User-Defined Level System: Beyond the calculated VWAP and moving average levels, traders can add custom horizontal lines at any price point for personalized analysis.
Strategic Applications:
- **Psychological Levels**: Round numbers, previous significant highs/lows
- **Technical Levels**: Fibonacci retracements, pivot points
- **Fundamental Targets**: Analyst price targets, earnings estimates
- **Risk Management**: Stop-loss and take-profit zones
Integration Features:
- Seamless incorporation with smart labeling system
- Custom color selection for visual organization
- Extension capabilities across all chart timeframes
- Maintains display clarity with existing indicators
------------------------------------------------------------------------------------
8. REPAINT PROTECTION TECHNOLOGY
------------------------------------------------------------------------------------
Critical Trading Feature: This addresses one of the most significant issues in live trading applications. Most multi-timeframe indicators "repaint," meaning they display different signals when viewing historical data versus real-time analysis.
Protection Benefits:
- Ensures every displayed signal could have been traded when it appeared
- Eliminates discrepancies between historical and live analysis
- Provides realistic performance expectations
- Maintains signal integrity across chart refreshes
Configuration Options:
- **Protection Enabled**: Default setting for live trading
- **Protection Disabled**: Available for backtesting analysis
- User-selectable toggle based on analysis requirements
- Applies to all multi-timeframe calculations
Implementation Note: With protection enabled, signals may appear one bar later than without protection, but this ensures all signals represent actionable opportunities that could have been executed in real-time market conditions.
------------------------------------------------------------------------------------
9. PRACTICAL TRADING APPLICATIONS
------------------------------------------------------------------------------------
**Day Trading Strategy**:
Focus on daily VWAP with 5-period moving averages. Look for bounces off VWAP or breaks through it with volume. Short-term momentum signals provide entry and exit timing.
**Swing Trading Approach**:
Weekly VWAP becomes your primary anchor point, with 50-period averages showing intermediate trends. Position sizing based on weekly VWAP distance.
**Position Trading Method**:
Monthly and yearly VWAP provide broad market context, while 200-period averages confirm long-term directional bias. Suitable for multi-week to multi-month holdings.
**Multi-Timeframe Confluence Strategy**:
The highest-probability setups occur when daily, weekly, and monthly VWAPs cluster together, especially when multiple moving averages confirm the same direction. These represent institutional consensus zones.
Risk Management Integration:
- VWAP levels serve as dynamic stop-loss references
- Multiple timeframe confirmation reduces false signals
- Institutional flow analysis improves position sizing decisions
- Trend direction signals optimize entry and exit timing
------------------------------------------------------------------------------------
10. SETUP & CONFIGURATION RECOMMENDATIONS
------------------------------------------------------------------------------------
Initial Configuration: Start with default settings and adjust based on individual trading style and market focus. Short-term traders should emphasize daily and weekly timeframes, while longer-term investors benefit from monthly and yearly level analysis.
Transparency Optimization: The transparency settings allow clear price action visibility while maintaining level reference points. Most traders find 70-80% transparency optimal - it provides a clean, unobstructed view of price movement while maintaining all critical reference levels needed for analysis.
Integration Strategy: Remember that no indicator functions effectively in isolation. LOI provides excellent context for institutional flow and trend direction analysis, but should be combined with complementary analysis tools for optimal results.
Performance Considerations:
- Multiple timeframe calculations may impact chart loading speed
- Adjust displayed timeframes based on trading frequency
- Customize color schemes for different market sessions
- Regular review and adjustment of custom levels
------------------------------------------------------------------------------------
FINAL ANALYSIS
------------------------------------------------------------------------------------
Competitive Advantage: What makes LOI different is its focus on where real money actually trades. By combining volume-weighted calculations with multiple timeframes and trend detection, it cuts through market noise to show you what institutions are really doing.
Key Success Factor: Understanding that different timeframes serve different purposes is essential. Use them together to build a complete picture of market structure, then execute trades accordingly.
The integration of institutional flow analysis with technical trend detection creates a comprehensive trading tool that addresses both short-term tactical decisions and longer-term strategic positioning.
------------------------------------------------------------------------------------
END OF DOCUMENTATION
------------------------------------------------------------------------------------
HoLo (Highest Open Lowest Open)HoLo (Highest Open Lowest Open) Method
Overview
HoLo stands for "Highest Open Lowest Open" – a forex trading strategy.
Core Concept
Definition of HoLo:
Highest Open (HO): The highest opening price among all H1 candles of the current trading day
Lowest Open (LO): The lowest opening price among all H1 candles of the current trading day
Trading Day: Starts at Asia Open Session
Strategy Setup
Step 1: Mark Key Levels
Current day's High/Low
Highest Open and Lowest Open (from H1 candles)
Step 2: Define the Area of Interest
Sell Zone: Between the Highest Open and the current day's High
Buy Zone: Between the Lowest Open and the current day's Low
Trade Entry Rules
Sell Trade:
Price goes above the Highest Open
Trigger candle (M5, M15, or M30) closes above the Highest Open
Enter a sell when price revisits the Highest Open level (Sell Stop Order)
Buy Trade:
Price drops below the Lowest Open
Trigger candle closes below the Lowest Open
Enter a buy when price revisits the Lowest Open level (Buy Stop Order)
Trigger Timeframe:
Choose M1, M5, or M15 based on:
Your screen time availability
Personal trading style
Risk and Profit Management
Stop Loss:
For sell: Set SL at the day’s High + spread
For buy: Set SL at the day’s Low + spread
Take Profit (TP) Basic Rule:
You should open 2 positions:
When profit reaches 1R: Take partial profit + move SL to BE (Break Even)
Let the remaining position run using partial TP or trailing stop
Money Management:
Never risk more than 1% per trade
Recommended: 0.5% risk due to multiple opportunities daily
Prioritize major pairs.
The Indicator
How to read data
For Day Traders
Monitor the sell zone (red area) for potential short entries near resistance
Watch the buy zone (blue area) for potential long entries near support
Use cross signals for entry/exit points
Pay attention to timing markers for key market hours
Alert
HO (Highest Open) level changes
LO (Lowest Close) level changes
Price crossing key levels
Timing notifications
Heikin-Ashi Mean Reversion Oscillator [Alpha Extract]The Heikin-Ashi Mean Reversion Oscillator combines the smoothing characteristics of Heikin-Ashi candlesticks with mean reversion analysis to create a powerful momentum oscillator. This indicator applies Heikin-Ashi transformation twice - first to price data and then to the oscillator itself - resulting in smoother signals while maintaining sensitivity to trend changes and potential reversal points.
🔶 CALCULATION
Heikin-Ashi Transformation: Converts regular OHLC data to smoothed Heikin-Ashi values
Component Analysis: Calculates trend strength, body deviation, and price deviation from mean
Oscillator Construction: Combines components with weighted formula (40% trend strength, 30% body deviation, 30% price deviation)
Double Smoothing: Applies EMA smoothing and second Heikin-Ashi transformation to oscillator values
Signal Generation: Identifies trend changes and crossover points with overbought/oversold levels
Formula:
HA Close = (Open + High + Low + Close) / 4
HA Open = (Previous HA Open + Previous HA Close) / 2
Trend Strength = Normalized consecutive HA candle direction
Body Deviation = (HA Body - Mean Body) / Mean Body * 100
Price Deviation = ((HA Close - Price Mean) / Price Mean * 100) / Standard Deviation * 25
Raw Oscillator = (Trend Strength * 0.4) + (Body Deviation * 0.3) + (Price Deviation * 0.3)
Final Oscillator = 50 + (EMA(Raw Oscillator) / 2)
🔶 DETAILS Visual Features:
Heikin-Ashi Candlesticks: Smoothed oscillator representation using HA transformation with vibrant teal/red coloring
Overbought/Oversold Zones: Horizontal lines at customizable levels (default 70/30) with background highlighting in extreme zones
Moving Averages: Optional fast and slow EMA overlays for additional trend confirmation
Signal Dashboard: Real-time table showing current oscillator status (Overbought/Oversold/Bullish/Bearish) and buy/sell signals
Reference Lines: Middle line at 50 (neutral), with 0 and 100 boundaries for range visualization
Interpretation:
Above 70: Overbought conditions, potential selling opportunity
Below 30: Oversold conditions, potential buying opportunity
Bullish HA Candles: Green/teal candles indicate upward momentum
Bearish HA Candles: Red candles indicate downward momentum
MA Crossovers: Fast EMA above slow EMA suggests bullish momentum, below suggests bearish momentum
Zone Exits: Price moving out of extreme zones (above 70 or below 30) often signals trend continuation
🔶 EXAMPLES
Mean Reversion Signals: When the oscillator reaches extreme levels (above 70 or below 30), it identifies potential reversal points where price may revert to the mean.
Example: Oscillator reaching 80+ levels during strong uptrends often precedes short-term pullbacks, providing profit-taking opportunities.
Trend Change Detection: The double Heikin-Ashi smoothing helps identify genuine trend changes while filtering out market noise.
Example: When oscillator HA candles change from red to teal after oversold readings, this confirms potential trend reversal from bearish to bullish.
Moving Average Confirmation: Fast and slow EMA crossovers on the oscillator provide additional confirmation of momentum shifts.
Example: Fast EMA crossing above slow EMA while oscillator is rising from oversold levels provides strong bullish confirmation signal.
Dashboard Signal Integration: The real-time dashboard combines oscillator status with directional signals for quick decision-making.
Example: Dashboard showing "Oversold" status with "BUY" signal when HA candles turn bullish provides clear entry timing.
🔶 SETTINGS
Customization Options:
Calculation: Oscillator period (default 14), smoothing factor (1-50, default 2)
Levels: Overbought threshold (50-100, default 70), oversold threshold (0-50, default 30)
Moving Averages: Toggle display, fast EMA length (default 9), slow EMA length (default 21)
Visual Enhancements: Show/hide signal dashboard, customizable table position
Alert Conditions: Oversold bounce, overbought reversal, bullish/bearish MA crossovers
The Heikin-Ashi Mean Reversion Oscillator provides traders with a sophisticated momentum tool that combines the smoothing benefits of Heikin-Ashi analysis with mean reversion principles. The double transformation process creates cleaner signals while the integrated dashboard and multiple confirmation methods help traders identify high-probability entry and exit points during both trending and ranging market conditions.
Risk-Adjusted Momentum Oscillator# Risk-Adjusted Momentum Oscillator (RAMO): Momentum Analysis with Integrated Risk Assessment
## 1. Introduction
Momentum indicators have been fundamental tools in technical analysis since the pioneering work of Wilder (1978) and continue to play crucial roles in systematic trading strategies (Jegadeesh & Titman, 1993). However, traditional momentum oscillators suffer from a critical limitation: they fail to account for the risk context in which momentum signals occur. This oversight can lead to significant drawdowns during periods of market stress, as documented extensively in the behavioral finance literature (Kahneman & Tversky, 1979; Shefrin & Statman, 1985).
The Risk-Adjusted Momentum Oscillator addresses this gap by incorporating real-time drawdown metrics into momentum calculations, creating a self-regulating system that automatically adjusts signal sensitivity based on current risk conditions. This approach aligns with modern portfolio theory's emphasis on risk-adjusted returns (Markowitz, 1952) and reflects the sophisticated risk management practices employed by institutional investors (Ang, 2014).
## 2. Theoretical Foundation
### 2.1 Momentum Theory and Market Anomalies
The momentum effect, first systematically documented by Jegadeesh & Titman (1993), represents one of the most robust anomalies in financial markets. Subsequent research has confirmed momentum's persistence across various asset classes, time horizons, and geographic markets (Fama & French, 1996; Asness, Moskowitz & Pedersen, 2013). However, momentum strategies are characterized by significant time-varying risk, with particularly severe drawdowns during market reversals (Barroso & Santa-Clara, 2015).
### 2.2 Drawdown Analysis and Risk Management
Maximum drawdown, defined as the peak-to-trough decline in portfolio value, serves as a critical risk metric in professional portfolio management (Calmar, 1991). Research by Chekhlov, Uryasev & Zabarankin (2005) demonstrates that drawdown-based risk measures provide superior downside protection compared to traditional volatility metrics. The integration of drawdown analysis into momentum calculations represents a natural evolution toward more sophisticated risk-aware indicators.
### 2.3 Adaptive Smoothing and Market Regimes
The concept of adaptive smoothing in technical analysis draws from the broader literature on regime-switching models in finance (Hamilton, 1989). Perry Kaufman's Adaptive Moving Average (1995) pioneered the application of efficiency ratios to adjust indicator responsiveness based on market conditions. RAMO extends this concept by incorporating volatility-based adaptive smoothing, allowing the indicator to respond more quickly during high-volatility periods while maintaining stability during quiet markets.
## 3. Methodology
### 3.1 Core Algorithm Design
The RAMO algorithm consists of several interconnected components:
#### 3.1.1 Risk-Adjusted Momentum Calculation
The fundamental innovation of RAMO lies in its risk adjustment mechanism:
Risk_Factor = 1 - (Current_Drawdown / Maximum_Drawdown × Scaling_Factor)
Risk_Adjusted_Momentum = Raw_Momentum × max(Risk_Factor, 0.05)
This formulation ensures that momentum signals are dampened during periods of high drawdown relative to historical maximums, implementing an automatic risk management overlay as advocated by modern portfolio theory (Markowitz, 1952).
#### 3.1.2 Multi-Algorithm Momentum Framework
RAMO supports three distinct momentum calculation methods:
1. Rate of Change: Traditional percentage-based momentum (Pring, 2002)
2. Price Momentum: Absolute price differences
3. Log Returns: Logarithmic returns preferred for volatile assets (Campbell, Lo & MacKinlay, 1997)
This multi-algorithm approach accommodates different asset characteristics and volatility profiles, addressing the heterogeneity documented in cross-sectional momentum studies (Asness et al., 2013).
### 3.2 Leading Indicator Components
#### 3.2.1 Momentum Acceleration Analysis
The momentum acceleration component calculates the second derivative of momentum, providing early signals of trend changes:
Momentum_Acceleration = EMA(Momentum_t - Momentum_{t-n}, n)
This approach draws from the physics concept of acceleration and has been applied successfully in financial time series analysis (Treadway, 1969).
#### 3.2.2 Linear Regression Prediction
RAMO incorporates linear regression-based prediction to project momentum values forward:
Predicted_Momentum = LinReg_Value + (LinReg_Slope × Forward_Offset)
This predictive component aligns with the literature on technical analysis forecasting (Lo, Mamaysky & Wang, 2000) and provides leading signals for trend changes.
#### 3.2.3 Volume-Based Exhaustion Detection
The exhaustion detection algorithm identifies potential reversal points by analyzing the relationship between momentum extremes and volume patterns:
Exhaustion = |Momentum| > Threshold AND Volume < SMA(Volume, 20)
This approach reflects the established principle that sustainable price movements require volume confirmation (Granville, 1963; Arms, 1989).
### 3.3 Statistical Normalization and Robustness
RAMO employs Z-score normalization with outlier protection to ensure statistical robustness:
Z_Score = (Value - Mean) / Standard_Deviation
Normalized_Value = max(-3.5, min(3.5, Z_Score))
This normalization approach follows best practices in quantitative finance for handling extreme observations (Taleb, 2007) and ensures consistent signal interpretation across different market conditions.
### 3.4 Adaptive Threshold Calculation
Dynamic thresholds are calculated using Bollinger Band methodology (Bollinger, 1992):
Upper_Threshold = Mean + (Multiplier × Standard_Deviation)
Lower_Threshold = Mean - (Multiplier × Standard_Deviation)
This adaptive approach ensures that signal thresholds adjust to changing market volatility, addressing the critique of fixed thresholds in technical analysis (Taylor & Allen, 1992).
## 4. Implementation Details
### 4.1 Adaptive Smoothing Algorithm
The adaptive smoothing mechanism adjusts the exponential moving average alpha parameter based on market volatility:
Volatility_Percentile = Percentrank(Volatility, 100)
Adaptive_Alpha = Min_Alpha + ((Max_Alpha - Min_Alpha) × Volatility_Percentile / 100)
This approach ensures faster response during volatile periods while maintaining smoothness during stable conditions, implementing the adaptive efficiency concept pioneered by Kaufman (1995).
### 4.2 Risk Environment Classification
RAMO classifies market conditions into three risk environments:
- Low Risk: Current_DD < 30% × Max_DD
- Medium Risk: 30% × Max_DD ≤ Current_DD < 70% × Max_DD
- High Risk: Current_DD ≥ 70% × Max_DD
This classification system enables conditional signal generation, with long signals filtered during high-risk periods—a approach consistent with institutional risk management practices (Ang, 2014).
## 5. Signal Generation and Interpretation
### 5.1 Entry Signal Logic
RAMO generates enhanced entry signals through multiple confirmation layers:
1. Primary Signal: Crossover between indicator and signal line
2. Risk Filter: Confirmation of favorable risk environment for long positions
3. Leading Component: Early warning signals via acceleration analysis
4. Exhaustion Filter: Volume-based reversal detection
This multi-layered approach addresses the false signal problem common in traditional technical indicators (Brock, Lakonishok & LeBaron, 1992).
### 5.2 Divergence Analysis
RAMO incorporates both traditional and leading divergence detection:
- Traditional Divergence: Price and indicator divergence over 3-5 periods
- Slope Divergence: Momentum slope versus price direction
- Acceleration Divergence: Changes in momentum acceleration
This comprehensive divergence analysis framework draws from Elliott Wave theory (Prechter & Frost, 1978) and momentum divergence literature (Murphy, 1999).
## 6. Empirical Advantages and Applications
### 6.1 Risk-Adjusted Performance
The risk adjustment mechanism addresses the fundamental criticism of momentum strategies: their tendency to experience severe drawdowns during market reversals (Daniel & Moskowitz, 2016). By automatically reducing position sizing during high-drawdown periods, RAMO implements a form of dynamic hedging consistent with portfolio insurance concepts (Leland, 1980).
### 6.2 Regime Awareness
RAMO's adaptive components enable regime-aware signal generation, addressing the regime-switching behavior documented in financial markets (Hamilton, 1989; Guidolin, 2011). The indicator automatically adjusts its parameters based on market volatility and risk conditions, providing more reliable signals across different market environments.
### 6.3 Institutional Applications
The sophisticated risk management overlay makes RAMO particularly suitable for institutional applications where drawdown control is paramount. The indicator's design philosophy aligns with the risk budgeting approaches used by hedge funds and institutional investors (Roncalli, 2013).
## 7. Limitations and Future Research
### 7.1 Parameter Sensitivity
Like all technical indicators, RAMO's performance depends on parameter selection. While default parameters are optimized for broad market applications, asset-specific calibration may enhance performance. Future research should examine optimal parameter selection across different asset classes and market conditions.
### 7.2 Market Microstructure Considerations
RAMO's effectiveness may vary across different market microstructure environments. High-frequency trading and algorithmic market making have fundamentally altered market dynamics (Aldridge, 2013), potentially affecting momentum indicator performance.
### 7.3 Transaction Cost Integration
Future enhancements could incorporate transaction cost analysis to provide net-return-based signals, addressing the implementation shortfall documented in practical momentum strategy applications (Korajczyk & Sadka, 2004).
## References
Aldridge, I. (2013). *High-Frequency Trading: A Practical Guide to Algorithmic Strategies and Trading Systems*. 2nd ed. Hoboken, NJ: John Wiley & Sons.
Ang, A. (2014). *Asset Management: A Systematic Approach to Factor Investing*. New York: Oxford University Press.
Arms, R. W. (1989). *The Arms Index (TRIN): An Introduction to the Volume Analysis of Stock and Bond Markets*. Homewood, IL: Dow Jones-Irwin.
Asness, C. S., Moskowitz, T. J., & Pedersen, L. H. (2013). Value and momentum everywhere. *Journal of Finance*, 68(3), 929-985.
Barroso, P., & Santa-Clara, P. (2015). Momentum has its moments. *Journal of Financial Economics*, 116(1), 111-120.
Bollinger, J. (1992). *Bollinger on Bollinger Bands*. New York: McGraw-Hill.
Brock, W., Lakonishok, J., & LeBaron, B. (1992). Simple technical trading rules and the stochastic properties of stock returns. *Journal of Finance*, 47(5), 1731-1764.
Calmar, T. (1991). The Calmar ratio: A smoother tool. *Futures*, 20(1), 40.
Campbell, J. Y., Lo, A. W., & MacKinlay, A. C. (1997). *The Econometrics of Financial Markets*. Princeton, NJ: Princeton University Press.
Chekhlov, A., Uryasev, S., & Zabarankin, M. (2005). Drawdown measure in portfolio optimization. *International Journal of Theoretical and Applied Finance*, 8(1), 13-58.
Daniel, K., & Moskowitz, T. J. (2016). Momentum crashes. *Journal of Financial Economics*, 122(2), 221-247.
Fama, E. F., & French, K. R. (1996). Multifactor explanations of asset pricing anomalies. *Journal of Finance*, 51(1), 55-84.
Granville, J. E. (1963). *Granville's New Key to Stock Market Profits*. Englewood Cliffs, NJ: Prentice-Hall.
Guidolin, M. (2011). Markov switching models in empirical finance. In D. N. Drukker (Ed.), *Missing Data Methods: Time-Series Methods and Applications* (pp. 1-86). Bingley: Emerald Group Publishing.
Hamilton, J. D. (1989). A new approach to the economic analysis of nonstationary time series and the business cycle. *Econometrica*, 57(2), 357-384.
Jegadeesh, N., & Titman, S. (1993). Returns to buying winners and selling losers: Implications for stock market efficiency. *Journal of Finance*, 48(1), 65-91.
Kahneman, D., & Tversky, A. (1979). Prospect theory: An analysis of decision under risk. *Econometrica*, 47(2), 263-291.
Kaufman, P. J. (1995). *Smarter Trading: Improving Performance in Changing Markets*. New York: McGraw-Hill.
Korajczyk, R. A., & Sadka, R. (2004). Are momentum profits robust to trading costs? *Journal of Finance*, 59(3), 1039-1082.
Leland, H. E. (1980). Who should buy portfolio insurance? *Journal of Finance*, 35(2), 581-594.
Lo, A. W., Mamaysky, H., & Wang, J. (2000). Foundations of technical analysis: Computational algorithms, statistical inference, and empirical implementation. *Journal of Finance*, 55(4), 1705-1765.
Markowitz, H. (1952). Portfolio selection. *Journal of Finance*, 7(1), 77-91.
Murphy, J. J. (1999). *Technical Analysis of the Financial Markets: A Comprehensive Guide to Trading Methods and Applications*. New York: New York Institute of Finance.
Prechter, R. R., & Frost, A. J. (1978). *Elliott Wave Principle: Key to Market Behavior*. Gainesville, GA: New Classics Library.
Pring, M. J. (2002). *Technical Analysis Explained: The Successful Investor's Guide to Spotting Investment Trends and Turning Points*. 4th ed. New York: McGraw-Hill.
Roncalli, T. (2013). *Introduction to Risk Parity and Budgeting*. Boca Raton, FL: CRC Press.
Shefrin, H., & Statman, M. (1985). The disposition to sell winners too early and ride losers too long: Theory and evidence. *Journal of Finance*, 40(3), 777-790.
Taleb, N. N. (2007). *The Black Swan: The Impact of the Highly Improbable*. New York: Random House.
Taylor, M. P., & Allen, H. (1992). The use of technical analysis in the foreign exchange market. *Journal of International Money and Finance*, 11(3), 304-314.
Treadway, A. B. (1969). On rational entrepreneurial behavior and the demand for investment. *Review of Economic Studies*, 36(2), 227-239.
Wilder, J. W. (1978). *New Concepts in Technical Trading Systems*. Greensboro, NC: Trend Research.
Cumulative Intraday Volume with Long/Short LabelsThis indicator calculates a running total of volume for each trading day, then shows on the price chart when that total crosses levels you choose. Every day at 6:00 PM Eastern Time, the total goes back to zero so it always reflects only the current day’s activity. From that moment on, each time a new candle appears the indicator looks at whether the candle closed higher than it opened or lower. If it closed higher, the candle’s volume is added to the running total; if it closed lower, the same volume amount is subtracted. As a result, the total becomes positive when buyers have dominated so far today and negative when sellers have dominated.
Because futures markets close at 6 PM ET, the running total resets exactly then, mirroring the way most intraday traders think in terms of a single session. Throughout the day, you will see this running total move up or down according to whether more volume is happening on green or red candles. Once the total goes above a number you specify (for example, one hundred thousand contracts), the indicator will place a small “Long” label at that candle on the main price chart to let you know buying pressure has reached that level. Similarly, once the total goes below a negative number you choose (for example, minus one hundred thousand), a “Short” label will appear at that candle to signal that selling pressure has reached your chosen threshold. You can set these threshold numbers to whatever makes sense for your trading style or the market you follow.
Because raw volume alone never turns negative, this design uses candle direction as a sign. Green candles (where the close is higher than the open) add volume, and red candles (where the close is lower than the open) subtract volume. Summing those signed volume values tells you in a single number whether buying or selling has been stronger so far today. That number resets every evening, so it does not carry over any buying or selling from previous sessions.
Once you have this indicator on your chart, you simply watch the “summed volume” line as it moves throughout the day. If it climbs past your long threshold, you know buyers are firmly in control and a long entry might make sense. If it falls past your short threshold, you know sellers are firmly in control and a short entry might make sense. In quieter markets or times of low volume, you might use a smaller threshold so that even modest buying or selling pressure will trigger a label. During very active periods, a larger threshold will prevent too many signals when volume spikes frequently.
This approach is straightforward but can be surprisingly powerful. It does not rely on complex formulas or hidden statistical measures. Instead, it simply adds and subtracts daily volume based on candle color, then alerts you when that total reaches levels you care about. Over several years of historical testing, this formula has shown an ability to highlight moments when intraday sentiment shifts decisively from buyers to sellers or vice versa. Because the indicator resets every day at 6 PM, it always reflects only today’s sentiment and remains easy to interpret without carrying over past data. You can use it on any intraday timeframe, but it works especially well on five-minute or fifteen-minute charts for futures contracts.
If you want a clear gauge of whether buyers or sellers are dominating in real time, and you prefer a rule-based method rather than a complex model, this indicator gives you exactly that. It shows net buying or selling pressure at a glance, resets each session like most intraday traders do, and marks the moments when that pressure crosses the levels you decide are important. By combining a daily reset with signed volume, you get a single number that tells you precisely what the crowd is doing at any given moment, without any of the guesswork or hidden calculations that more complicated indicators often carry.
Buysell Martingale Signal - CustomBuysell Martingale Signal - Custom Indicator
Introduction:
This indicator provides a dynamic buy and sell signal system incorporating an adaptive Martingale logic. Built upon the signalLib_yashgode9/2 library, it is designed for use across various markets and timeframes.
Key Features:
Primary Buy & Sell Signals: Identifies initial buy and sell opportunities based on directional changes derived from the signalLib.
Martingale Signals:
For Short (Sell) Positions: A Martingale Sell signal is triggered when the price moves against the existing short position by a specified stepPercent from the last entry price, indicating a potential opportunity to average down or increase position size.
For Long (Buy) Positions: Similarly, a Martingale Buy signal is triggered when the price moves against the existing long position by a stepPercent from the last entry price.
On-Chart Labels: Displays clear, customizable labels on the chart for primary Buy, Sell, Martingale Buy, and Martingale Sell signals.
Customizable Colors: Allows users to set distinct colors for primary signals and Martingale signals for better visual distinction.
Adjustable Sensitivity: Features configurable parameters (DEPTH_ENGINE, DEVIATION_ENGINE, BACKSTEP_ENGINE) to fine-tune the sensitivity of the underlying signal generation.
Webhook Support (Static Message Alerts): This indicator provides alerts with static messages for both primary and Martingale buy/sell signals. These alerts can be leveraged for automation by external systems (such as trading bots or exchange-provided Webhook Signal Trading services).
Important Note: When using these alerts for automation, an external system is required to handle the complex Martingale logic and position management (e.g., tracking steps, PnL calculation, hedging, dynamic quantity sizing), as this indicator solely focuses on signal generation and sending predefined messages.
How to Use:
Add the indicator to your desired chart.
Adjust the input parameters in the indicator's settings to match your specific trading symbol and timeframe.
For automation, you can set up TradingView alerts for the Buy Signal (Main/Martingale) and Sell Signal (Main/Martingale) conditions, pointing them to your preferred Webhook URL.
Configurable Parameters:
DEPTH_ENGINE: (e.g., 30) Controls the depth of analysis for the signal algorithm.
DEVIATION_ENGINE: (e.g., 5) Defines the allowable deviation for signal generation.
BACKSTEP_ENGINE: (e.g., 5) Specifies the number of historical bars to look back.
Martingale Step Percent: (e.g., 0.5) The percentage price movement against the current position that triggers a Martingale signal.
Labels Transparency: Adjusts the transparency of the on-chart signal labels.
Buy-Color / Sell-Color: Sets the color for primary Buy and Sell signal labels.
Martingale Buy-Color / Martingale Sell-Color: Sets the color for Martingale Buy and Sell signal labels.
Label size: Controls the visual size of the labels.
Label Offset: Adjusts the vertical offset of the labels from the candlesticks.
Risk Warning:
Financial trading inherently carries significant risk. Martingale strategies are particularly high-risk and can lead to substantial losses or even complete liquidation of capital if the market moves strongly and persistently against your position. Always backtest thoroughly and practice with a demo account, fully understanding the associated risks, before engaging with real capital.
Codigo Trading 1.0📌Codigo Trading 1.0
This indicator strategically combines SuperTrend, multiple Exponential Moving Averages (EMAs), the Relative Strength Index (RSI), and the Average True Range (ATR) to offer clear entry and exit signals, as well as an in-depth view of market trends. Ideal for traders looking to optimize their operations with an all-in-one tool.
🔩How the Indicator Works:
This indicator relies on the interaction and confirmation of several key components to generate signals:
SuperTrend: Determines the primary trend direction. An uptrend SuperTrend signal (green line) indicates an upward trend, while a downtrend (red line) signals a downward trend. It also serves as a guide for setting Stop Loss and Take Profit levels.
EMAs: Includes EMAs of 10, 20, 55, 100, 200, and 325 periods. The relationship between the EMA 10 and EMA 20 is fundamental for confirming the strength and direction of movements. An EMA 10 above the EMA 20 suggests an uptrend, and vice versa. Longer EMAs act as dynamic support and resistance levels, offering a broader view of the market structure.
RSI: Used to identify overbought (RSI > 70/80) and oversold (RSI < 30/20) conditions, generating "Take Profit" alerts for potential trade closures.
ATR: Monitors market volatility to help you manage exits. ATR exit signals are triggered when volatility changes direction, indicating a possible exhaustion of the movement.
🗒️Entry and Exit Signals:
I designed specific alerts based on all the indicators I use in conjunction:
Long Entries: When SuperTrend is bullish and EMA 10 crosses above EMA 20.
Short Entries: When SuperTrend is bearish and EMA 10 crosses below EMA 20.
RSI Exits (Take Profit): Indicated by "TP" labels on the chart, when the RSI reaches extreme levels (overbought for longs, oversold for shorts).
EMA 20 Exits: When the price closes below EMA 20 (for longs) or above EMA 20 (for shorts).
ATR Exits: When the ATR changes direction, signaling a possible decrease in momentum.
📌Key Benefits:
Clarity in Trend: Quickly identifies market direction with SuperTrend and EMA alignment.
Strategic Entry and Exit Signals: Receive timely alerts to optimize your entry and exit points.
Assisted Trade Management: RSI and ATR help you consider when to take profits or exit a position.
Intuitive Visualization: Arrows, labels, and colored lines make analysis easy to interpret.
Disclaimer:
Trading in financial markets carries significant risks. This indicator is an analysis tool and should not be considered financial advice. Always conduct your own research and trade at your own risk.
Profits Framework 25.6The Profits Framework 25.6 is a multi-timeframe, EMA-based trading system designed for futures traders seeking clean, high-conviction entries. This script uses:
EMAs (12, 50, 200) for structure
30-minute confluence with the current chart
A 4-factor entry scoring system (bias, stack, pullback, candle confirmation)
Fixed 100-tick target/stop
Real-time BUY/SELL labels with entry prices
Scoreboard showing win/loss outcomes for both directions
Best suited for NQ futures traders using the 15-minute chart for entries.
Test and adapt to your style before live trading.
OA - SMESSmart Money Entry Signals (SMES)
The SMES indicator is developed to identify potential turning points in market behavior by analyzing internal price dynamics, rather than relying on external volume or sentiment data. It leverages normalized price movement, directional volatility, and smoothing algorithms to detect potential areas of accumulation or distribution by market participants.
Core Concepts
Smart Money Flow calculation based on normalized price positioning
Directional VHF (Vertical Horizontal Filter) used to enhance signal directionality
Overbought and Oversold regions defined with optional glow visualization
Entry and Exit signals based on dynamic crossovers
Highly customizable input parameters for precision control
Key Inputs
Smart Money Flow Period
Smoothing Period
Price Analysis Length
Fibonacci Lookback Length
Visual toggle options (zones, glow effects, signal display)
Usage
This tool plots the smoothed smart money flow as a standalone oscillator, designed to help traders identify potential momentum shifts or extremes in market sentiment. Entry signals are generated through crossover logic, while optional filters based on price behavior can refine those signals. Exit signals are shown when the smart money line exits extreme regions.
Important Notes
This indicator does not repaint
Works on all timeframes and instruments
Best used as a confirmation tool with other technical frameworks
All calculations are based strictly on price data
Disclaimer
This script is intended for educational purposes only. It does not provide financial advice or guarantee performance. Please do your own research and apply appropriate risk management before making any trading decisions.
CNN Statistical Trading System [PhenLabs]📌 DESCRIPTION
An advanced pattern recognition system utilizing Convolutional Neural Network (CNN) principles to identify statistically significant market patterns and generate high-probability trading signals.
CNN Statistical Trading System transforms traditional technical analysis by applying machine learning concepts directly to price action. Through six specialized convolution kernels, it detects momentum shifts, reversal patterns, consolidation phases, and breakout setups simultaneously. The system combines these pattern detections using adaptive weighting based on market volatility and trend strength, creating a sophisticated composite score that provides both directional bias and signal confidence on a normalized -1 to +1 scale.
🚀 CONCEPTS
• Built on Convolutional Neural Network pattern recognition methodology adapted for financial markets
• Six specialized kernels detect distinct price patterns: upward/downward momentum, peak/trough formations, consolidation, and breakout setups
• Activation functions create non-linear responses with tanh-like behavior, mimicking neural network layers
• Adaptive weighting system adjusts pattern importance based on current market regime (volatility < 2% and trend strength)
• Multi-confirmation signals require CNN threshold breach (±0.65), RSI boundaries, and volume confirmation above 120% of 20-period average
🔧 FEATURES
Six-Kernel Pattern Detection:
Simultaneous analysis of upward momentum, downward momentum, peak/resistance, trough/support, consolidation, and breakout patterns using mathematically optimized convolution kernels.
Adaptive Neural Architecture:
Dynamic weight adjustment based on market volatility (ATR/Price) and trend strength (EMA differential), ensuring optimal performance across different market conditions.
Professional Visual Themes:
Four sophisticated color palettes (Professional, Ocean, Sunset, Monochrome) with cohesive design language. Default Monochrome theme provides clean, distraction-free analysis.
Confidence Band System:
Upper and lower confidence zones at 150% of threshold values (±0.975) help identify high-probability signal areas and potential exhaustion zones.
Real-Time Information Panel:
Live display of CNN score, market state with emoji indicators, net momentum, confidence percentage, and RSI confirmation with dynamic color coding based on signal strength.
Individual Feature Analysis:
Optional display of all six kernel outputs with distinct visual styles (step lines, circles, crosses, area fills) for advanced pattern component analysis.
User Guide
• Monitor CNN Score crossing above +0.65 for long signals or below -0.65 for short signals with volume confirmation
• Use confidence bands to identify optimal entry zones - signals within confidence bands carry higher probability
• Background intensity reflects signal strength - darker backgrounds indicate stronger conviction
• Enter long positions when blue circles appear above oscillator with RSI < 75 and volume > 120% average
• Enter short positions when dark circles appear below oscillator with RSI > 25 and volume confirmation
• Information panel provides real-time confidence percentage and momentum direction for position sizing decisions
• Individual feature plots allow granular analysis of specific pattern components for strategy refinement
💡Conclusion
CNN Statistical Trading System represents the evolution of technical analysis, combining institutional-grade pattern recognition with retail accessibility. The six-kernel architecture provides comprehensive market pattern coverage while adaptive weighting ensures relevance across all market conditions. Whether you’re seeking systematic entry signals or advanced pattern confirmation, this indicator delivers mathematically rigorous analysis with intuitive visual presentation.
Congestion Indicator - Oscillator by saurabh maggoCore Functionality
Market State Detection:
Congestion: Identifies periods of low volatility (price consolidation) where the price range is tight relative to the Average True Range (ATR). Visualized with a blue background in the oscillator panel.
Breakout Up: Detects upward breakouts from congestion zones, requiring conditions like price movement above the congestion high, volume spikes, and volatility increases. Visualized with a green background.
Breakdown (Breakout Down): Detects downward breakouts from congestion zones, with similar conditions as Breakout Up but for downward movement. Visualized with a red background.
Post-Congestion: Identifies the period after a congestion zone ends but before a breakout occurs (if extend_until_breakout is disabled). Visualized with a yellow background.
Pullback: Detects pullbacks after breakouts or breakdowns, useful for identifying potential entry points (if use_pullback_entry is enabled). Visualized with a purple background.
Visualization:
Oscillator Panel: Displays the market state in a separate panel below the chart.
Background Color: The panel’s background color changes to reflect the current state (e.g., blue for Congestion, green for Breakout Up).
Histogram Plot: Optionally plots the state value as a histogram (e.g., 1 for Congestion, 2 for Breakout Up), toggleable via TradingView’s "Style" tab ("Market State"). The histogram provides a numerical representation of the state:
Congestion: 1.0
Breakout Up: 2.0
Breakdown: -2.0
Post-Congestion: 0.5
Pullback: 1.5
None: 0.0
Alerts:
Generates alerts for state changes (Congestion, Breakout Up, Breakdown).
Supports enhanced alerts (if use_enhanced_alerts is enabled), including additional context like breakout level, volatility state, and trend direction.
Includes an alert cooldown period (if use_alert_cooldown is enabled) to prevent excessive alerts.
Key Features and Filters
Customizable Parameters:
Lookback Period: Adjusts the number of bars used to calculate the price range for congestion detection.
Range Threshold: Sets the maximum price range (as a percentage of ATR) for a congestion zone.
Dynamic Threshold: Optionally uses a percentile-based dynamic threshold for more adaptive congestion detection.
Minimum Congestion Bars: Requires a minimum number of bars for a congestion zone to be confirmed.
Volume Filter: Optionally requires low volume during congestion zones.
Volume Breakout Filter: Requires a volume spike for breakouts/breakdowns.
Volatility Breakout Filter: Requires an ATR spike for breakouts/breakdowns.
Minimum Price Movement: Optionally requires a minimum price movement for breakouts/breakdowns.
RSI Filter: Optionally requires RSI to be in a neutral range during congestion.
Max Price Range Filter: Limits the absolute price range for congestion zones.
Trend Filter: Optionally filters breakouts/breakdowns based on a higher timeframe trend (using a moving average).
Momentum Filter: Optionally requires MACD momentum confirmation for breakouts/breakdowns.
Pullback Detection: Optionally detects pullbacks after breakouts/breakdowns for entry opportunities.
Timeframe Adjustment: Adjusts parameters based on the chart’s timeframe.
Auto-Settings: Automatically adjusts parameters based on market volatility.
Show Current Day Only: Optionally limits the indicator’s display to the current trading day (NSE session).
Presets: Offers predefined configurations (Default, Aggressive, Conservative) for quick setup.
Session Support: Operates within the NSE session (9:15 AM–3:30 PM IST) by default, ensuring relevance for Indian markets.
Visual Output
The oscillator panel uses color-coded backgrounds to indicate the market state:
Blue: Congestion
Green: Breakout Up
Red: Breakdown
Yellow: Post-Congestion
Purple: Pullback
Transparent (None): No state detected
The histogram plot (optional) provides a numerical representation of the state, which can be toggled on/off in TradingView’s settings.
Alerts
Alerts are triggered for significant state changes (Congestion, Breakout Up, Breakdown).
Enhanced alerts include additional details like price levels, volatility, and trend direction, making them more informative for traders.
Step 2: Craft the Description for Publishing
Based on the analysis, here’s a concise, user-friendly description you can use when publishing the indicator on TradingView:
Congestion Indicator - Oscillator by Saurabh Maggo
This indicator identifies market congestion zones, breakouts, breakdowns, post-congestion periods, and pullbacks in a separate oscillator panel below your chart. Designed for traders, it helps you spot key market states and potential trading opportunities with clear visual cues and customizable alerts.
Key Features:
Market States: Detects Congestion (Blue), Breakout Up (Green), Breakdown (Red), Post-Congestion (Yellow), and Pullbacks (Purple).
Visual Display: Shows market states using background colors in an oscillator panel, with an optional histogram plot (toggleable in settings).
Alerts: Generates alerts for state changes, with enhanced options to include price levels, volatility, and trend context.
Customizable Filters: Includes volume, volatility, RSI, trend, momentum, and price movement filters to refine signals.
Adaptable Settings: Supports dynamic thresholds, timeframe adjustments, auto-settings based on volatility, and predefined presets (Default, Aggressive, Conservative).
NSE Session: Optimized for Indian markets with a default session time of 9:15 AM–3:30 PM IST.
How can Grok help?
Adaptive Volume‐Demand‐Index (AVDI)Demand Index (according to James Sibbet) – Short Description
The Demand Index (DI) was developed by James Sibbet to measure real “buying” vs. “selling” strength (Demand vs. Supply) using price and volume data. It is not a standalone trading signal, but rather a filter and trend confirmer that should always be used together with chart structure and additional indicators.
---
\ 1. Calculation Basis\
1. Volume Normalization
$$
\text{normVol}_t
= \frac{\text{Volume}_t}{\mathrm{EMA}(\text{Volume},\,n_{\text{Vol}})_t}
\quad(\text{e.g., }n_{\text{Vol}} = 13)
$$
This smooths out extremely high volume spikes and compares them to the average (≈ 1 means “average volume”).
2. Price Factor
$$
\text{priceFactor}_t
= \frac{\text{Close}_t - \text{Open}_t}{\text{Open}_t}.
$$
Positive values for bullish bars, negative for bearish bars.
3. Component per Bar
$$
\text{component}_t
= \text{normVol}_t \times \text{priceFactor}_t.
$$
If volume is above average (> 1) and the price rises slightly, this yields a noticeably positive value; conversely if the price falls.
4. Raw DI (Rolling Sum)
Over a window of \$w\$ bars (e.g., 20):
$$
\text{RawDI}_t
= \sum_{i=0}^{w-1} \text{component}_{\,t-i}.
$$
Alternatively, recursively for \$t \ge w\$:
$$
\text{RawDI}_t
= \text{RawDI}_{t-1}
+ \text{component}_t
- \text{component}_{\,t-w}.
$$
5. Optional EMA Smoothing
An EMA over RawDI (e.g., \$n\_{\text{DI}} = 50\$) reduces short-term fluctuations and highlights medium-term trends:
$$
\text{EMA\_DI}_t
= \mathrm{EMA}(\text{RawDI},\,n_{\text{DI}})_t.
$$
6.Zero Line
Handy guideline:
RawDI > 0: Accumulated buying power dominates.
RawDI < 0: Accumulated selling power dominates.
2. Interpretation & Application
Crossing Zero
RawDI above zero → Indication of increasing buying pressure (potential long signal).
RawDI below zero → Indication of increasing selling pressure (potential short signal).
Not to be used alone for entry—always confirm with price action.
RawDI vs. EMA_DI
RawDI > EMA\_DI → Acceleration of demand.
RawDI < EMA\_DI → Weakening of demand.
Divergences
Price makes a new high, RawDI does not make a higher high → potential weakness in the uptrend.
Price makes a new low, RawDI does not make a lower low → potential exhaustion of the downtrend.
3. Typical Signals (for Beginners)
\ 1. Long Setup\
RawDI crosses zero from below,
RawDI > EMA\_DI (acceleration),
Price closes above a short-term swing high or resistance.
Stop-Loss: just below the last swing low, Take-Profit/Trailing: on reversal signals or fixed R\:R.
2. Short Setup
RawDI crosses zero from above,
RawDI < EMA\_DI (increased selling pressure),
Price closes below a short-term swing low or support.
Stop-Loss: just above the last swing high.
---
4. Notes and Parameters
Recommended Values (Beginners):
Volume EMA (n₍Vol₎) = 13
RawDI window (w) = 20
EMA over DI (n₍DI₎) = 50 (medium-term) or 1 (no smoothing)
Attention:\
NEVER use in isolation. Always in combination with price action analysis (trendlines, support/resistance, candlestick patterns).
Especially during volatile news phases, RawDI can fluctuate strongly → EMA\_DI helps to avoid false signals.
---
Conclusion The Demand Index by James Sibbet is a powerful filter to assess price movements by their volume backing. It shows whether a rally is truly driven by demand or merely a short-term volume anomaly. In combination with classic chart analysis and risk management, it helps to identify robust entry points and potential trend reversals earlier.
Candle/RSI BUY SELLWhy Use Candlesticks?
They help traders visualize price action
Used in technical analysis and price pattern recognition (e.g., Doji, Engulfing, Hammer)
Assist in determining entry and exit points
Why Traders Use RSI:
To identify potential reversal zones
To confirm trend strength
To detect divergences between price and momentum
Why Combine Candlestick Patterns with RSI?
Using Candlestick patterns together with the Relative Strength Index (RSI) enhances trading decisions by combining price action and momentum analysis.
Conclusion:
Combining RSI with Candlestick patterns allows traders to:
Confirm potential reversals
Filter false signals
Improve entry and exit timing
Make more confident and accurate decisions
How It Works:
RSI Calculation
Custom RSI is calculated manually using Wilder's smoothing technique.
MA or BB Option
User can select whether to apply a smoothing MA or Bollinger Bands to RSI (useful for visual enhancements or custom strategies).
Buy/Sell Logic
check for:
Buy when the current candle is bullish (open <= close) and the previous candle was bearish (open >= close ), AND RSI is ≥ 50.
Sell when current candle is bearish and previous was bullish, AND RSI is ≤ 50.
Plot Buy/Sell Labels
Final Verdict
code is:
Valid (no syntax errors)
Useful (combines candlestick confirmation + RSI strength)
Extendable (can add divergence, alerts, etc.)
This Timeframe 5 min : XAU
9:15 Range with 0.09% BufferThis strategy is based on the first 9:15 AM candle for Nifty, which is considered a key reference point (also called the "GAN level entry"). It defines a range around the high and low of the 9:15 candle with a 0.09% buffer on both sides.
The upper buffer level acts as a potential resistance.
The lower buffer level acts as a potential support.
When the price crosses above the upper buffer, it signals a possible entry for a Call option (CE) or a long position.
When the price crosses below the lower buffer, it signals a possible entry for a Put option (PE) or a short position.
This approach helps traders identify early breakout opportunities based on the opening candle range, aiming to capture momentum moves in either direction during the trading session.
Z-Score Adaptive Connors RSIZ-Score Adaptive Connors RSI blends the classic three-component Connors RSI (RSI, Up/Down streak RSI, and Percentile Rank of 1-bar ROC) with a dynamic z-score filter that distinguishes trending vs. mean-reverting market regimes.
When the indicator detects an extreme deviation (|z-score| > threshold) , it switches to “trending” mode and tightens entry thresholds for capturing momentum. When markets are in a more neutral regime, it reverts to wider thresholds, hunting for overbought/oversold reversals.
Key Features
Connors RSI Core: Combines price momentum, streak measurements, and velocity for a robust baseline oscillator. Z-Score Regime Filter: Computes the z-score of the Connors RSI over a lookback window to adapt your trading style to trending vs. reverting environments.
Dynamic Thresholds: Separate user-configurable thresholds for trending (“tight” entries) and mean-reverting (“wide” entries) scenarios.
Inputs & Parameters
Connors RSI Settings
RSI Source: Price series for RSI calculation (default: Close)
RSI Length: Period for price‐change RSI (default: 24)
Up/Down Length: Period for streak RSI (default: 20)
ROC Length: Period for percentile‐rank of 1-bar return (default: 75)
Z-Score Filter
Lookback: Number of bars to compute mean and standard deviation of Connors RSI (default: 14)
Threshold: Minimum |z-score| to enter “trending” mode (default: 1.5)
Entry Thresholds
Trending Long/Short: Upper and lower RSI Thresholds when trending
Reverting Long/Short: Upper and lower RSI Thresholds when reverting
Uptrick: Z-Trend BandsOverview
Uptrick: Z-Trend Bands is a Pine Script overlay crafted to capture high-probability mean-reversion opportunities. It dynamically plots upper and lower statistical bands around an EMA baseline by converting price deviations into z-scores. Once price moves outside these bands and then reenters, the indicator verifies that momentum is genuinely reversing via an EMA-smoothed RSI slope. Signal memory ensures only one entry per momentum swing, and traders receive clear, real-time feedback through customizable bar-coloring modes, a semi-transparent fill highlighting the statistical zone, concise “Up”/“Down” labels, and a live five-metric scoring table.
Introduction
Markets often oscillate between trending and reverting, and simple thresholds or static envelopes frequently misfire when volatility shifts. Standard deviation quantifies how “wide” recent price moves have been, and a z-score transforms each deviation into a measure of how rare it is relative to its own history. By anchoring these bands to an exponential moving average, the script maintains a fluid statistical envelope that adapts instantly to both calm and turbulent regimes. Meanwhile, the Relative Strength Index (RSI) tracks momentum; smoothing RSI with an EMA and observing its slope filters out erratic spikes, ensuring that only genuine momentum flips—upward for longs and downward for shorts—qualify.
Purpose
This indicator is purpose-built for short-term mean-reversion traders operating on lower–timeframe charts. It reveals when price has strayed into the outer 5 percent of its recent range, signaling an increased likelihood of a bounce back toward fair value. Rather than firing on price alone, it demands that momentum follow suit: the smoothed RSI slope must flip in the opposite direction before any trade marker appears. This dual-filter approach dramatically reduces noise-driven, false setups. Traders then see immediate visual confirmation—bar colors that reflect the latest signal and age over time, clear entry labels, and an always-visible table of metric scores—so they can gauge both the validity and freshness of each signal at a glance.
Originality and Uniqueness
Uptrick: Z-Trend Bands stands apart from typical envelope or oscillator tools in four key ways. First, it employs fully normalized z-score bands, meaning ±2 always captures roughly the top and bottom 5 percent of moves, regardless of volatility regime. Second, it insists on two simultaneous conditions—price reentry into the bands and a confirming RSI slope flip—dramatically reducing whipsaw signals. Third, it uses slope-phase memory to lock out duplicate signals until momentum truly reverses again, enforcing disciplined entries. Finally, it offers four distinct bar-coloring schemes (solid reversal, fading reversal, exceeding bands, and classic heatmap) plus a dynamic scoring table, rather than a single, opaque alert, giving traders deep insight into every layer of analysis.
Why Each Component Was Picked
The EMA baseline was chosen for its blend of responsiveness—weighting recent price heavily—and smoothness, which filters market noise. Z-score deviation bands standardize price extremes relative to their own history, adapting automatically to shifting volatility so that “extreme” always means statistically rare. The RSI, smoothed with an EMA before slope calculation, captures true momentum shifts without the false spikes that raw RSI often produces. Slope-phase memory flags prevent repeated alerts within a single swing, curbing over-trading in choppy conditions. Bar-coloring modes provide flexible visual contexts—whether you prefer to track the latest reversal, see signal age, highlight every breakout, or view a continuous gradient—and the scoring table breaks down all five core checks for complete transparency.
Features
This indicator offers a suite of configurable visual and logical tools designed to make reversal signals both robust and transparent:
Dynamic z-score bands that expand or contract in real time to reflect current volatility regimes, ensuring the outer ±zThreshold levels always represent statistically rare extremes.
A smooth EMA baseline that weights recent price more heavily, serving as a fair-value anchor around which deviations are measured.
EMA-smoothed RSI slope confirmation, which filters out erratic momentum spikes by first smoothing raw RSI and then requiring its bar-to-bar slope to flip before any signal is allowed.
Slope-phase memory logic that locks out duplicate buy or sell markers until the RSI slope crosses back through zero, preventing over-trading during choppy swings.
Four distinct bar-coloring modes—Reversal Solid, Reversal Fade, Exceeding Bands, Classic Heat—plus a “None” option, so traders can choose whether to highlight the latest signal, show signal age, emphasize breakout bars, or view a continuous heat gradient within the bands.
A semi-transparent fill between the EMA and the upper/lower bands that visually frames the statistical zone and makes extremes immediately obvious.
Concise “Up” and “Down” labels that plot exactly when price re-enters a band with confirming momentum, keeping chart clutter to a minimum.
A real-time, five-metric scoring table (z-score, RSI slope, price vs. EMA, trend state, re-entry) that updates every two bars, displaying individual +1/–1/0 scores and an averaged Buy/Sell/Neutral verdict for complete transparency.
Calculations
Compute the fair-value EMA over fairLen bars.
Subtract that EMA from current price each bar to derive the raw deviation.
Over zLen bars, calculate the rolling mean and standard deviation of those deviations.
Convert each deviation into a z-score by subtracting the mean and dividing by the standard deviation.
Plot the upper and lower bands at ±zThreshold × standard deviation around the EMA.
Calculate raw RSI over rsiLen bars, then smooth it with an EMA of length rsiEmaLen.
Derive the RSI slope by taking the difference between the current and previous smoothed RSI.
Detect a potential reentry when price exits one of the bands on the prior bar and re-enters on the current bar.
Require that reentry coincide with an RSI slope flip (positive for a lower-band reentry, negative for an upper-band reentry).
On first valid reentry per momentum swing, fire a buy or sell signal and set a memory flag; reset that flag only when the RSI slope crosses back through zero.
For each bar, assign scores of +1, –1, or 0 for the z-score direction, RSI slope, price vs. EMA, trend-state, and reentry status.
Average those five scores; if the result exceeds +0.1, label “Buy,” if below –0.1, label “Sell,” otherwise “Neutral.”
Update bar colors, the semi-transparent fill, reversal labels, and the scoring table every two bars to reflect the latest calculations.
How It Actually Works
On each new candle, the EMA baseline and band widths update to reflect current volatility. The RSI is smoothed and its slope recalculated. The script then looks back one bar to see if price exited either band and forward to see if it reentered. If that reentry coincides with an appropriate RSI slope flip—and no signal has yet been generated in that swing—a concise label appears. Bar colors refresh according to your selected mode, and the scoring table updates to show which of the five conditions passed or failed, along with the overall verdict. This process repeats seamlessly at each bar, giving traders a continuous feed of disciplined, statistically filtered reversal cues.
Inputs
All parameters are fully user-configurable, allowing you to tailor sensitivity, lookbacks, and visuals to your trading style:
EMA length (fairLen): number of bars for the fair-value EMA; higher values smooth more but lag further behind price.
Z-Score lookback (zLen): window for calculating the mean and standard deviation of price deviations; longer lookbacks reduce noise but respond more slowly to new volatility.
Z-Score threshold (zThreshold): number of standard deviations defining the upper and lower bands; common default is 2.0 for roughly the outer 5 percent of moves.
Source (src): choice of price series (close, hl2, etc.) used for EMA, deviation, and RSI calculations.
RSI length (rsiLen): period for raw RSI calculation; shorter values react faster to momentum changes but can be choppier.
RSI EMA length (rsiEmaLen): period for smoothing raw RSI before taking its slope; higher values filter more noise.
Bar coloring mode (colorMode): select from None, Reversal Solid, Reversal Fade, Exceeding Bands, or Classic Heat to control how bars are shaded in relation to signals and band positions.
Show signals (showSignals): toggle on-chart “Up” and “Down” labels for reversal entries.
Show scoring table (enableTable): toggle the display of the five-metric breakdown table.
Table position (tablePos): choose which corner (Top Left, Top Right, Bottom Left, Bottom Right) hosts the scoring table.
Conclusion
By merging a normalized z-score framework, momentum slope confirmation, disciplined signal memory, flexible visuals, and transparent scoring into one Pine Script overlay, Uptrick: Z-Trend Bands offers a powerful yet intuitive tool for intraday mean-reversion trading. Its adaptability to real-time volatility and multi-layered filter logic deliver clear, high-confidence reversal cues without the clutter or confusion of simpler indicators.
Disclaimer
This indicator is provided solely for educational and informational purposes. It does not constitute financial advice. Trading involves substantial risk and may not be suitable for all investors. Past performance is not indicative of future results. Always conduct your own testing and apply careful risk management before trading live.
Brian Shannon 5-Day MA BackgroundBrian Shannon 5-Day Moving Average with Dynamic Background Fill
OVERVIEW
This indicator implements Brian Shannon's renowned 5-Day Moving Average methodology from his acclaimed work "Technical Analysis Using Multiple Timeframes." The indicator provides instant visual clarity on short-term trend direction and momentum, making it an essential tool for swing traders and active investors.
KEY FEATURES
• True 5-Day Moving Average: Dynamically calculates the correct period across all timeframes (1min, 5min, 15min, 1H, etc.)
• Visual Price-to-MA Relationship: Color-coded fill between price and the moving average
- Green Fill: Price is above the 5-day MA (bullish short-term momentum)
- Red Fill: Price is below the 5-day MA (bearish short-term momentum)
• Multi-Timeframe Compatible: Works seamlessly on any chart timeframe while maintaining the true 5-day calculation
BRIAN SHANNON'S STRATEGIC APPLICATION
Primary Uses:
1. Trend Identification: Quickly identify short-term momentum shifts
2. Dynamic Support/Resistance: The 5-day MA acts as a moving support level in uptrends and resistance in downtrends
3. Entry Signal Confirmation: Look for pullbacks to the 5-day MA as potential entry points in trending stocks
4. Multi-Timeframe Analysis: Essential component of Shannon's multiple timeframe approach
Perfect Combination with:
• AVWAP (Anchored Volume Weighted Average Price): Use together to identify high-probability setups where price is above both the 5-day MA and AVWAP
• Longer-term Moving Averages: Combine with 20-day and 50-day MAs for complete trend analysis
• Volume Analysis: Confirm 5-day MA signals with volume patterns
TRADING APPLICATIONS
For Swing Traders:
• Bullish Setup: Price above 5-day MA + above AVWAP + above longer-term MAs = Strong uptrend
• Bearish Setup: Price below 5-day MA + below AVWAP + below longer-term MAs = Strong downtrend
• Entry Timing: Use pullbacks to the 5-day MA as entry opportunities in the direction of the primary trend
For Day Traders:
• Quick visual confirmation of intraday momentum
• Dynamic support/resistance levels for scalping opportunities
• Clear trend bias for directional trades
WHY THIS INDICATOR WORKS
Brian Shannon's approach emphasizes that the 5-day moving average represents the short-term sentiment of market participants. When price is consistently above this level, it indicates buyers are in control of short-term price action. Conversely, when price falls below, it suggests selling pressure is dominating.
The visual fill makes it immediately obvious:
• How far price is from the 5-day MA
• The strength of the current short-term trend
• Potential areas where price might find support or resistance
BEST PRACTICES
1. Never use in isolation - Always combine with longer timeframe analysis
2. Volume confirmation - Look for volume expansion on moves away from the 5-day MA
3. Multiple timeframe approach - Check higher timeframes for overall trend direction
4. Combine with AVWAP - Most powerful when both indicators align
INSTALLATION NOTES
This indicator automatically adjusts for any timeframe, ensuring you always get a true 5-trading-day moving average regardless of whether you're viewing 1-minute or hourly charts.
Based on the technical analysis methodology of Brian Shannon, author of "Technical Analysis Using Multiple Timeframes"
FVG Premium [no1x]█ OVERVIEW
This indicator provides a comprehensive toolkit for identifying, visualizing, and tracking Fair Value Gaps (FVGs) across three distinct timeframes (current chart, a user-defined Medium Timeframe - MTF, and a user-defined High Timeframe - HTF). It is designed to offer traders enhanced insight into FVG dynamics through detailed state monitoring (formation, partial fill, full mitigation, midline touch), extensive visual customization for FVG representation, and a rich alert system for timely notifications on FVG-related events.
█ CONCEPTS
This indicator is built upon the core concept of Fair Value Gaps (FVGs) and their significance in price action analysis, offering a multi-layered approach to their detection and interpretation across different timeframes.
Fair Value Gaps (FVGs)
A Fair Value Gap (FVG), also known as an imbalance, represents a range in price delivery where one side of the market (buying or selling) was more aggressive, leaving an inefficiency or an "imbalance" in the price action. This concept is prominently featured within Smart Money Concepts (SMC) and Inner Circle Trader (ICT) methodologies, where such gaps are often interpreted as footprints left by "smart money" due to rapid, forceful price movements. These methodologies suggest that price may later revisit these FVG zones to rebalance a prior inefficiency or to seek liquidity before continuing its path. These gaps are typically identified by a three-bar pattern:
Bullish FVG : This is a three-candle formation where the second candle shows a strong upward move. The FVG is the space created between the high of the first candle (bottom of FVG) and the low of the third candle (top of FVG). This indicates a strong upward impulsive move.
Bearish FVG : This is a three-candle formation where the second candle shows a strong downward move. The FVG is the space created between the low of the first candle (top of FVG) and the high of the third candle (bottom of FVG). This indicates a strong downward impulsive move.
FVGs are often watched by traders as potential areas where price might return to "rebalance" or find support/resistance.
Multi-Timeframe (MTF) Analysis
The indicator extends FVG detection beyond the current chart's timeframe (Low Timeframe - LTF) to two higher user-defined timeframes: Medium Timeframe (MTF) and High Timeframe (HTF). This allows traders to:
Identify FVGs that might be significant on a broader market structure.
Observe how FVGs from different timeframes align or interact.
Gain a more comprehensive perspective on potential support and resistance zones.
FVG State and Lifecycle Management
The indicator actively tracks the lifecycle of each detected FVG:
Formation : The initial identification of an FVG.
Partial Fill (Entry) : When price enters but does not completely pass through the FVG. The indicator updates the "current" top/bottom of the FVG to reflect the filled portion.
Midline (Equilibrium) Touch : When price touches the 50% level of the FVG.
Full Mitigation : When price completely trades through the FVG, effectively "filling" or "rebalancing" the gap. The indicator records the mitigation time.
This state tracking is crucial for understanding how price interacts with these zones.
FVG Classification (Large FVG)
FVGs can be optionally classified as "Large FVGs" (LV) if their size (top to bottom range) exceeds a user-defined multiple of the Average True Range (ATR) for that FVG's timeframe. This helps distinguish FVGs that are significantly larger relative to recent volatility.
Visual Customization and Information Delivery
A key concept is providing extensive control over how FVGs are displayed. This control is achieved through a centralized set of visual parameters within the indicator, allowing users to configure numerous aspects (colors, line styles, visibility of boxes, midlines, mitigation lines, labels, etc.) for each timeframe. Additionally, an on-chart information panel summarizes the nearest unmitigated bullish and bearish FVG levels for each active timeframe, providing a quick glance at key price points.
█ FEATURES
This indicator offers a rich set of features designed to provide a highly customizable and comprehensive Fair Value Gap (FVG) analysis experience. Users can tailor the FVG detection, visual representation, and alerting mechanisms across three distinct timeframes: the current chart (Low Timeframe - LTF), a user-defined Medium Timeframe (MTF), and a user-defined High Timeframe (HTF).
Multi-Timeframe FVG Detection and Display
The core strength of this indicator lies in its ability to identify and display FVGs from not only the current chart's timeframe (LTF) but also from two higher, user-selectable timeframes (MTF and HTF).
Timeframe Selection: Users can specify the exact MTF (e.g., "60", "240") and HTF (e.g., "D", "W") through dedicated inputs in the "MTF (Medium Timeframe)" and "HTF (High Timeframe)" settings groups. The visibility of FVGs from these higher timeframes can be toggled independently using the "Show MTF FVGs" and "Show HTF FVGs" checkboxes.
Consistent Detection Logic: The FVG detection logic, based on the classic three-bar imbalance pattern detailed in the 'Concepts' section, is applied consistently across all selected timeframes (LTF, MTF, HTF)
Timeframe-Specific Visuals: Each timeframe's FVGs (LTF, MTF, HTF) can be customized with unique colors for bullish/bearish states and their mitigated counterparts. This allows for easy visual differentiation of FVGs originating from different market perspectives.
Comprehensive FVG Visualization Options
The indicator provides extensive control over how FVGs are visually represented on the chart for each timeframe (LTF, MTF, HTF).
FVG Boxes:
Visibility: Main FVG boxes can be shown or hidden per timeframe using the "Show FVG Boxes" (for LTF), "Show Boxes" (for MTF/HTF) inputs.
Color Customization: Colors for bullish, bearish, active, and mitigated FVG boxes (including Large FVGs, if classified) are fully customizable for each timeframe.
Box Extension & Length: FVG boxes can either be extended to the right indefinitely ("Extend Boxes Right") or set to a fixed length in bars ("Short Box Length" or "Box Length" equivalent inputs).
Box Labels: Optional labels can display the FVG's timeframe and fill percentage on the box. These labels are configurable for all timeframes (LTF, MTF, and HTF). Please note: If FVGs are positioned very close to each other on the chart, their respective labels may overlap. This can potentially lead to visual clutter, and it is a known behavior in the current version of the indicator.
Box Borders: Visibility, width, style (solid, dashed, dotted), and color of FVG box borders are customizable per timeframe.
Midlines (Equilibrium/EQ):
Visibility: The 50% level (midline or EQ) of FVGs can be shown or hidden for each timeframe.
Style Customization: Width, style, and color of the midline are customizable per timeframe. The indicator tracks if this midline has been touched by price.
Mitigation Lines:
Visibility: Mitigation lines (representing the FVG's opening level that needs to be breached for full mitigation) can be shown or hidden for each timeframe. If shown, these lines are always extended to the right.
Style Customization: Width, style, and color of the mitigation line are customizable per timeframe.
Mitigation Line Labels: Optional price labels can be displayed on mitigation lines, with a customizable horizontal bar offset for positioning. For optimal label placement, the following horizontal bar offsets are recommended: 4 for LTF, 8 for MTF, and 12 for HTF.
Persistence After Mitigation: Users can choose to keep mitigation lines visible even after an FVG is fully mitigated, with a distinct color for such lines. Importantly, this option is only effective if the general setting 'Hide Fully Mitigated FVGs' is disabled, as otherwise, the entire FVG and its lines will be removed upon mitigation.
FVG State Management and Behavior
The indicator tracks and visually responds to changes in FVG states.
Hide Fully Mitigated FVGs: This option, typically found in the indicator's general settings, allows users to automatically remove all visual elements of an FVG from the chart once price has fully mitigated it. This helps maintain chart clarity by focusing on active FVGs.
Partial Fill Visualization: When price enters an FVG, the indicator offers a dynamic visual representation: the portion of the FVG that has been filled is shown as a "mitigated box" (typically with a distinct color), while the original FVG box shrinks to clearly highlight the remaining, unfilled portion. This two-part display provides an immediate visual cue about how much of the FVG's imbalance has been addressed and what potential remains within the gap.
Visual Filtering by ATR Proximity: To help users focus on the most relevant price action, FVGs can be dynamically hidden if they are located further from the current price than a user-defined multiple of the Average True Range (ATR). This behavior is controlled by the "Filter Band Width (ATR Multiple)" input; setting this to zero disables the filter entirely, ensuring all detected FVGs remain visible regardless of their proximity to price.
Alternative Usage Example: Mitigation Lines as Key Support/Resistance Levels
For traders preferring a minimalist chart focused on key Fair Value Gap (FVG) levels, the indicator's visualization settings can be customized to display only FVG mitigation lines. This approach leverages these lines as potential support and resistance zones, reflecting areas where price might revisit to address imbalances.
To configure this view:
Disable FVG Boxes: Turn off "Show FVG Boxes" (for LTF) or "Show Boxes" (for MTF/HTF) for the desired timeframes.
Hide Midlines: Disable the visibility of the 50% FVG Midlines (Equilibrium/EQ).
Ensure Mitigation Lines are Visible: Keep "Mitigation Lines" enabled.
Retain All Mitigation Lines:
Disable the "Hide Fully Mitigated FVGs" option in the general settings.
Enable the feature to "keep mitigation lines visible even after an FVG is fully mitigated". This ensures lines from all FVGs (active or fully mitigated) remain on the chart, which is only effective if "Hide Fully Mitigated FVGs" is disabled.
This setup offers:
A Decluttered Chart: Focuses solely on the FVG opening levels.
Precise S/R Zones: Treats mitigation lines as specific points for potential price reactions.
Historical Level Analysis: Includes lines from past, fully mitigated FVGs for a comprehensive view of significant price levels.
For enhanced usability with this focused view, consider these optional additions:
The on-chart Information Panel can be activated to display a quick summary of the nearest unmitigated FVG levels.
Mitigation Line Labels can also be activated for clear price level identification. A customizable horizontal bar offset is available for positioning these labels; for example, offsets of 4 for LTF, 8 for MTF, and 12 for HTF can be effective.
FVG Classification (Large FVG)
This feature allows for distinguishing FVGs based on their size relative to market volatility.
Enable Classification: Users can enable "Classify FVG (Large FVG)" to identify FVGs that are significantly larger than average.
ATR-Based Threshold: An FVG is classified as "Large" if its height (price range) is greater than or equal to the Average True Range (ATR) of its timeframe multiplied by a user-defined "Large FVG Threshold (ATR Multiple)". The ATR period for this calculation is also configurable.
Dedicated Colors: Large FVGs (both bullish/bearish and active/mitigated) can be assigned unique colors, making them easily distinguishable on the chart.
Panel Icon: Large FVGs are marked with a special icon in the Info Panel.
Information Panel
An on-chart panel provides a quick summary of the nearest unmitigated FVG levels.
Visibility and Position: The panel can be shown/hidden and positioned in any of the nine standard locations on the chart (e.g., Top Right, Middle Center).
Content: It displays the price levels of the nearest unmitigated bullish and bearish FVGs for LTF, MTF (if active), and HTF (if active). It also indicates if these nearest FVGs are Large FVGs (if classification is enabled) using a selectable icon.
Styling: Text size, border color, header background/text colors, default text color, and "N/A" cell background color are customizable.
Highlighting: Background and text colors for the cells displaying the overall nearest bullish and bearish FVG levels (across all active timeframes) can be customized to draw attention to the most proximate FVG.
Comprehensive Alert System
The indicator offers a granular alert system for various FVG-related events, configurable for each timeframe (LTF, MTF, HTF) independently. Users can enable alerts for:
New FVG Formation: Separate alerts for new bullish and new bearish FVG formations.
FVG Entry/Partial Fill: Separate alerts for price entering a bullish FVG or a bearish FVG.
FVG Full Mitigation: Separate alerts for full mitigation of bullish and bearish FVGs.
FVG Midline (EQ) Touch: Separate alerts for price touching the midline of a bullish or bearish FVG.
Alert messages are detailed, providing information such as the timeframe, FVG type (bull/bear, Large FVG), relevant price levels, and timestamps.
█ NOTES
This section provides additional information regarding the indicator's usage, performance considerations, and potential interactions with the TradingView platform. Understanding these points can help users optimize their experience and troubleshoot effectively.
Performance and Resource Management
Maximum FVGs to Track : The "Max FVGs to Track" input (defaulting to 25) limits the number of FVG objects processed for each category (e.g., LTF Bullish, MTF Bearish). Increasing this value significantly can impact performance due to more objects being iterated over and potentially drawn, especially when multiple timeframes are active.
Drawing Object Limits : To manage performance, this script sets its own internal limits on the number of drawing objects it displays. While it allows for up to approximately 500 lines (max_lines_count=500) and 500 labels (max_labels_count=500), the number of FVG boxes is deliberately restricted to a maximum of 150 (max_boxes_count=150). This specific limit for boxes is a key performance consideration: displaying too many boxes can significantly slow down the indicator, and a very high number is often not essential for analysis. Enabling all visual elements for many FVGs across all three timeframes can cause the indicator to reach these internal limits, especially the stricter box limit
Optimization Strategies : To help you manage performance, reduce visual clutter, and avoid exceeding drawing limits when using this indicator, I recommend the following strategies:
Maintain or Lower FVG Tracking Count: The "Max FVGs to Track" input defaults to 25. I find this value generally sufficient for effective analysis and balanced performance. You can keep this default or consider reducing it further if you experience performance issues or prefer a less dense FVG display.
Utilize Proximity Filtering: I suggest activating the "Filter Band Width (ATR Multiple)" option (found under "General Settings") to display only those FVGs closer to the current price. From my experience, a value of 5 for the ATR multiple often provides a good starting point for balanced performance, but you should feel free to adjust this based on market volatility and your specific trading needs.
Hide Fully Mitigated FVGs: I strongly recommend enabling the "Hide Fully Mitigated FVGs" option. This setting automatically removes all visual elements of an FVG from the chart once it has been fully mitigated by price. Doing so significantly reduces the number of active drawing objects, lessens computational load, and helps maintain chart clarity by focusing only on active, relevant FVGs.
Disable FVG Display for Unused Timeframes: If you are not actively monitoring certain higher timeframes (MTF or HTF) for FVG analysis, I advise disabling their display by unchecking "Show MTF FVGs" or "Show HTF FVGs" respectively. This can provide a significant performance boost.
Simplify Visual Elements: For active FVGs, consider hiding less critical visual elements if they are not essential for your specific analysis. This could include box labels, borders, or even entire FVG boxes if, for example, only the mitigation lines are of interest for a particular timeframe.
Settings Changes and Platform Limits : This indicator is comprehensive and involves numerous calculations and drawings. When multiple settings are changed rapidly in quick succession, it is possible, on occasion, for TradingView to issue a "Runtime error: modify_study_limit_exceeding" or similar. This can cause the indicator to temporarily stop updating or display errors.
Recommended Approach : When adjusting settings, it is advisable to wait a brief moment (a few seconds) after each significant change. This allows the indicator to reprocess and update on the chart before another change is made
Error Recovery : Should such a runtime error occur, making a minor, different adjustment in the settings (e.g., toggling a checkbox off and then on again) and waiting briefly will typically allow the indicator to recover and resume correct operation. This behavior is related to platform limitations when handling complex scripts with many inputs and drawing objects.
Multi-Timeframe (MTF/HTF) Data and Behavior
HTF FVG Confirmation is Essential: : For an FVG from a higher timeframe (MTF or HTF) to be identified and displayed on your current chart (LTF), the three-bar pattern forming the FVG on that higher timeframe must consist of fully closed bars. The indicator does not draw speculative FVGs based on incomplete/forming bars from higher timeframes.
Data Retrieval and LTF Processing: The indicator may use techniques like lookahead = barmerge.lookahead_on for timely data retrieval from higher timeframes. However, the actual detection of an FVG occurs after all its constituent bars on the HTF have closed.
Appearance Timing on LTF (1 LTF Candle Delay): As a natural consequence of this, an FVG that is confirmed on an HTF (i.e., its third bar closes) will typically become visible on your LTF chart one LTF bar after its confirmation on the HTF.
Example: Assume an FVG forms on a 30-minute chart at 15:30 (i.e., with the close of the 30-minute bar that covers the 15:00-15:30 period). If you are monitoring this FVG on a 15-minute chart, the indicator will detect this newly formed 30-minute FVG while processing the data for the 15-minute bar that starts at 15:30 and closes at 15:45. Therefore, the 30-minute FVG will become visible on your 15-minute chart at the earliest by 15:45 (i.e., with the close of that relevant 15-minute LTF candle). This means the HTF FVG is reflected on the LTF chart with a delay equivalent to one LTF candle.
FVG Detection and Display Logic
Fair Value Gaps (FVGs) on the current chart timeframe (LTF) are detected based on barstate.isconfirmed. This means the three-bar pattern must be complete with closed bars before an FVG is identified. This confirmation method prevents FVGs from being prematurely identified on the forming bar.
Alerts
Alert Setup : To receive alerts from this indicator, you must first ensure you have enabled the specific alert conditions you are interested in within the indicator's own settings (see 'Comprehensive Alert System' under the 'FEATURES' section). Once configured, open TradingView's 'Create Alert' dialog. In the 'Condition' tab, select this indicator's name, and crucially, choose the 'Any alert() function call' option from the dropdown list. This setup allows the indicator to trigger alerts based on the precise event conditions you have activated in its settings
Alert Frequency : Alerts are designed to trigger once per bar close (alert.freq_once_per_bar_close) for the specific event.
User Interface (UI) Tips
Settings Group Icons: In the indicator settings menu, timeframe-specific groups are marked with star icons for easier navigation: 🌟 for LTF (Current Chart Timeframe), 🌟🌟 for MTF (Medium Timeframe), and 🌟🌟🌟 for HTF (High Timeframe).
Dependent Inputs: Some input settings are dependent on others being enabled. These dependencies are visually indicated in the settings menu using symbols like "↳" (dependent setting on the next line), "⟷" (mutually exclusive inline options), or "➜" (directly dependent inline option).
Settings Layout Overview: The indicator settings are organized into logical groups for ease of use. Key global display controls – such as toggles for MTF FVGs, HTF FVGs (along with their respective timeframe selectors), and the Information Panel – are conveniently located at the very top within the '⚙️ General Settings' group. This placement allows for quick access to frequently adjusted settings. Other sections provide detailed customization options for each timeframe (LTF, MTF, HTF), specific FVG components, and alert configurations.
█ FOR Pine Script® CODERS
This section provides a high-level overview of the FVG Premium indicator's internal architecture, data flow, and the interaction between its various library components. It is intended for Pine Script™ programmers who wish to understand the indicator's design, potentially extend its functionality, or learn from its structure.
System Architecture and Modular Design
The indicator is architected moduarly, leveraging several custom libraries to separate concerns and enhance code organization and reusability. Each library has a distinct responsibility:
FvgTypes: Serves as the foundational data definition layer. It defines core User-Defined Types (UDTs) like fvgObject (for storing all attributes of an FVG) and drawSettings (for visual configurations), along with enumerations like tfType.
CommonUtils: Provides utility functions for common tasks like mapping user string inputs (e.g., "Dashed" for line style) to their corresponding Pine Script™ constants (e.g., line.style_dashed) and formatting timeframe strings for display.
FvgCalculations: Contains the core logic for FVG detection (both LTF and MTF/HTF via requestMultiTFBarData), FVG classification (Large FVGs based on ATR), and checking FVG interactions with price (mitigation, partial fill).
FvgObject: Implements an object-oriented approach by attaching methods to the fvgObject UDT. These methods manage the entire visual lifecycle of an FVG on the chart, including drawing, updating based on state changes (e.g., mitigation), and deleting drawing objects. It's responsible for applying the visual configurations defined in drawSettings.
FvgPanel: Manages the creation and dynamic updates of the on-chart information panel, which displays key FVG levels.
The main indicator script acts as the orchestrator, initializing these libraries, managing user inputs, processing data flow between libraries, and handling the main event loop (bar updates) for FVG state management and alerts.
Core Data Flow and FVG Lifecycle Management
The general data flow and FVG lifecycle can be summarized as follows:
Input Processing: User inputs from the "Settings" dialog are read by the main indicator script. Visual style inputs (colors, line styles, etc.) are consolidated into a types.drawSettings object (defined in FvgTypes). Other inputs (timeframes, filter settings, alert toggles) control the behavior of different modules. CommonUtils assists in mapping some string inputs to Pine constants.
FVG Detection:
For the current chart timeframe (LTF), FvgCalculations.detectFvg() identifies potential FVGs based on bar patterns.
For MTF/HTF, the main indicator script calls FvgCalculations.requestMultiTFBarData() to fetch necessary bar data from higher timeframes, then FvgCalculations.detectMultiTFFvg() identifies FVGs.
Newly detected FVGs are instantiated as types.fvgObject and stored in arrays within the main script. These objects also undergo classification (e.g., Large FVG) by FvgCalculations.
State Update & Interaction: On each bar, the main indicator script iterates through active FVG objects to manage their state based on price interaction:
Initially, the main script calls FvgCalculations.fvgInteractionCheck() to efficiently determine if the current bar's price might be interacting with a given FVG.
If a potential interaction is flagged, the main script then invokes methods directly on the fvgObject instance (e.g., updateMitigation(), updatePartialFill(), checkMidlineTouch(), which are part of FvgObject).
These fvgObject methods are responsible for the detailed condition checking and the actual modification of the FVG's state. For instance, the updateMitigation() and updatePartialFill() methods internally utilize specific helper functions from FvgCalculations (like checkMitigation() and checkPartialMitigation()) to confirm the precise nature of the interaction before updating the fvgObject’s state fields (such as isMitigated, currentTop, currentBottom, or isMidlineTouched).
Visual Rendering:
The FvgObject.updateDrawings() method is called for each fvgObject. This method is central to drawing management; it creates, updates, or deletes chart drawings (boxes, lines, labels) based on the FVG's current state, its prev_* (previous bar state) fields for optimization, and the visual settings passed via the drawSettings object.
Information Panel Update: The main indicator script determines the nearest FVG levels, populates a panelData object (defined in FvgPanelLib), and calls FvgPanel.updatePanel() to refresh the on-chart display.
Alert Generation: Based on the updated FVG states and user-enabled alert settings, the main indicator script constructs and triggers alerts using Pine Script's alert() function."
Key Design Considerations
UDT-Centric Design: The fvgObject UDT is pivotal, acting as a stateful container for all information related to a single FVG. Most operations revolve around creating, updating, or querying these objects.
State Management: To optimize drawing updates and manage FVG lifecycles, fvgObject instances store their previous bar's state (e.g., prevIsVisible, prevCurrentTop). The FvgObject.updateDrawings() method uses this to determine if a redraw is necessary, minimizing redundant drawing calls.
Settings Object: A drawSettings object is populated once (or when inputs change) and passed to drawing functions. This avoids repeatedly reading numerous input() values on every bar or within loops, improving performance.
Dynamic Arrays for FVG Storage: Arrays are used to store collections of fvgObject instances, allowing for dynamic management (adding new FVGs, iterating for updates).