OPEN-SOURCE SCRIPT
تم تحديثه PDH/PDL Liquidity Reversal - 15M Confirmed Close

🔍 Overview
This indicator identifies high-probability reversal setups based on Previous Day High (PDH) and Previous Day Low (PDL) liquidity sweeps. It is designed for use on the 15-minute timeframe, using higher timeframe context from the daily range.
The strategy focuses on capturing false breakouts (liquidity grabs) where price moves beyond a key level, traps traders, and then reverses.
🧠 Core Concept
Markets often:
Break above resistance (PDH) → trigger breakout buyers → reverse down
Break below support (PDL) → trigger breakout sellers → reverse up
This script detects those conditions and signals when a confirmed reversal is likely underway.
⚙️ How It Works
1. Previous Day Levels
Automatically plots:
Previous Day High (PDH)
Previous Day Low (PDL)
These act as key liquidity zones.
2. Liquidity Sweep Detection
Tracks when price:
Moves above PDH
Moves below PDL
This indicates a potential stop hunt or liquidity grab.
3. 15-Minute Confirmation (Critical Rule)
Signals are only generated when:
BUY Setup:
Price sweeps below PDL
A 15M candle closes back above PDL
Optional: candle shows bullish rejection (closes in upper half)
SELL Setup:
Price sweeps above PDH
A 15M candle closes back below PDH
Optional: bearish rejection confirmation
👉 This prevents false signals from wick-only moves.
4. Trade Signals
BUY / SELL markers appear on the chart at the signal candle
Signals are limited to one per direction per day (optional)
Each signal includes:
Entry price (based on candle close)
Stop loss (based on current day extreme + buffer)
Target projection using configurable Risk:Reward
5. Risk & Trade Structure
Stop Loss:
BUY → below current day low
SELL → above current day high
Configurable buffer to avoid premature stop-outs
Minimum Risk:Reward filter (default 1.5R)
6. Smart Trailing Stop (Key Feature)
A structure-based trailing system is included:
Activates only after price reaches +1R
Trails using:
Higher lows (BUY trades)
Lower highs (SELL trades)
Includes ATR-based buffer to avoid tight stop-outs
👉 This allows trades to breathe while still locking in profits.
7. Visual Features
Clear PDH/PDL levels
BUY/SELL markers at confirmed entries
Order info labels (Entry, Stop, Target)
Adjustable label offset to prevent chart clutter
Trailing stop plotted dynamically
⏰ Best Use Cases
15-minute charts
High-liquidity sessions (New York session preferred)
Works across:
Futures (e.g., S&P 500 / Nasdaq-100)
Forex
High-volume stocks
⚠️ Important Notes
This is a confirmation-based system — patience is required
Not all sweeps lead to reversals; filtering is built in
Avoid low-volume or ranging market conditions
🎯 Strategy Objective
To consistently capture high-probability reversals after liquidity sweeps while:
Reducing false entries
Maintaining structured risk management
Allowing winners to run using adaptive trailing stops
This indicator identifies high-probability reversal setups based on Previous Day High (PDH) and Previous Day Low (PDL) liquidity sweeps. It is designed for use on the 15-minute timeframe, using higher timeframe context from the daily range.
The strategy focuses on capturing false breakouts (liquidity grabs) where price moves beyond a key level, traps traders, and then reverses.
🧠 Core Concept
Markets often:
Break above resistance (PDH) → trigger breakout buyers → reverse down
Break below support (PDL) → trigger breakout sellers → reverse up
This script detects those conditions and signals when a confirmed reversal is likely underway.
⚙️ How It Works
1. Previous Day Levels
Automatically plots:
Previous Day High (PDH)
Previous Day Low (PDL)
These act as key liquidity zones.
2. Liquidity Sweep Detection
Tracks when price:
Moves above PDH
Moves below PDL
This indicates a potential stop hunt or liquidity grab.
3. 15-Minute Confirmation (Critical Rule)
Signals are only generated when:
BUY Setup:
Price sweeps below PDL
A 15M candle closes back above PDL
Optional: candle shows bullish rejection (closes in upper half)
SELL Setup:
Price sweeps above PDH
A 15M candle closes back below PDH
Optional: bearish rejection confirmation
👉 This prevents false signals from wick-only moves.
4. Trade Signals
BUY / SELL markers appear on the chart at the signal candle
Signals are limited to one per direction per day (optional)
Each signal includes:
Entry price (based on candle close)
Stop loss (based on current day extreme + buffer)
Target projection using configurable Risk:Reward
5. Risk & Trade Structure
Stop Loss:
BUY → below current day low
SELL → above current day high
Configurable buffer to avoid premature stop-outs
Minimum Risk:Reward filter (default 1.5R)
6. Smart Trailing Stop (Key Feature)
A structure-based trailing system is included:
Activates only after price reaches +1R
Trails using:
Higher lows (BUY trades)
Lower highs (SELL trades)
Includes ATR-based buffer to avoid tight stop-outs
👉 This allows trades to breathe while still locking in profits.
7. Visual Features
Clear PDH/PDL levels
BUY/SELL markers at confirmed entries
Order info labels (Entry, Stop, Target)
Adjustable label offset to prevent chart clutter
Trailing stop plotted dynamically
⏰ Best Use Cases
15-minute charts
High-liquidity sessions (New York session preferred)
Works across:
Futures (e.g., S&P 500 / Nasdaq-100)
Forex
High-volume stocks
⚠️ Important Notes
This is a confirmation-based system — patience is required
Not all sweeps lead to reversals; filtering is built in
Avoid low-volume or ranging market conditions
🎯 Strategy Objective
To consistently capture high-probability reversals after liquidity sweeps while:
Reducing false entries
Maintaining structured risk management
Allowing winners to run using adaptive trailing stops
ملاحظات الأخبار
Updated Indicator Change DescriptionSince the earlier script description, the indicator has been upgraded with several important execution, alert, and visual improvements.
1. Risk/Reward Updated
The default reward target was changed from:
1.5R
to:
2.0R
This means the projected target now uses a 2:1 reward-to-risk model by default.
2. Opposite Signal Blocking Added
The script now prevents conflicting trade alerts.
If currently in a BUY trade:
No SELL signal or SELL alert will trigger
unless:
The buy trade is exited, or a new trading day starts
If currently in a SELL trade:
No BUY signal or BUY alert will trigger
unless:
The sell trade is exited, or a new trading day starts
This keeps the indicator from flipping back and forth while a trade is still active.
3. Trade State Reset on New Day
At the start of each new trading day, the script resets:
BUY/SELL taken status
Sweep detection
Long/short trade state
Entry price
Stop loss
Risk value
Trailing stop values
This gives each trading day a fresh start.
4. Trailing Stop Color Changed
The trailing stop line was changed from separate green/red colors to:
Orange
This makes the trailing stop easier to visually separate from BUY/SELL signals and PDH/PDL levels.
5. NY Session Filter Added
A New York session filter was added.
Default session:
9:30 AM – 12:00 PM New York time
For PDT, this automatically corresponds to:
6:30 AM – 9:00 AM PDT
The script uses:
America/New_York
so TradingView handles daylight savings automatically.
When enabled, BUY/SELL signals only trigger during the selected NY session.
6. Near PDH/PDL Alerts Added
The script now includes early-warning alerts when price approaches:
Previous Day High
Previous Day Low
Default near-distance setting:
0.15%
This helps you prepare before the actual sweep-and-close confirmation occurs.
Example use:
Price is near PDL → prepare for possible sweep below PDL → wait for 15M close back above PDL
7. Near-Level Visual Markers Added
Small orange circle markers were added to show when price is near:
PDH
PDL
These are not trade entries. They are preparation alerts only.
The actual trade entry still requires:
15M candle close confirmation
8. Script Structure Clarified
The script now needs to follow this order:
1. indicator()
2. inputs
3. trade state variables
4. PDH / PDL calculation
5. session logic
6. near PDH / PDL logic
7. sweep detection
8. buy/sell confirmation logic
9. plotting
10. alerts
This prevents errors like:
Undeclared identifier
or:
Mismatched input
Updated Summary
The indicator is now a more complete NY-session PDH/PDL liquidity sweep system with:
15M candle close confirmation
2R target projection
active trade conflict protection
orange structure trailing stop
NY-only signal filtering
early Near PDH/PDL alerts
cleaner visual chart markers
ملاحظات الأخبار
🚀 Major Enhancements (Latest Update)⭐ 1. A+ Scoring System (Primary Upgrade)
Each setup is now scored based on multiple conditions:
Proximity to PDH/PDL
Sweep quality (true liquidity grab vs drift)
Strength of 15M close
Session timing (NY open)
RSI momentum confirmation (optional)
📊 Output:
Score: 0–10
Grade: A+ / A / B / SKIP
🎯 Interpretation:
8–10 → A+ (Trade)
7 → A (High Watch)
5–6 → B (Low Priority)
<5 → Skip
🧠 Benefit:
👉 Filters out weak setups automatically
👉 Focuses trader on top 10–20% of opportunities
👉 Reduces overtrading and emotional decisions
🖥️ 2. Large On-Chart Score Panel
A dynamic panel displays:
Setup Score: 8/10 A+
Color-coded:
Green → A+
Lime → A
Orange → B
Red → Skip
🧠 Benefit:
👉 Instant clarity—no guesswork
👉 Eliminates hesitation during live trading
👉 Keeps focus on quality setups
🏷️ 3. A+, A, B Labels on Trade Signals
Every BUY/SELL signal now includes:
BUY A+
Score: 9/10
or
SELL B
Score: 5/10
🧠 Benefit:
👉 Immediate quality classification at entry
👉 Helps reinforce discipline (“only trade A+”)
👉 Useful for journaling and performance tracking
🔔 4. “Only Alert If A+” Filtering
Alerts can now be restricted to:
Score ≥ A+ threshold (default = 8)
🧠 Benefit:
👉 Eliminates alert noise
👉 Only notifies you of high-probability setups
👉 Turns watchlist into a passive opportunity feed
🕒 5. NY Session Filter (Time-Based Edge)
Default trading window:
9:30 AM – 12:00 PM New York
Automatically adjusts for:
EST / EDT
Your local timezone (e.g., PDT)
🧠 Benefit:
👉 Focuses on highest liquidity period
👉 Avoids low-probability midday chop
👉 Aligns with institutional activity
📍 6. Near PDH/PDL Early Warning Alerts
Indicator now identifies when price is approaching key levels before a setup forms.
🧠 Benefit:
👉 Gives trader time to prepare
👉 Improves anticipation vs reaction
👉 Reduces missed opportunities
🔁 7. Trade State Management (Conflict Protection)
Blocks opposite signals while in a trade
Resets cleanly at the start of each new day
🧠 Benefit:
👉 Prevents signal flipping
👉 Enforces structured trade management
👉 Improves consistency
🔶 8. Structure-Based Trailing Stop (Orange Line)
Trailing stop:
Activates after +1R
Follows 15M structure (higher lows / lower highs)
Includes ATR buffer
🧠 Benefit:
👉 Avoids premature stop-outs
👉 Lets winning trades run
👉 Adapts to volatility
🎯 9. Risk/Reward Optimization
Default target now:
2.0R (2:1 Reward-to-Risk)
🧠 Benefit:
👉 Improves expectancy
👉 Requires fewer winning trades to be profitable
📊 How It Works with Your Watchlist
Your workflow:
1. Load curated watchlist (20–25 high-quality stocks)
2. Scan charts quickly
3. Let scoring system evaluate setups
4. Focus only on A+ opportunities
5. Execute with confirmation + risk structure
🧠 Benefit:
👉 Converts large watchlist → small actionable set
👉 Improves speed and efficiency
👉 Eliminates analysis paralysis
🧠 Key Advantage of This Version
This indicator no longer just says:
“Here is a setup”
It now says:
“This is a high-quality setup worth trading”
⚠️ Important Notes
This is a confirmation-based system → patience required
Not every sweep results in a trade
Best used during NY session
Designed for:
Stocks
Futures
Forex (major pairs)
🎯 Final Outcome for the Trader
With this upgraded version, the trader gains:
Fewer trades
Higher-quality setups
Clear decision-making framework
Reduced emotional trading
Improved consistency over time
🚀 Summary
This is now a:
Liquidity Sweep + Confirmation + Scoring System
Designed to:
👉 Identify
👉 Filter
👉 Prioritize
👉 Execute
Only the best opportunities in the market.
ملاحظات الأخبار
Summary of Latest Indicator ChangesThe indicator has been upgraded from a single-symbol A+ scoring tool into a multi-symbol scanner and alert system.
It now supports a 10-symbol scanner list, where:
Symbols 1–4 = Core 4
Symbols 5–10 = Rotating 6
Your Core 4 are placed in positions 1 through 4:
1. NVDA
2. TSLA
3. AAPL
4. MSFT
The remaining 6 positions are used for daily rotating symbols based on volume, relative volume, gap, and daily movement.
The main benefit is that you no longer need to manually watch every chart. The scanner can monitor your selected symbols and alert you when an A+ BUY or A+ SELL setup appears.
Detailed Description of Changes
1. Multi-Symbol Scanner Mode Added
A new Scanner Mode was added to the indicator.
This allows the script to monitor up to 10 symbols from inside one TradingView chart.
The scanner evaluates each symbol using the same core logic:
PDH/PDL level
Liquidity sweep
15M candle close confirmation
A+ scoring system
NY session filter
RSI confirmation if enabled
2. Core 4 Symbols Added to Positions 1–4
The first four scanner slots are now reserved for the strongest core symbols:
Symbol 1: NVDA
Symbol 2: TSLA
Symbol 3: AAPL
Symbol 4: MSFT
These are kept in the scanner every day because they usually provide:
High liquidity
Strong intraday range
Institutional participation
Clean PDH/PDL reactions
Strong alignment with NQ / tech-led market movement
3. Rotating 6 Symbols Added to Positions 5–10
The remaining six scanner slots are used for daily rotation.
These should be changed based on which stocks are most active that day.
The Rotating 6 should be selected using:
Relative Volume
Volume
% Change
Gap %
Daily range potential
News or catalyst
This gives the scanner flexibility while still keeping the watchlist high quality.
4. One Alert Can Monitor Multiple Symbols
The scanner uses alert() calls so TradingView can trigger alerts from multiple symbols inside the scanner module.
This allows one alert condition:
Any alert() function call
to notify you when any scanner symbol produces an A+ setup.
Example alert:
A+ BUY: NVDA | Score: 9/10 | TF: 15
or
A+ SELL: TSLA | Score: 8/10 | TF: 15
5. Scanner Timeframe Added
A scanner timeframe input was added.
Default:
15 minutes
This matches your execution model because the system requires a confirmed 15M candle close.
6. Scanner Uses the Same A+ Scoring Logic
Each scanned symbol is scored using the same 10-point model:
Near PDH/PDL
Sweep quality
Strong candle close
NY session timing
RSI confirmation
Only symbols that meet the A+ threshold trigger alerts.
Default A+ threshold:
8/10
7. Core Workflow Updated
Your workflow is now:
Core 4 stay fixed
Rotating 6 change daily
Scanner monitors all 10
Only A+ setups trigger alerts
Trader opens chart and confirms visually
This reduces screen time and keeps your attention on only the best setups.
Benefit to the Trader
This update provides several major benefits:
Less manual chart flipping
Faster awareness of A+ setups
Better focus on high-quality symbols
Reduced overtrading
Cleaner daily workflow
More consistent execution
The indicator now works as both:
A chart-based execution tool
and
A multi-symbol opportunity scanner
The Core 4 give you a stable foundation, while the Rotating 6 let you adapt to the strongest movers each day.
ملاحظات الأخبار
Latest Update:📘 Update: Unified Trade Labels + Direction-Based Color Logic
Summary
This update replaced the previous dual-label system with a single combined execution label and introduced direction-based color coding.
Previously, the indicator created:
Trade Quality Label
+
Order Information Label
at the same chart location.
This caused:
overlapping labels
hidden text
unreadable chart areas
color confusion (SELL A+ appearing green)
The update merges those into one professional trade label.
🔧 What Changed
1. Combined Multiple Labels Into One
The indicator previously generated:
Label 1
BUY A+
Score: 9/10
Label 2
BUY ORDER
Entry
Stop
Target
Those labels occupied the same coordinates.
Now both were merged into:
BUY A+
Score: 9/10
Entry
Stop
Target
Only one label is created.
2. Direction-Based Color System Added
The old logic colored labels based on score.
Example:
SELL A+
appeared:
🟢 Green
which looked incorrect.
Now color is determined by:
BUY → Green family
SELL → Red family
Score determines intensity.
🎨 New Label Color Logic
BUY Labels
BUY A+ → Strong Green
BUY A → Medium Green
BUY B → Light Green
BUY SKIP → Gray
SELL Labels
SELL A+ → Strong Red
SELL A → Medium Red
SELL B → Light Red
SELL SKIP → Gray
📊 Label Content Now Includes
Every signal label displays:
Direction
Score
Entry
Stop
Target
Example:
SELL A+
Score: 8/10
Entry: 110.80
Stop: 111.10
Target 2R: 110.20
🧠 Benefit to the Trader
This update improves:
✅ Decision Speed
Direction is immediately visible.
✅ Reduced Visual Clutter
Only one label instead of stacked labels.
✅ Faster Trade Recognition
BUY = Green
SELL = Red
No interpretation required.
✅ Better Execution Confidence
All important information appears together.
✅ Cleaner Historical Review
Past signals become easier to evaluate.
🧠 Impact on Your Workflow
Before:
Score Label
+
Order Label
=
Clutter
Now:
One Label
=
One Decision
🎯 Final Result
This update transformed the indicator from:
Signal Generator
into a more polished:
Trade Decision Interface
where:
Direction
+
Quality
+
Risk
+
Reward
are visible instantly from a single label.
ملاحظات الأخبار
Latest Update:Removed Setup Label on upper right of chart as it was redundant.
ملاحظات الأخبار
The indicator is designed to be non-repainting. It uses previous-day confirmed levels, 15-minute candle close confirmation, and lookahead_off in higher-timeframe requests. Signals should not appear historically using future data.ملاحظات الأخبار
Updated to include Mid-Line of the PDH & PDLملاحظات الأخبار
📘 Update: Custom Session PDH / PDL Engine + Midline StabilitySummary
The indicator’s Previous Day High (PDH) and Previous Day Low (PDL) logic was redesigned to eliminate level shifting during the trading session.
Previously, PDH/PDL were derived from:
request.security(..., "D", ...)
This caused levels to sometimes:
Update at day rollover
Then shift again several candles later
especially on:
Futures
Extended-hours charts
Mixed session markets
The indicator now calculates PDH/PDL using a custom session-based engine.
Result:
One session
One PDH
One PDL
One Midline
🔧 What Changed
1. Replaced Daily request.security() PDH/PDL Logic
Previous method
Used:
request.security(
syminfo.tickerid,
"D",
high[1]
)
and
request.security(
syminfo.tickerid,
"D",
low[1]
)
Issue:
Session rollovers caused double updates
New method
Builds:
Current session high
Current session low
Stores completed session
Uses that as PDH/PDL
Benefit:
Stable levels
More consistent behavior
2. Added Session Inputs for PDH / PDL
New inputs added:
PDH/PDL Session
PDH/PDL Timezone
Examples:
Stocks:
0930–1600
America/New_York
Futures:
1800–1700
America/New_York
Benefit:
Levels now match the actual market traded
3. Midline (Yellow Line) Fully Integrated
Added:
PD Midline
=
(PDH + PDL) / 2
Displayed as:
🟡 Yellow
Benefit:
Visual equilibrium reference
Potential trail activation reference
4. Restored Near PDH / Near PDL Alerts
These were preserved:
nearDistance
nearPDH
nearPDL
Additional protection added:
not na(pdh)
not na(pdl)
Benefit:
Prevents alert failures
Prevents invalid scoring
5. Reduced Repaint Risk
Earlier you changed:
lookahead_on
→
lookahead_off
This update complements that.
Result:
Previous session fixed
Confirmed levels only
Lower repaint behavior
📊 Before vs After
Feature Before After
PDH/PDL Source Daily request.security Session-based
Mid-session shifts Possible Reduced
Futures behavior Inconsistent Improved
Midline None Added
Near Alerts Existing Preserved
Repaint Risk Low Lower
🧠 Benefit to the Trader
This update improves:
✅ Confidence
PDH/PDL no longer appear to “move.”
✅ Cleaner Sweep Detection
False sweeps should reduce.
✅ Better A+ Scoring Inputs
Scoring now references more stable levels.
✅ More Reliable Paper Testing
You can trust historical chart behavior more.
✅ Better Multi-Market Support
Stocks, futures, and forex behave more consistently.
🎯 Result
The indicator now treats:
Previous Day Levels
=
Session-defined market structure
instead of:
Calendar day boundaries
ملاحظات الأخبار
📘 Latest Indicator Update SummaryThese latest edits significantly improved the indicator’s:
Chart clarity
Session consistency
Trade visualization
Non-repainting reliability
Execution usability
The indicator is evolving from a development/debugging tool into a much cleaner and more professional trading interface.
🔧 Changes Implemented
1. Custom Session-Based PDH / PDL Engine Added
Previous Behavior
The indicator originally used:
request.security(..., "D", ...)
to calculate Previous Day High and Previous Day Low.
This caused issues where:
PDH/PDL changed twice
Levels shifted intraday
Futures sessions behaved inconsistently
especially on:
Futures
Extended-hours charts
Session rollover periods
New Behavior
The indicator now:
Tracks the active session high/low
Stores the completed session values
Uses them as PDH/PDL
using custom session logic.
New Inputs Added
PDH/PDL Session
PDH/PDL Timezone
Examples:
Stocks
0930-1600
America/New_York
Futures
1800-1700
America/New_York
Benefits
✅ PDH/PDL update only once
✅ Better futures behavior
✅ Cleaner session transitions
✅ More accurate market structure
✅ Lower repaint risk
2. PDH / PDL Midline Added
A new midpoint line was introduced:
(PDH + PDL) / 2
Displayed as:
🟡 Yellow
Purpose
The midpoint provides:
✅ Market equilibrium reference
✅ Additional structure guidance
✅ Potential future trailing-stop logic
✅ Better visual balance on chart
3. Near PDH / Near PDL Logic Preserved
The Near PDH / PDL alert system was retained.
These calculations remain active:
nearDistance
nearPDH
nearPDL
Additional protections added:
not na(pdh)
not na(pdl)
to prevent invalid signals before session initialization.
4. Non-Repainting Improvements
The indicator previously used:
lookahead = barmerge.lookahead_on
This was replaced with:
lookahead = barmerge.lookahead_off
in all applicable locations.
Result
Signals are now based on:
Confirmed previous session data
Confirmed 15M candle closes
Confirmed completed bars
This significantly reduces repaint behavior.
5. Removed Redundant Visual Elements
Several development/debugging visuals were cleaned up.
Removed Orange Dot Markers
The orange dots were determined to provide little decision-making value and mainly cluttered the chart.
Benefits:
✅ Cleaner candles
✅ Faster chart reading
✅ Less visual distraction
Removed Separate “15M CLOSE” Bubble
Previously:
BUY
15M CLOSE
was displayed separately from the execution label.
This became redundant because the combined label already implies:
15M candle confirmation completed
Benefits:
✅ Less duplication
✅ Cleaner signal visualization
✅ Simpler historical review
6. Combined Execution Label Enhanced
The combined execution label now contains:
Direction
Grade
Score
Entry
Stop
Target
Example:
BUY A+
Score: 9/10
Entry
Stop
Target 2R
7. Direction-Based Color System Added
BUY labels now use:
🟢 Green family
SELL labels now use:
🔴 Red family
Score quality changes shade intensity.
Examples
BUY
A+ = Dark Green
A = Medium Green
B = Light Green
SELL
A+ = Dark Red
A = Medium Red
B = Light Red
8. Execution Labels Repositioned Near Trade Levels
Execution labels were moved closer to the actual market structure levels:
BUY labels
Placed near:
🟢 PDL (green line)
SELL labels
Placed near:
🔴 PDH (red line)
instead of floating far above/below price.
Benefits
✅ Cleaner appearance
✅ Faster trade recognition
✅ Better visual relationship to structure
✅ More professional chart layout
📊 Overall Effect of These Updates
The indicator now provides:
Cleaner chart structure
Better futures compatibility
More stable PDH/PDL behavior
Reduced repaint risk
Improved trade visualization
Faster decision-making
Lower chart clutter
🧠 Current Indicator State
The indicator has evolved from:
Development / Debugging Tool
into:
Professional Trade Decision Interface
focused on:
Liquidity sweeps
15M confirmation
A+ setup filtering
Risk-defined execution
Cleaner chart readability
ملاحظات الأخبار
📘 Indicator Update SummaryObjective
Improve:
Chart readability
Trade identification
Signal clarity
Market structure visibility
Decision speed
while reducing:
Visual clutter
Overlapping labels
Information duplication
1. Added Custom Session-Based PDH / PDL Engine
Problem
The original PDH/PDL calculation was causing:
Double updates
Session rollover shifts
Inconsistent futures behavior
especially on:
Futures
Extended-hours markets
Non-equity instruments
Solution
Implemented:
CUSTOM SESSION PREVIOUS HIGH / LOW
which now:
Tracks session highs/lows
Stores completed session values
Uses them as PDH/PDL
Benefit
✅ More stable PDH/PDL
✅ Better futures compatibility
✅ Reduced repaint concerns
✅ Cleaner market structure
2. Added PDH / PDL Midline
A new yellow midpoint was added:
(PDH + PDL) ÷ 2
Displayed as:
🟡 Yellow
Benefit
Provides:
Market equilibrium
Structure reference
Additional trade context
without adding complexity.
3. Preserved Near PDH / Near PDL Alert Logic
The following remain active:
nearDistance
nearPDH
nearPDL
Additional protections were added to prevent:
Invalid calculations
Missing PDH/PDL values
Benefit
✅ Keeps A+ scoring intact
✅ Supports scanner functionality
✅ Improves alert reliability
4. Reduced Repainting Risk
Previously:
lookahead_on
was replaced with:
lookahead_off
throughout the script.
Benefit
Signals now rely on:
Confirmed bars
Confirmed closes
Completed session data
which makes historical testing much more trustworthy.
5. Removed Visual Clutter
Removed Orange Dot Markers
These dots were originally useful during development but no longer provided meaningful trade information.
Result
Cleaner charts.
Removed 15M CLOSE Bubble Labels
Previously:
BUY
15M CLOSE
and
SELL
15M CLOSE
appeared separately.
These were redundant because the trade signal itself already implies a confirmed close.
Result
Less duplication.
Faster chart reading.
6. Added BUY / SELL Trigger Arrows
New section:
BUY / SELL TRIGGER ARROWS
Displays:
Green Up Arrow
Red Down Arrow
on the exact trigger candle.
Benefit
Immediately identifies:
Where trade triggered
without requiring a large label.
7. Added Trade Information Table
New section:
TRADE INFO TABLE
Displays:
Trade Direction
Grade
Score
Entry
Stop
Target
RR
Example:
SELL A+
Score 8/10
Entry 35.76
Stop 37.31
Target 32.66
RR 2R
Benefit
Provides all trade information in a fixed location.
No longer covers candles.
No longer shifts with zoom level.
8. Moved Trade Details Away From Price Action
The trade table was positioned:
Bottom Right
after testing.
This proved superior to:
Top Left
Top Right
Middle Right
because it avoids:
Ticker Name
OHLC Data
Buy/Sell Buttons
Indicator Controls
while remaining visible.
9. Improved Overall Chart Layout
Current layout:
PDH (Red)
PDL (Green)
Midline (Yellow)
BUY Arrow
SELL Arrow
Trailing Stop
Trade Info Table
This creates a cleaner separation between:
Market Structure
Trade Trigger
Trade Management
Trade Information
📊 Result of the Latest Updates
Before
Multiple labels
Debug markers
Overlapping information
Chart clutter
After
Clean market structure
Clear trigger arrows
Fixed trade information panel
Improved readability
Professional layout
ملاحظات الأخبار
📘 Indicator Update Summary – Active Trade Status PanelThis update transformed the Trade Info Table from a historical signal display into a true Active Trade Management Panel.
The goal was to ensure the table reflects the current state of the trade rather than continuing to display information from a trade that has already completed.
🎯 Objective
Previously:
Trade triggers
↓
Table populates
↓
Trade stops out
↓
Table still shows old trade
This could create confusion because the chart appeared to have an active position when none existed.
🔧 Changes Implemented
1. Automatic Table Reset on Trade Exit
The following exit conditions now trigger a table reset:
Long Trade Exit
When:
Price touches or breaches Long Trailing Stop
the system now:
Closes Long Trade State
Clears Trade Information
Resets Table Variables
Short Trade Exit
When:
Price touches or breaches Short Trailing Stop
the system now:
Closes Short Trade State
Clears Trade Information
Resets Table Variables
2. Added "No Active Trade" State
A new trade status condition was introduced.
When no active trade exists:
lastTradeDirection == ""
the table displays:
Trade
No Active Trade
instead of showing outdated trade information.
📊 Table Behavior Before vs After
Previous Behavior
Trade Triggered
BUY A+
Score 8/10
Entry
Stop
Target
Trade Stopped Out
BUY A+
Score 8/10
Entry
Stop
Target
(Still displayed)
This could lead to:
Confusion
False assumption of active position
Chart clutter
New Behavior
Trade Triggered
BUY A+
Score 8/10
Entry
Stop
Target
RR 2R
Trade Completed
Trade
No Active Trade
🧠 Benefits
Improved Situational Awareness
The table now answers:
Do I currently have an active trade?
at a glance.
Reduced Confusion
No more:
Old signals appearing active
Stale trade information
Better Live Trading Experience
The panel now behaves more like:
Professional Trade Dashboard
instead of:
Historical Signal Display
Cleaner Chart Workflow
You can now quickly determine:
Active Position
Table populated
No Position
No Active Trade
without inspecting the chart.
📈 Overall Impact
This update completes the transition of the Trade Info Table from a:
Signal Notification Tool
to a:
Live Trade Management Panel
The indicator now provides:
✅ PDH / PDL Market Structure
✅ Midline Reference
✅ A+ Signal Identification
✅ Entry / Stop / Target Information
✅ Trailing Stop Management
✅ Active Trade Status Monitoring
✅ Automatic Trade Completion Detection
This is a meaningful usability improvement because it reduces cognitive load and allows you to focus on finding the next valid setup rather than determining whether the previous trade is still active.
ملاحظات الأخبار
The Problem We DiscoveredWhen you enabled:
Reset This Chart Display
the table correctly changed to:
No Active Trade
However, when you turned it back off, the old trade immediately returned.
Why?
Because Pine Script reprocesses all historical bars every time the indicator recalculates.
The script was essentially doing this:
Load Chart
↓
Read Historical Bars
↓
Find Old BUY A+ Signal
↓
Rebuild Trade Table
↓
Rebuild Trade State
So the reset wasn't failing.
The historical signal was simply being rediscovered.
What We Added
We added:
resetAfterTime = input.time(...)
and
allowSignalsAfterReset = time >= resetAfterTime
Then wrapped the signal generation:
finalBuySignal =
allowSignalsAfterReset and
canBuy and
validBuyRisk
finalSellSignal =
allowSignalsAfterReset and
canSell and
validSellRisk
What This Does
Instead of trying to erase history, we tell the indicator:
Ignore all signals before this date/time.
Example:
Current Time = June 5, 2026 09:00
Any BUY or SELL signal generated before:
June 5, 2026 09:00
is ignored.
The indicator behaves as if those trades never happened.
Why This Is Better
Old Method
Clear variables
↓
Indicator reloads
↓
Old signal found again
↓
Trade returns
New Method
Indicator reloads
↓
Old signal found
↓
Signal timestamp checked
↓
Too old
↓
Ignored
The trade never gets rebuilt.
Benefits
1. Clears One Chart Only
You specifically wanted:
Clear the chart I am viewing
Do NOT affect all charts
This accomplishes exactly that.
Each chart can have its own:
Ignore Signals Before This Time
value.
2. Preserves Future Trades
The indicator continues operating normally from the reset point forward.
New BUY and SELL signals still work.
Alerts still work.
Trade panel still works.
Trailing stop still works.
3. Cleaner Watchlist Workflow
This is especially useful when you open:
Scanner Candidate
↓
Old signal from 2 days ago
↓
Trade panel clutter
Now you can simply:
Reset to Current Time
and begin evaluating only fresh setups.
Practical Use Case
Tomorrow morning:
Open VECO
Old BUY from yesterday
Instead of removing/readding the indicator:
Set Ignore Signals Before This Time
= Now
Result:
Old BUY disappears
Trade panel clears
Only new signals are shown
Overall Assessment
This is one of the cleaner quality-of-life improvements we've added.
It does not change the trading logic.
It does not affect scoring.
It does not affect alerts.
It simply gives you a way to tell the indicator:
"Start fresh from this point forward on this chart."
For someone working through scanner candidates every day, that's much more practical than constantly removing and reapplying the indicator.
ملاحظات الأخبار
PDH/PDL Liquidity Reversal IndicatorEngineering Change Record (ECR)
ECR-0005
Trade Persistence & Panel Clearing Logic Fix
Date: July 2, 2026
Status: Verified
Background
During live market testing of Version 2 of the PDH/PDL Liquidity Reversal Indicator, several charts continued displaying completed trades long after those trades should have been considered inactive.
Although the original design intentionally allowed an active trade to remain visible until either:
the 2R profit target was achieved, or
the stop loss was reached,
testing revealed an unintended consequence.
When a previous trade remained active, the Trade Information Panel became "locked" to that trade and prevented any new signals from being displayed.
Symptoms Observed
During live trading the following behaviors were observed:
1. Previous trades remained on screen
Charts continued displaying:
BUY A+
SELL A+
Entry
Stop
Target
Score
even though a completely different market setup had already developed.
2. New A+ signals appeared missing
Several stocks appeared to have no current trade information.
Example:
JACK
Initially displayed the previous day's BUY trade.
After that BUY trade finally stopped out, the panel immediately revealed:
SELL A+ (8/10)
This confirmed the SELL setup had actually existed but had been hidden behind the previous BUY.
3. Manual Clear option ineffective
A "Clear Trade" setting had previously been added.
Testing showed:
Clearing temporarily removed the trade.
As soon as the setting was turned OFF,
the previous trade immediately returned.
Therefore the Clear function was only cosmetic and not actually resetting the indicator state.
Root Cause Analysis
The indicator stored the current trade using persistent (var) variables.
Examples:
lastTradeDirection
lastTradeGrade
lastTradeEntry
lastTradeStop
lastTradeTarget
These variables were intentionally preserved from one bar to the next.
However, when the trade was cleared, only the display table was being refreshed.
The underlying persistent variables were never reset.
Therefore, on the next calculation the indicator simply rebuilt the Trade Panel from the old stored values.
In effect:
Trade Panel
↑
Persistent Variables
↑
Never Cleared
The display could be cleared.
The stored trade could not.
Corrective Action
The indicator was modified to separate two different operations:
1. Reset the stored trade
The persistent trade variables are now explicitly cleared.
Example:
lastTradeDirection := ""
lastTradeGrade := ""
lastTradeScore := na
lastTradeEntry := na
lastTradeStop := na
lastTradeTarget := na
lastTradeColor := color.gray
This removes the trade from memory.
2. Clear the displayed panel
Separately, the Trade Information Table is rebuilt with:
Trade
No Active Trade
and blank rows.
The display now accurately reflects the internal state.
Additional Compiler Issue
While implementing the reset logic an additional problem occurred.
The reset code was initially inserted before the variables were declared.
This produced compiler errors such as:
Undeclared identifier
lastTradeDirection
The solution was to move the reset logic below the variable declarations while leaving the daily reset logic near the beginning of the script.
This maintains proper variable scope and execution order.
Verification Testing
Testing was performed using live market data.
Test Case 1
Instrument
JACK
Initial State
Previous BUY trade remained visible.
Action
Price eventually crossed the stop loss.
Expected Result
Old BUY trade removed.
Actual Result
PASS
BUY trade disappeared.
Test Case 2
Immediately after the previous BUY cleared:
The indicator displayed:
SELL A+
Score 8/10
This proved:
the SELL setup already existed,
but had previously been hidden.
Result
PASS
Test Case 3
Subsequent live testing
Multiple symbols were monitored after market open.
Old trades cleared correctly.
New trades appeared normally.
Result
PASS
Operational Impact
This correction significantly improves indicator behavior.
Before:
Old Trade
↓
Locks Panel
↓
New Setup Hidden
After:
Old Trade Ends
↓
Trade State Reset
↓
Panel Cleared
↓
New Signal Immediately Visible
Benefits
The modification provides several important improvements:
Eliminates stale trade information.
Prevents previous trades from masking new opportunities.
Allows one trade lifecycle to complete cleanly before the next begins.
Ensures the Trade Information Panel accurately reflects the current market state.
Improves confidence in live trading by reducing operator confusion.
Establishes a clean state machine for future enhancements.
Lessons Learned
This issue reinforced an important engineering principle:
A visual display should never be treated as the source of truth. The display is only a representation of the underlying state.
By resetting both the stored trade state and the displayed panel independently, the indicator now behaves consistently and predictably.
ملاحظات الأخبار
v2.4.0 – Performance Optimization Release- Removed internal multi-symbol scanner module.
- Reduced request.security() load.
- Preserved PDH/PDL, scoring, trade panel, alerts, and trade-state clearing logic.
نص برمجي مفتوح المصدر
بروح TradingView الحقيقية، قام مبتكر هذا النص البرمجي بجعله مفتوح المصدر، بحيث يمكن للمتداولين مراجعة وظائفه والتحقق منها. شكرا للمؤلف! بينما يمكنك استخدامه مجانًا، تذكر أن إعادة نشر الكود يخضع لقواعد الموقع الخاصة بنا.
إخلاء المسؤولية
لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.
نص برمجي مفتوح المصدر
بروح TradingView الحقيقية، قام مبتكر هذا النص البرمجي بجعله مفتوح المصدر، بحيث يمكن للمتداولين مراجعة وظائفه والتحقق منها. شكرا للمؤلف! بينما يمكنك استخدامه مجانًا، تذكر أن إعادة نشر الكود يخضع لقواعد الموقع الخاصة بنا.
إخلاء المسؤولية
لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.