Failed 2U/2D + 50% Retrace Scanner📈 Multi-Ticker Failed 2U/2D Scanner with Daily Retrace & Market Breadth Table
This TradingView indicator is a multi-symbol price action scanner designed to catch high-probability reversal signals using The Strat’s failed 2U/2D patterns and daily 50% retrace logic, while also displaying market breadth metrics ( USI:TICK and USI:ADD ) for context.
Monitored Symbols:
SPY, SPX, QQQ, IWM, NVDA, AMD, AAPL, META, MSTR
🔍 Detection Logic
1. Failed 2U / Failed 2D Setups
Failed 2U: Price breaks above the previous candle’s high but closes back below the open → Bearish reversal
Failed 2D: Price breaks below the previous candle’s low but closes back above the open → Bullish reversal
Timeframes Monitored:
🕐 1-Hour (1H)
⏰ 4-Hour (4H)
2. Daily 50% Candle Retrace
Checks if price has retraced 50% or more of the previous day’s candle body
Highlights potential trend exhaustion or reversal confluence
3. Market Breadth Metrics (Display Only)
USI:TICK : Measures real-time NYSE up vs. down ticks
USI:ADD : Advance-Decline Line (net advancing stocks)
Not used in signal logic — just displayed in the table for overall market context
🖼️ Visual Elements
✅ Chart Markers
🔺 Red/Green Arrows for 1H Failed 2U/2D
🟨 Yellow Squares for 4H Failed 2U/2D
Visual markers are plotted directly on the relevant candles
📊 Signal Table
Lists all 9 tickers in rows
Columns for:
1H Signal
4H Signal
Daily 50% Retrace
USI:TICK Value
USI:ADD Value
Color-Coded Cells:
🔴 Red = Failed 2U
🟢 Green = Failed 2D
⚠️ Highlight if 50% Daily Retrace condition is true
🟦 Neutral-colored cells for TICK/ADD numeric display
🔔 Alerts
Hardcoded alerts fire when:
A 1H or 4H Failed 2U/2D is detected
The Daily 50% retrace condition is met
Each alert is labeled clearly by symbol and timeframe:
"META 4H Failed 2D"
"AAPL Daily 50% Retrace"
🎯 Use Case
Built for:
Reversal traders using The Strat
Swing or intraday traders watching hourly setups
Traders wanting quick visual context on market breadth without relying on it for confirmation
Monitoring multiple tickers in one clean view
This is scan 2
Add scan 1 for spx, spy, iwm, qqq, aapl
This indicator is not financial advice. Use the alerts to check out chart and when tickers trigger.
Candlestick analysis
Impulsive Candle Detector TRW [3-in-1]Impulsive Candle Detector
Description: professor Michael impulsive candle but 3 -1 code by me
The Impulsive Candle Detector is a powerful tool designed to identify and highlight three different types of impulsive candles on your TradingView chart—all in a single, customizable indicator. Each impulsive candle type uses its own configurable settings, allowing traders to easily visualize various market dynamics without crowding their charts with multiple indicators.
How it works:
The indicator detects “impulsive” candles based on custom thresholds for candle range, volume, and body-to-wick ratio.
Each of the three types is independently configurable with its own parameters (length for averages, size multiplier, volume multiplier, body ratio, and color).
When an impulsive candle is detected, the corresponding bar is colored and can optionally display a label above the candle indicating its type.
Separate alerts can be set for each impulsive candle type, enabling you to react to different market conditions instantly.
Features:
Three independent impulsive candle detection types, all in one indicator
Adjustable settings for each type (range, volume, body ratio, and color)
Clean, uncluttered chart view
Custom bar coloring and optional labels for instant visual recognition
Supports individual alert notifications for each impulsive candle type
Perfect for:
Traders looking to spot strong market moves or volatility spikes
Those who want to monitor multiple impulsive candle patterns without overlapping indicators
Anyone who values clean and customizable charting solutions
Percent Change IndicatorThe Percent Change Indicator helps you see how much the price of an asset has changed over a specific number of bars (or candles) on the chart. You get to decide how many bars to look back — for example, the last 10 candles. The indicator takes the current closing price and compares it to the closing price from 10 bars ago, then calculates the percentage difference between the two.
If the price has increased, the indicator shows a positive value and displays it in green. If the price has dropped, the value is negative and shown in red. A horizontal zero line helps you quickly see whether the market is gaining or losing value over the selected period.
On your chart, this indicator appears as a line that moves up or down with the price trend. It updates in real time and works on all timeframes — so whether you're trading on the 1-minute chart or analyzing the daily chart, it always tells you how much the price has changed over the number of bars you chose.
This tool is especially useful for spotting trends, measuring price momentum, or identifying when the market is starting to reverse direction.
SHYY-TFC-Horizontal V2SHYY-TFC-Horizontal V2 – Multi-Timeframe Clarity for The Strat Traders
SHYY-TFC-Horizontal V2 is a powerful, clean, and efficient overlay designed for serious traders who use Rob Smith’s The Strat.
This real-time table gives you instant visual insight across all key timeframes – from 5 minutes to monthly – with:
Candle direction (bullish, bearish, neutral)
Strat bar type (1, 2U, 2D, 3)
Live countdown to bar close
Compact horizontal layout that saves space and enhances clarity
Fully customizable table position to fit any chart setup
Built with no lookahead bias, this version meets TradingView’s script publishing standards and is optimized for actionable, real-time decisions.
Ideal for:
Scalpers who need fast confirmation
Swing traders aligning entries with time frame continuity
Price action traders following The Strat methodology
Trade with confidence. See the full picture. React faster.
SHYY-TFC-Horizontal V2 – built to make you faster, sharper, and more in control.
Metatron Lines (Highs & Lows Geometry)Metatron Lines
Hey TradingView community! 👋
I wanted to share something I've been working on that might help you see market structure from a different angle. This indicator connects pivot highs and lows using geometric patterns, creating what I call "Metatron Lines."
What it does (simply put):
- Finds significant highs and lows on your chart
- Draws lines connecting these points to reveal hidden geometric relationships
- Shows you the underlying structure that price tends to respect
Why I built this:
I noticed that markets often move in patterns that aren't immediately obvious. Sometimes the most important levels aren't the obvious support and resistance lines, but the intersections and angles created by connecting multiple pivot points. This tool helps visualize those relationships.
How it might help you:
- Pattern Recognition : Spot geometric formations that traditional analysis might miss
- Support/Resistance : See where multiple geometric lines converge to create strong levels
- Market Structure : Better understand how price flows and where it might find obstacles
- Confluence Areas : Identify zones where multiple geometric elements align
A few honest thoughts:
This isn't a magic bullet or a guaranteed profit maker (nothing is!). It's simply another lens through which to view price action. Some traders find geometric analysis helpful, others prefer different approaches - and that's perfectly fine.
I've tried to make it customizable so you can adjust it to fit your trading style and timeframe. The default settings work well for most instruments, but feel free to experiment.
Settings you can adjust:
- Pivot detection sensitivity
- Number of connection points
- Line colors and styles
- Which connections to show (highs, lows, or both)
I hope some of you find this useful! I'm always learning from this community, so if you have suggestions for improvements or different ways to use it, I'd love to hear them.
Trade safe and trust your process! 📈
---
This indicator is provided as-is for educational and analysis purposes. Please practice proper risk management and never risk more than you can afford to lose.
Pivot Liquidity Sweep [scalpmeister]📌 Pivot Liquidity Sweep
Scalp-oriented, liquidity sweep-based advanced signal and strategy indicator.
This indicator analyzes the price's sweeping of significant pivot levels and the subsequent breakouts to generate long/short signals based on different logics. It is sensitive to both classic sweep logic and strong reversal candles. Additionally, it visually marks liquidity gathering zones, offering excellent opportunities especially for scalp and intraday traders.
⚙️ Features and Strategy Types
🟢 Automatic Pivot Detection:
Pivot high/low levels are detected and stored based on the number of left and right bars.
🔴 Sweep Detection (Stop Hunt):
If the price violates a pivot level with a wick and closes inside, it is considered a sweep (liquidity cleaning). Strategies activate after this sweep.
🧠 5 Different Signal Styles:
SweepBreak:
It is expected that the extreme (high/low) level of the sweeping candle is broken with a close.
PivotBreak:
After the sweep, the first newly formed pivot in the trend direction is expected to break. (It is dynamically determined and drawn on the chart.)
StrongSweep:
It is sufficient if the candle following the sweep surpasses the previous candle with a single candle. No additional breakout is expected.
StrongCandle:
Strong momentum candles measured with a special RSI calculation are taken into account. It considers strong opposite-direction candles formed shortly after a pivot sweep.
ReversalCandleSweep:
Reversal candles that close in the opposite direction after a sweep (e.g., a red close on a sweep candle formed at the top or a green close at the bottom) are directly considered as signals.
📐 Technical Details:
Signals are triggered only once (triggered control).
Sweep lines (green/red), Long and Short lines (Orange)
Strong candles are filtered using an RSI-momentum-based measurement system (StrongCandle).
Sweep and breakout zones are dynamically invalidated. That is, if the zones are violated by the price, the signals and lines are automatically canceled.
🎯 Who Should Use It?
Professional traders working with liquidity zones
Scalp and intraday strategy practitioners
Those focused on stop hunts, sweeps, and reversal zones
🔔 Alert Support:
Sweep High / Low Alert
Long / Short Signal Alert
Inside Bar Detector - 15min
🔍 What is an Inside Bar?
An **Inside Bar** is a candle that forms **entirely within the high and low of the previous candle**. It represents **consolidation**, **indecision**, or **potential reversal**, and is a key signal in The Strat trading method.
🔧 What the Script Does:
1. **Timeframe Restriction**:
* The script activates **only on the 15-minute timeframe**, avoiding clutter on other timeframes.
2. **Inside Bar Logic**:
* It checks whether the **current bar’s high is lower than the previous bar’s high**, **AND** the **current bar’s low is higher than the previous bar’s low**.
* If both conditions are true, it confirms an Inside Bar.
3. **Visual Display**:
* When an Inside Bar is detected, the script **plots a yellow label ("1") above the bar**.
* The label represents the Strat 1-bar and helps you easily spot potential setups.
🎯 Use Case:
* Ideal for **Strat traders**, **price action analysts**, or **any trader** looking for breakout or reversal opportunities.
* Common setups include **1-2**, **1-3**, or **double inside bar** breakouts.
Mark specific candle (e.g. bar 20)This Pine Script indicator, "Mark specific candle (e.g. bar 20)" (short title "Mark candle"), is a simple yet powerful tool to visually highlight a particular candle on your chart.
What it does:
It marks a specific candle (e.g., the 20th, 10th, or any number you choose) counting backwards from the most recent candle on your chart. The marked candle will be colored in a subtle light grey and also feature a tiny, matching grey arrow pointing down from above it.
Why it's useful:
This indicator helps you quickly identify and track a consistent reference point in recent price action. It's great for strategies that depend on fixed look-back periods or for simply keeping an eye on a specific historical candle's position as new data comes in.
Key Features:
Adjustable Candle Number: Easily change which candle is marked (e.g., 20th, 10th, 5th) directly from the indicator settings using the "Candle Number to Mark (from end)" input.
Clear Visuals: Both the candle color and a small arrow provide a subtle, yet effective, visual cue.
How to use:
Simply add this script to your TradingView chart. Then, open the indicator's settings to set your desired candle number.
Bias Bar Coloring + Multi-Timeframe Bias Table + AlertsMulti-Timeframe Bias Bar Coloring with Alerts & Table
This indicator provides a powerful, visual way to assess price action bias across multiple timeframes—Monthly, Weekly, and Daily—while also coloring each bar based on the current chart’s bias.
Features:
Persistent Bar Coloring: Bars are colored green for bullish bias (close above previous high), red for bearish bias (close below previous low), and persist the last color if neither condition is met. This makes trend shifts and momentum easy to spot at a glance.
Bias Change Alerts: Get notified instantly when the bias flips from bullish to bearish or vice versa, helping you stay on top of potential trade setups or risk management decisions.
Multi-Timeframe Bias Table: A table anchored in the top right corner displays the current bias for the Monthly, Weekly, and Daily charts, color-coded for quick reference. This gives you a clear view of higher timeframe context while trading any chart.
Consistent Logic: The same objective bias logic is used for all timeframes, ensuring clarity and reliability in your analysis.
How to Use:
Use the bar colors for instant visual feedback on trend and momentum shifts.
Watch the top-right table to align your trades with higher timeframe bias, improving your edge and filtering out lower-probability setups.
Set alerts to be notified of bias changes, so you never miss a potential opportunity.
This tool is ideal for traders who value multi-timeframe analysis, want clear visual cues for trend direction, and appreciate having actionable alerts and context at their fingertips.
Hidden Orderblock,HOB,OB,BB,MT,MTF Hidden Order Block & Breaker Block (HOB/BB) Multi-Timeframe Analysis
A powerful tool for Smart Money traders and ICT-style practitioners seeking precision, confluence, and clean visual execution. This indicator identifies institutional price zones such as Hidden Order Blocks (HOB), Breaker Blocks (BB), Partial Hidden Order Blocks (PHOB), and traditional Order Blocks (OB)—all across multiple timeframes with minimal chart clutter.
✅ Key Features
1. Hidden Order Block (HOB) Detection
Identifies non-obvious order blocks often hidden within price action.
Requires the EQ (Equilibrium) of the block to pass through at least one Fair Value Gap (FVG).
Invalidation Rule: If price touches the EQ and then closes beyond it (depending on structure), the HOB is invalidated.
2. Breaker Block (BB) Detection
Highlights zones where price made a liquidity grab followed by a strong reversal.
Useful for anticipating support/resistance flips and high-probability reaction areas.
3. Partial Hidden Order Block (PHOB) Detection
A variation of HOBs where price only partially touches the EQ.
Often acts as an early warning zone for reversals or continuation.
Less strict than HOBs, but still institutionally relevant.
4. Traditional Order Block (OB) Detection
Identifies bullish/bearish OBs based on engulfing patterns and displacement.
Marks only the body of the engulfing candle, with the EQ line acting as a key validation/invalidation level.
Once the EQ is touched, the OB is considered invalidated.
5. Engulfing Filter Engine
Customizable logic for OB qualification.
“Easy Engulfing Mode” simplifies detection for newer traders or faster workflow.
Fine-tune aggressiveness and visual clarity with user-defined settings.
6. Multi-Timeframe (MTF) Visualization
Overlay OBs, HOBs, BBs, and PHOBs from higher timeframes (e.g., 4H, 1D) on lower timeframes (15m, 1H).
Enhances top-down confluence without switching charts.
Keeps the visual experience clean and intuitive.
7. Minimalist Visual Design
Only the zone boundaries and EQ lines are displayed.
No extra noise—perfect for both scalpers and swing traders.
Dynamic label positioning and styling for improved chart aesthetics.
8. Performance-Optimized Code
Lightweight, real-time rendering.
Designed for responsiveness—even on lower timeframes with dense historical data.
⚙️ How It Works (Simplified Logic)
Order Block Detection:
Scans for engulfing candles that show displacement.
Defines the OB as the body of the engulfing candle.
EQ line is marked and projected forward until invalidated.
Hidden Order Block Logic:
Starts from a traditional OB, but requires the EQ to pass through at least one FVG.
Upon a close beyond the EQ in the opposite direction, the HOB is invalidated.
PHOB Logic:
Similar to HOBs, but allows partial touches of the EQ before reacting.
Breaker Block Logic:
Identifies liquidity sweeps followed by impulsive moves.
Marks these zones as BBs for potential reaction areas.
📈 Use Cases
Detect institutional price zones with high precision.
Simplify decision-making with visual EQs and MTF overlays.
Integrate seamlessly into:
Smart Money Concepts (SMC)
ICT-style trading
Wyckoff methodology
Discretionary zone-to-zone strategies
🧠 Definitions Summary
OB (Order Block):
Engulfed candle body; EQ is the midpoint of the body. Invalid once EQ is touched.
HOB (Hidden Order Block):
Like OB, but EQ must pass through at least one FVG.
Invalidated when a candle touches EQ and closes beyond it.
PHOB (Partial Hidden Order Block):
Like HOB, but allows partial touch of the EQ to remain valid.
Data Monitoring TableThis is a visual data dashboard specifically designed for users engaged in quantitative trading and technical analysis. It is equipped with two data tables that can dynamically display key market technical indicators and cryptocurrency price fluctuation data, supporting customizable column configurations and trading mode filtering.
✅ Core Features:
Intuitive display of critical technical indicators, including the Relative Strength Index (RSI), K-line entity gain, upper/lower shadow ratio, trading volume level, and change rate.
Multi-timeframe tracking of price fluctuations for BTC/ETH/SOL/XRP/DOGE (1-day, 6-hour, 3-hour).
Selectable trading modes: "long-only", "short-only", or "both".
Customizable number of columns to adapt to analysis needs across different timeframes.
All data is visualized in tables with color-coded prompts for market conditions (overbought, oversold, high volatility, low volatility, etc.).
📈 Target Audience:
Investors seeking systematic access to technical data.
Quantitative strategy developers aiming to capture market structural changes.
Intermediate and beginner traders looking to enhance market intuition and decision-making.
New Feature:
We have added a trading volume monitoring grade setting feature. Users can set the monitoring grade by themselves. When the market trading volume reaches this grade, the system will trigger an alarm. The default setting is level 5. This setting is designed to filter out trades with small fluctuations, helping users to capture key trading signals more accurately and improve the efficiency of trading decisions.
中文介绍
这是一款专为量化交易和技术分析用户设计的可视化数据仪表盘。它配备两个数据表格,可动态展示关键市场技术指标与加密货币价格波动数据,支持自定义列配置和交易模式筛选。
✅ 核心功能:
直观展示相对强弱指标(RSI)、K 线实体涨幅、上下影线比例、成交量水平及变化率等关键技术指标。
多时间框架追踪 BTC/ETH/SOL/XRP/DOGE 价格波动(1 日、6 小时、3 小时)。
可选交易模式:“仅做多”“仅做空” 或 “多空双向”。
可自定义列数,适配不同时间框架的分析需求。
所有数据以表格可视化呈现,通过颜色标注提示市场状况(超买、超卖、高波动、低波动等)。
📈 目标用户:
寻求系统获取技术数据的投资者。
旨在捕捉市场结构变化的量化策略开发者。
希望提升市场洞察力和决策能力的初、中级交易者。
新增功能:
我们新增了成交量监控等级设置功能。用户可自行设定监控等级,当市场成交量达到该等级时,系统将触发警报。默认设置为 5 级,此设置旨在过滤掉小幅波动的交易,帮助用户更精准地捕捉关键交易信号,提升交易决策效率。
Supply/Demand Zones (Synthetic SMA Candles)Supply/Demand Zones (Synthetic SMA Candles)
Created by The_Forex_Steward
This indicator highlights institutional-style supply and demand zones using synthetic SMA-based candles rather than raw price data. It provides a smoother, more refined view of price action to help identify key imbalance areas where price is likely to react.
Features:
- Uses SMA-smoothed synthetic candles to detect bullish and bearish engulfing structures
- Draws demand zones after bullish breakouts and supply zones after bearish breakouts
- Zones are persistent for a customizable number of bars
- Mitigated zones can optionally be removed from the chart
- Includes alerts for breakout and mitigation events
- Optional plotting of synthetic candles over price for visual clarity
How It Works:
When a synthetic candle closes above the high of a previous bearish candle, a bullish engulfing is detected, and a demand zone is created from that bearish candle’s high and low. Conversely, when price closes below the low of a previous bullish candle, a supply zone is formed. These zones stay on the chart for the user-defined duration or until they are mitigated by price, at which point they can be removed automatically.
How to Use:
- Adjust the SMA Length to control how smooth the synthetic candles appear
- Enable or disable Show Supply Zones and Show Demand Zones as needed
- Set the Zone Duration to control how long each zone persists
- Use Delete Mitigated Zones to automatically remove zones when price returns to them
- Optionally enable Show Synthetic SMA Candles to see the candle logic used in detection
- Use the built-in alerts to stay notified of new zone creation or mitigation
Note: This tool is most effective when combined with structure or trend-based strategies for confirmation.
Unified Sentiment Candles Overlay (SMA)Unified Sentiment Candles (SMA) Indicator
The Unified Sentiment Candles (SMA) is a custom overlay indicator designed to provide a smoothed visualization of market sentiment by plotting synthetic candles based on the Simple Moving Average (SMA) of open, high, low, and close prices. It helps traders identify trend direction and potential reversals more clearly.
How to Use:
- Observe Candle Colors: Green candles indicate bullish sentiment (close ≥ open), while red candles suggest bearish sentiment (close < open).
- Trend Identification: Consistent green candles point to an uptrend, whereas consistent red candles may signal a downtrend.
- Support & Resistance Zones: The SMA-based candles smooth out short-term volatility, assisting in spotting key support and resistance levels.
- Entry & Exit Signals: Look for color changes or candle pattern formations within the synthetic candles to time entries and exits more effectively.
Settings:
SMA Length : Adjust this parameter to control the smoothing period. A shorter length makes the indicator more responsive, while a longer length smooths out more noise.
This indicator is best used in conjunction with other technical analysis tools to confirm signals and improve trading accuracy.
This script is open-source and licensed under the Mozilla Public License 2.0. Use and modify it at your own discretion.
Directional Change Extremes by CR86Подтверждение сигналов в индкаторе Directional Change происходит на основе алгоритма отката цены (sigma), заданного как процент от предыдущего экстремума. Процесс следующий:
Поиск вершины (Top): Изначально индикатор ищет максимум (tmp_max). Когда цена откатывает ниже текущего максимума на величину sigma (например, close < tmp_max - tmp_max * sigma), вершина подтверждается, и сигнал Top фиксируется. Это запускает поиск основания.
Поиск основания (Bottom): После подтверждения вершины минимальная цена (tmp_min) обновляется. Когда цена растет выше текущего минимума на sigma (например, close > tmp_min + tmp_min * sigma), основание подтверждается, и сигнал Bottom фиксируется. Это переключает индикатор обратно к поиску вершины.
Условия: Подтверждение происходит только при закрытии бара, что обеспечивает стабильность сигнала. Метки "Confirm" появляются на баре, где выполнено условие отката.
Пример: Если tmp_max = 1000 и sigma = 0.031, подтверждение Top произойдет, когда цена упадет ниже 969 (1000 * 0.969).
English
Signal confirmation in the Directional Change indicator is based on a price retracement algorithm (sigma) defined as a percentage of the previous extreme. The process is as follows:
Top Detection: The indicator initially seeks a maximum (tmp_max). A top is confirmed when the price retraces below the current maximum by sigma (e.g., close < tmp_max - tmp_max * sigma), triggering a Top signal. This shifts the focus to bottom detection.
Bottom Detection: After a top is confirmed, the minimum price (tmp_min) is updated. A bottom is confirmed when the price rises above the current minimum by sigma (e.g., close > tmp_min + tmp_min * sigma), triggering a Bottom signal. This switches the indicator back to seeking a top.
Conditions: Confirmation occurs only on bar close, ensuring signal stability. "Confirm" labels appear on the bar where the retracement condition is met.
Example: If tmp_max = 1000 and sigma = 0.031, a Top is confirmed when the price drops below 969 (1000 * 0.969).
Stephis Supply & Demand Zones v3
📉 Support
Definition: Support is a price level where a downtrend can be expected to pause or reverse due to a concentration of buying interest.
Why it matters: When the price of an asset falls to a support level, traders expect buyers to step in, preventing the price from falling further.
Visual clue: On a chart, support often appears as a horizontal line where the price has bounced up multiple times.
📈 Demand
Definition: Demand refers to the willingness and ability of buyers to purchase an asset at a given price.
In trading context: High demand typically pushes prices up, while low demand can lead to price drops.
Relation to support: A support level exists because of demand—buyers are willing to buy at that price, creating a floor.
🧠 How They Work Together
When price approaches a support level, traders watch to see if demand increases—if it does, the price may bounce.
If the support level is broken, it may signal that demand has weakened, and the price could fall further.
🔁 Opposite Concept: Resistance & Supply
Resistance is the opposite of support—it's a level where selling pressure (supply) may stop a price from rising.
Just like demand creates support, supply creates resistance.
Valid Pullbacks [keypoems]Valid Pullbacks
This indicator marks Valid Pullbacks on a chart. The core of the script is designed to find significant swing points by maintaining and validating candidate highs and lows.
Notice this is very different than other swing marker (fractals or otherwise). This is the base used to draw DTFX/Supply and Demand Zones. I am starting a full rewrite of all the components of my market structure indicator and this is part 1.
Core Concepts
The script operates in a stateful manner, alternating between searching for a Valid Pullback High and a Valid Pullback Low.
Initial State: At the beginning, the script assumes it is searching for the first Valid Pullback High.
Alternating Search: Once a Valid Pullback High is confirmed, the script switches its state to search for a Valid Pullback Low. Conversely, after a Valid Pullback Low is confirmed, it begins searching for a Valid Pullback High. This ensures a proper sequence of alternating swing points.
Defining a Swing Point
The script uses two primary ways to define a swing point, depending on user settings:
Wick-Based Swing (Default):
A Swing High occurs when the high of a candle is higher than the high of the candle immediately before and after it. (high > high and high > high )
A Swing Low occurs when the low of a candle is lower than the low of the candle immediately before and after it. (low < low and low < low )
Close-Based Swing:
A Swing High is identified based on a more complex relationship involving the closes and highs/opens of the three most recent candles, requiring the swing point to be formed by an "up-close" candle.
A Swing Low is identified similarly, requiring the swing point to be formed by a "down-close" candle.
* The Logic
This logic to update the internal state runs on every bar of the chart to update the status of candidate highs and lows.
1. Candidate Selection
The script continuously searches for the best possible candidate for the next valid swing.
Searching for a Candidate High:
This happens only if the last confirmed swing was a Valid Pullback Low (or at the very start).
On every new bar, the script checks if the previous bar represents a better candidate than the current one.
A "better" candidate is one with a higher price. The specific price checked (high or close) depends on whether the close-based or wick-based definition of a swing is being used.
If a better candidate is found, it replaces the existing candidateHigh. The candidate's price is always recorded as the high of that bar.
Searching for a Candidate Low:
This happens only if the last confirmed swing was a Valid Pullback High.
The logic is the mirror opposite of the high search. It looks for a "better" candidate with a lower price on every new bar.
If a better candidate is found, it replaces the existing candidateLow. The candidate's price is always recorded as the low of that bar.
2. Candidate Confirmation
Once a candidate is being tracked, the script waits for a specific market action to confirm it as a Valid swing.
Confirming a Valid Pullback High:
A candidateHigh is confirmed and becomes a Valid Pullback High if the price breaks below the low of the candidate bar.
When this happens:
The candidateHigh is stored in the validHighs array.
Both the candidateHigh and candidateLow are completely reset.
The script's state switches to now search for a Valid Pullback Low.
Confirming a Valid Pullback Low:
A candidateLow is confirmed and becomes a Valid Pullback Low if the price breaks above the high of the candidate bar.
When this happens:
The candidateLow is stored in the validLows array.
Both the candidateLow and candidateHigh are completely reset.
The script's state switches to now search for a Valid Pullback High.
This continuous process of searching, updating, and confirming candidates allows the script to dynamically identify and plot the most recent and relevant valid swing points on the chart.