Pivot Points + Day First Candle Breakout + VWAP + Supertrend This indicator amalgamates several key indicators to provide a comprehensive analysis for trading decisions, including SuperTrend, Pivot Points, VWAP, along with the Day First Candle Breakout strategy.
Key Features:
Day First Candle Breakout: Identifies potential breakout opportunities based on the first candle of the trading day. It utilizes the high and low of the initial trading range to determine entry points.
Timeframe Selection: Allows users to select the timeframe for analyzing the first candle (e.g., 5, 15, or 60 minutes).
Previous Day and Week High/Low: Displays the high and low of the previous day and week to provide additional context for trading decisions and assess the strength of the trend.
Trend Strength Analysis: Indicates whether the current price is above or below the previous day's high or low, signaling a stronger bullish or bearish trend respectively.
SuperTrend Indicator: Visualizes the trend direction and potential reversal points based on the SuperTrend indicator. It helps traders to stay aligned with the prevailing trend and avoid premature exits.
Pivot Points: Presents key support and resistance levels derived from Pivot Points, assisting traders in identifying potential reversal or breakout zones.
VWAP (Volume Weighted Average Price): Plots VWAP to provide insight into the average price traded over a given period, aiding in determining the fair value of the asset and potential buying/selling zones.
Trading Signals:
Buy Signal: Triggered when the price exceeds the high of the initial trading range after an upward price gap.
Sell Signal: Generated when the price falls below the low of the initial trading range after a downward price gap.
Caveats for Effective Trading:
Extended Trading Ranges: Adjusts support and resistance levels if the initial trading range extends beyond the defined timeframe.
Morning Noise Consideration: Exercises caution during volatile morning sessions to avoid false breakouts and whipsaws.
Pullbacks and Narrow Range Bars: Looks for opportunities during pullbacks or when the price forms narrow range bars to enter trades, reducing the risk of sudden reversals.
In den Scripts nach "pivot" suchen
Pivot-Point Weighted Moving AverageThe Pivot-Point Weighted MA is very different from other weighted MAs, in the sense that the price weights can achieve negative values. For an example, if a length of 21 is used, the pivot point will be calculated as 13, meaning that the 13th prior candle will have 0 weight, and all prices before it will have a negative weight on the sum, so their impact is reversed rather than just unweighted.
The intent of this is to reduce lag by front-loading the prices. It works better in cyclic markets, and with a longer length, where the inflection point (the one with 0 weight) is aligned with the cyclic turn.
You can configure where the weight starts. If you leave it as 0, it will start with floor(length * 0.66) - 1.
PIVOT AND ICHIMOKU BACKGROUND BY PRANOJIT DEYIt shows pivot bias in relation to day open line and it also shows ichimoku bullish trend background. good for option buyers to understand market bias.
Pivot Fib 4H — EAStrategy uses the pivot standard to open position, it has well define entry and exit point with SL, it also has a proper money management plan, maximum 4 trades a day, each trade risk 0.5% of the account, I have it EA version of it also.
Pivot Levels [UkutaLabs]█ OVERVIEW
The Pivot Levels Indicator provides real-time insight into key price levels within the market that can serve as powerful support and resistance levels. These levels are based on currently-relevant price-action information to ensure that the lines being drawn provide the most value to traders regardless of their trading style.
The aim of this script is to simplify the trading experience of users by automatically identifying and displaying price levels that they should be aware of.
█ USAGE
At the beginning of each trading day, the script will identify the previous day’s hlc3 level. We refer to this level as the day’s Source Level, and it is from this price that the other Resistance and Support levels are calculated.
The script then identifies the total price range of the previous day (Previous Day High - Previous Day Low), then draws Resistance and Support lines based on the Source Level and the previous day’s range.
The script identifies these levels on both sides of the Source. Levels above the Source are considered to be points of Resistance and below the Source are considered to be Support, but the levels are free to be interpreted and used in whatever way fits the user’s trading strategy.
A label is drawn at the end of each line that identifies the line and whether it represents support or resistance. These labels can be disabled in the settings.
█ SETTINGS
Configuration
• Show Labels: Determines whether or not labels are displayed at the end of each line.
• Display Mode: Determines the number of days for the script to load.
Line Settings
• Resistance Color: Determines the color of the resistance lines and labels above the Source Level.
• Source Color: Determines the color of the source line and label.
• Support Color: Determines the color of the support lines and labels below the Source Level.
• Line width: Determines the width of lines.
• Line Style: Determines the style of lines.
Pivot Point Oscillator by AlgotrdrThis script tracks moments where price closes over s/r levels on 3 sets of pivot points and turns it into an oscillator to help users analyze price movements at a glance. Enjoy!
Pivot TrackerThis script finds swing lows and swing highs based on input criteria for lookback and lookforward periods, and plots letters accordingly.
Helps identify trend or lacktherof
HH = higher high
LH = lower high
HL = higher low
LL = lower low
Pivot Boss -- Squat bars and Non Squat Bars 2.0Squat Bar Signal -- current Volume is greater than previous volume but Current bar MFI(Market Facilitation index) is lesser than previous bar MFI
Other Conditions -- Current Bars Range is lesser than (Average Range * Range Multiplier)
Non Squat Bar Buy Signal(Green Up Triangle) -- Volume and MFI is greater than previous bar, Close greater than open, Close is greater than midpoint
Non Squat Bar Sell Signal(Red Down Triangle) -- Volume and MFI is greater than previous bar, Close lesser than open, Close is lesser than midpoint
Usually Squat signal is confirmed by Non Squat Bar Signal..
Other indicator used -- PEMA -- Pivot based EMA
For Better results use it along with Advanced Volume indicator and PEMA
pivot semaphore support&resistance levels [LM]Hello Traders,
I would like to introduce you pivot semaphore support&resistance levels. The idea is the same as the zigzag script of mine to spot the importance of support&resistence
The Semafor is used to spot future multi-level Supports and Resistance zones.
It is also useful to spot HL or LL or HH or LH zones at different Depth settings.
The red zones are the extreme places where the market has a higher chance of reversing while the green zones have the lowest setting with lower chances of the market reversal
The lines can be extended like so
The lines also can just stop extending when price will reach it
Enjoy!
Pivot Points [KrisWaters] vX by DGT (Russian version)A useful multitool script from the talented dgtrd with my translation into Russian. Full description from the author.
Полезный скрипт-мультитул от талантливого dgtrd с моим переводом на русский.
Полное описание у автора:
Pivot Points 17 - StandardDisclaimer!
-This indicator doesn't tell you the market condition (BUY or SELL)
Cons!
- Totally dependent on your knowledge
Pros!
- Projects the Key Levels of a single time frame on the chart
Usage!
- Watch out for rejections at these levels
- Identify breakouts at these levels with strong confirmation like RETEST (as Level Role Reversal)
Pivot Reversal Strategy - TimeFramedThis is Pivot Reversal Strategy including the time frames for backtesting.
PPMA - Pivot Point Moving Average by soruPivot Point Moving Average
check it out:) works nicely
In options you can set custom timeframe for indicator values
Cheers
Market State Engine V2# Market State Engine
**Deterministic Confidence-Scoring System for TradingView**
A professional-grade PineScript v5 indicator that scores market conditions from 0-100, helping traders identify high-quality trading opportunities through systematic structure analysis, VWAP positioning, order flow dynamics, and time-based context.
---
## 🎯 Overview
The **Market State Engine** is not a trading bot—it's a **noise-reduction and opportunity-ranking system** designed to filter market conditions and surface only the highest-quality setups.
Instead of blindly taking every signal, this indicator:
- ✅ **Scores** market conditions objectively (0-100 scale)
- ✅ **Filters** out low-probability setups automatically
- ✅ **Classifies** opportunities into A, A+, and A++ grades
- ✅ **Alerts** only on confirmed structure shifts with supporting context
- ✅ **Keeps the human in control** - provides intelligence, not automation
### Philosophy: Reduce Noise. Enforce Discipline. Surface Quality.
---
## 🚀 Key Features
- **Deterministic Scoring** - No black boxes, fully explainable logic
- **Multi-Factor Analysis** - Combines 4 independent market state components
- **Structure-First Approach** - Only alerts on confirmed pivot breaks
- **VWAP Mean Reversion Logic** - Directional filtering based on VWAP zones
- **Order Flow Proxy** - CVD divergence and confirmation detection
- **Session-Aware Scoring** - Prioritizes high-volume New York sessions
- **Alert De-Duplication** - One alert per unique structure shift
- **Zero Repainting** - Uses confirmed pivots only (left=2, right=2)
- **Fully Configurable** - All parameters exposed as inputs
- **Visual Feedback** - VWAP bands, setup labels, and real-time score panel
---
## 📊 Scoring System (0-100)
The Market State Engine evaluates **four independent components**, each contributing up to **25 points** for a maximum total score of **100**.
### 🎯 Component Breakdown
| Component | Max Points | Description |
|-----------|------------|-------------|
| **VWAP Context** | 25 | Measures price deviation from session VWAP |
| **Structure Shift** | 25 | Confirms pivot breakout (HARD GATE) |
| **CVD Alignment** | 25 | Detects order flow divergence/confirmation |
| **Time-of-Day** | 25 | Identifies high-probability trading sessions |
---
### 1️⃣ VWAP Context (Max 25 Points)
**Purpose:** Identifies extreme price deviations from fair value for mean-reversion opportunities.
VWAP (Volume-Weighted Average Price) is calculated session-anchored to New York market time, with standard deviation bands creating zones of opportunity.
#### Band Structure:
- **1st Band**: ±1σ from VWAP (fair value zone)
- **2nd Band**: ±2σ from VWAP (moderate deviation)
- **3rd Band**: ±3σ from VWAP (extreme deviation)
#### Scoring Logic (Exclusive):
```
Price in 3rd VWAP Band (>2σ and ≤3σ) → +25 points
Price in 2nd VWAP Band (>1σ and ≤2σ) → +15 points
Otherwise (inside 1σ or beyond 3σ) → 0 points
```
**Key Insight:** The further price stretches from VWAP, the higher the probability of mean reversion.
---
### 2️⃣ Structure Shift (Max 25 Points) — **HARD GATE**
**Purpose:** Confirms momentum shift through confirmed pivot breakouts.
⚠️ **CRITICAL:** Structure shift is **mandatory**. If no valid structure shift occurs, the **total score becomes 0** regardless of other factors.
#### Detection Method:
Uses TradingView's `ta.pivothigh()` and `ta.pivotlow()` functions with **locked parameters**:
- **Left bars**: 2
- **Right bars**: 2
- **Source**: Configurable (Wick or Body)
- **Break confirmation**: Candle close only
#### Bullish Structure Shift:
- ✅ Prior swing high exists (confirmed pivot)
- ✅ Current candle **closes above** swing high + tick buffer
- ✅ Must occur in VWAP 2nd or 3rd band
- ✅ **VWAP Filter**: Price must be **at or below VWAP** (lower bands)
#### Bearish Structure Shift:
- ✅ Prior swing low exists (confirmed pivot)
- ✅ Current candle **closes below** swing low - tick buffer
- ✅ Must occur in VWAP 2nd or 3rd band
- ✅ **VWAP Filter**: Price must be **at or above VWAP** (upper bands)
#### Scoring:
```
Valid structure shift → +25 points
No structure shift → Total score = 0
```
**Tick Buffer:** Default 5 ticks (configurable) - prevents false breaks from minor price noise.
---
### 3️⃣ CVD Alignment (Max 25 Points)
**Purpose:** Detects institutional order flow through volume delta analysis.
CVD (Cumulative Volume Delta) is a proxy for order flow:
```
Close > Open → +Volume (buying pressure)
Close < Open → -Volume (selling pressure)
```
#### Scoring Logic:
| Condition | Points | Description |
|-----------|--------|-------------|
| **Divergence** | +25 | Price makes higher high + CVD makes lower high (bearish)Price makes lower low + CVD makes higher low (bullish) |
| **Confirmation** | +20 | Price and CVD both make higher highs or lower lows |
| **Neutral** | 0 | No clear divergence or confirmation |
**Lookback Window:** Last 20 bars (configurable) - prevents stale divergences.
**Key Insight:** Divergences suggest weakening momentum, while confirmations validate the trend.
---
### 4️⃣ Time-of-Day Context (Max 25 Points)
**Purpose:** Prioritizes high-volume, high-volatility New York sessions.
#### Scored Sessions (America/New_York timezone):
| Session | Time Range (NY) | Points | Description |
|---------|-----------------|--------|-------------|
| **Pre-Market** | 03:00 - 04:00 | +25 | Early liquidity injection |
| **Market Open** | 09:30 - 11:30 | +25 | Highest volume period |
| **Off-Hours** | All other times | 0 | Lower probability setups |
**Key Insight:** Structure shifts during active sessions have higher follow-through probability.
---
## 🏆 Setup Classification
Setups are graded based on total score thresholds (configurable):
| Grade | Score Range | Typical Components | Quality Level |
|-------|-------------|-------------------|---------------|
| **A++ Setup** | ≥90 | All 4 factors aligned(VWAP 3rd band + Structure + CVD + Session) | Premium - Rare |
| **A+ Setup** | ≥75 | Structure + VWAP + CVD or Session(3 of 4 factors) | High - Select |
| **A Setup** | ≥60 | Structure + VWAP + Session(Minimum viable setup) | Good - Regular |
| **No Grade** | <60 | Insufficient confluence | Filtered out |
**Default Thresholds:**
- A Setup: 60 points
- A+ Setup: 75 points
- A++ Setup: 90 points
---
## 📥 Installation
### Step 1: Download the Indicator
Download the `market_state_engine.pine` file from this repository.
### Step 2: Add to TradingView
1. Open (www.tradingview.com)
2. Open the **Pine Editor** (bottom panel)
3. Click **"New"** → **"Blank indicator"**
4. Delete all default code
5. Paste the contents of `market_state_engine.pine`
6. Click **"Add to Chart"**
### Step 3: Configure for Your Symbol
1. Click the **gear icon** next to the indicator name
2. Adjust **Tick Size** for your instrument:
- ES futures: `0.25`
- NQ futures: `0.25`
- Stocks: `0.01`
3. Save settings
---
## ⚙️ Configuration
### Symbol Settings
| Parameter | Default | Description |
|-----------|---------|-------------|
| **Tick Size** | 0.25 | Minimum price movement for your symbol |
| **Tick Buffer Count** | 5 | Ticks beyond swing for valid break |
### VWAP Settings
| Parameter | Default | Description |
|-----------|---------|-------------|
| **VWAP Band 1 (σ)** | 1.0 | 1st standard deviation multiplier |
| **VWAP Band 2 (σ)** | 2.0 | 2nd standard deviation multiplier |
| **VWAP Band 3 (σ)** | 3.0 | 3rd standard deviation multiplier |
### Session Settings
| Parameter | Default | Description |
|-----------|---------|-------------|
| **Session 1** | 0300-0400 | Pre-market window (NY time) |
| **Session 2** | 0930-1130 | Market open window (NY time) |
### Score Thresholds
| Parameter | Default | Description |
|-----------|---------|-------------|
| **A Setup Threshold** | 60 | Minimum score for A grade |
| **A+ Setup Threshold** | 75 | Minimum score for A+ grade |
| **A++ Setup Threshold** | 90 | Minimum score for A++ grade |
### CVD Settings
| Parameter | Default | Description |
|-----------|---------|-------------|
| **CVD Divergence Lookback** | 20 | Maximum bars for divergence detection |
### Swing Settings
| Parameter | Default | Options | Description |
|-----------|---------|---------|-------------|
| **Swing Detection Method** | Wick | Wick / Body | Use high/low or open/close for pivots |
### Visual Settings
| Parameter | Default | Description |
|-----------|---------|-------------|
| **Show VWAP Bands** | ✅ | Display VWAP and standard deviation bands |
| **Show Setup Labels** | ✅ | Display setup markers on chart |
| **Show Score Panel** | ✅ | Display real-time score breakdown |
---
## 📖 How to Use
### Step 1: Apply to 1-Minute Chart
⚠️ **The indicator is locked to 1-minute timeframe** - do not use on other timeframes.
### Step 2: Understand the Visual Signals
#### Setup Labels
- **Green Triangle (▲)** - Bullish (Long) setup detected
- **Red Triangle (▼)** - Bearish (Short) setup detected
- Label shows **Grade** (A/A+/A++) and **Total Score**
#### VWAP Bands
- **Yellow Line** - Session VWAP (fair value)
- **Blue Bands** - ±1σ (fair value zone)
- **Purple Bands** - ±2σ (moderate deviation)
- **Red Bands** - ±3σ (extreme deviation)
#### Score Panel (Top Right)
Real-time breakdown of all four components:
```
Component Score
VWAP Zone 15/25
Structure 25/25
CVD 20/25
Session 25/25
TOTAL 85/100 (A+)
```
### Step 3: Interpret Signals
#### Valid Long Setup:
✅ Green triangle below candle
✅ Price in **lower VWAP bands** (below VWAP)
✅ Structure shift breaks swing high
✅ Score ≥60
#### Valid Short Setup:
✅ Red triangle above candle
✅ Price in **upper VWAP bands** (above VWAP)
✅ Structure shift breaks swing low
✅ Score ≥60
### Step 4: Set Up Alerts (See Alert Conditions section)
---
## 🚦 Signal Filters (VWAP Zone Logic)
The indicator uses **directional VWAP filtering** to prevent counter-trend signals:
### Long Signals (Green)
**Only allowed when price is AT or BELOW VWAP**
- ✅ Lower 2nd band (-2σ to -1σ)
- ✅ Lower 3rd band (-3σ to -2σ)
- ✅ At VWAP exactly
- ❌ **BLOCKED** in upper bands (above VWAP)
**Logic:** Longs when price is stretched below fair value (mean reversion)
### Short Signals (Red)
**Only allowed when price is AT or ABOVE VWAP**
- ✅ Upper 2nd band (+1σ to +2σ)
- ✅ Upper 3rd band (+2σ to +3σ)
- ✅ At VWAP exactly
- ❌ **BLOCKED** in lower bands (below VWAP)
**Logic:** Shorts when price is stretched above fair value (mean reversion)
---
## 🎨 Visual Elements
### Chart Overlays
| Element | Color | Description |
|---------|-------|-------------|
| **VWAP Line** | Yellow | Session-anchored fair value |
| **±1σ Bands** | Blue | Fair value zone (no score) |
| **±2σ Bands** | Purple | Moderate deviation (15 pts) |
| **±3σ Bands** | Red | Extreme deviation (25 pts) |
| **Swing Highs** | Red ▼ | Confirmed pivot highs |
| **Swing Lows** | Green ▲ | Confirmed pivot lows |
| **Session Background** | Light Green | Active high-value session |
### Setup Labels
**Bullish Setup:**
```
A+
▲ 75
```
Green label below candle, shows grade and score
**Bearish Setup:**
```
A++
▼ 90
```
Red label above candle, shows grade and score
### Score Panel
Real-time table in top-right corner:
- Individual component scores (0-25 each)
- Total score (0-100)
- Current setup grade (A/A+/A++)
- Updates in real-time as market conditions change
---
## 🔔 Alert Conditions
### Setting Up Alerts
#### Method 1: Built-in Alert Conditions
1. Click **"Create Alert"** in TradingView
2. Select **Market State Engine** as condition
3. Choose alert type:
- **Bullish Setup** - Long signals only
- **Bearish Setup** - Short signals only
- **Any Setup** - All signals
4. Set to **"Once Per Bar Close"**
5. Configure notification method (app, email, webhook)
#### Method 2: Custom Alert Message
Alert messages include full breakdown:
```
A+ Setup Detected (Score: 85)
Components: VWAP(25) + Structure(25) + CVD(20) + Time(15)
CVD State: Confirmation
Direction: Long
Timeframe: 1m
```
### Alert Behavior
✅ **One alert per unique pivot break** - no spam
✅ **Fires on candle close only** - no repainting
✅ **Minimum score filter** - only A grade or higher (≥60)
✅ **Direction-specific** - separate bullish/bearish conditions
⚠️ **No cooldown between different pivots** - multiple alerts per session allowed if different swing levels break
---
## 🔧 Technical Details
### Timeframe Lock
- **Required**: 1-minute chart only
- **Reason**: Scoring model calibrated for 1m micro-structure
- **Future**: Multi-timeframe support planned for v2
### Timezone Configuration
- **Hard-coded**: `America/New_York`
- **Session Detection**: Uses TradingView's native session functions
- **Consistency**: All time-based logic uses NY timezone
### Swing Detection Parameters
**Locked to specification:**
- `ta.pivothigh(source, left=2, right=2)`
- `ta.pivotlow(source, left=2, right=2)`
**Implications:**
- Pivots confirmed 2 bars after formation
- No repainting - historical pivots don't move
- 4-bar minimum swing structure (2 left + pivot + 2 right)
### VWAP Calculation
- **Type**: Session-anchored (resets daily)
- **Source**: Typical price `(high + low + close) / 3`
- **Weighting**: Volume-weighted
- **Standard Deviation**: True population standard deviation
### CVD Proxy Formula
```pine
barDelta = close > open ? volume : close < open ? -volume : 0
CVD = cumulative sum of barDelta (session-reset)
```
### Performance Limits
- **Max Labels**: 500 (TradingView limit)
- **Max Bars Back**: 500
- **Memory**: Lightweight - uses only essential variables
---
## 💡 Best Practices
### 1. **Use as a Filter, Not a Strategy**
❌ Don't: Blindly take every signal
✅ Do: Use score as confluence for your existing analysis
### 2. **Higher Grades = Better Probability**
- **A Setups (60-74)**: Regular opportunities, still require discretion
- **A+ Setups (75-89)**: High-quality, multiple factors aligned
- **A++ Setups (90-100)**: Rare premium opportunities, strongest edge
### 3. **Respect the VWAP Zone Filter**
The indicator **automatically blocks**:
- Longs in upper VWAP bands (counter-trend)
- Shorts in lower VWAP bands (counter-trend)
Trust this logic - it enforces mean reversion discipline.
### 4. **Monitor the Score Panel**
Watch which components are scoring to understand **why** a setup formed:
- Missing CVD score? → No order flow confirmation
- Missing Time score? → Outside high-volume sessions
- Low VWAP score? → Weak deviation from fair value
### 5. **Combine with Risk Management**
The indicator provides **opportunity scoring**, not position sizing:
- Use stop losses based on swing structure
- Scale position size with setup grade (larger on A++, smaller on A)
- Set profit targets at VWAP or opposing band
### 6. **Session Awareness**
Prioritize signals during **active sessions**:
- **03:00-04:00 NY**: Pre-market momentum
- **09:30-11:30 NY**: Highest volume, tightest spreads
Off-hours signals (0 time score) are lower probability but still valid if other factors strong.
### 7. **Understand the Hard Gate**
If **no structure shift** occurs:
- Total score = 0
- No alerts fire
- Other components irrelevant
**Why?** Structure shift confirms momentum change - without it, there's no tradable opportunity.
### 8. **Avoid Over-Optimization**
Default settings are well-calibrated:
- Don't chase "perfect" parameters
- Test changes on historical data before live use
- Document any modifications
### 9. **Leverage Alert De-Duplication**
The indicator prevents spam automatically:
- One alert per unique swing break
- New swing levels = new alerts
- No need to manually filter notifications
### 10. **Supplement with Price Action**
Use the indicator alongside:
- Support/resistance levels
- Order flow footprint charts
- Volume profile
- Market internals (breadth, TICK, etc.)
---
## 📚 Example Scenarios
### Example 1: A++ Premium Setup (Score: 95)
```
Price: In lower 3rd VWAP band (-2.8σ) → VWAP: 25 pts
Structure: Close breaks swing high → Structure: 25 pts
CVD: Price LL + CVD HL (bullish div) → CVD: 25 pts
Time: 10:15 AM NY (market open) → Time: 25 pts
Direction: LONG (price below VWAP) → Valid
Grade: A++ (95/100)
```
**Interpretation:** All factors aligned - premium mean-reversion long opportunity.
---
### Example 2: A+ Strong Setup (Score: 80)
```
Price: In upper 2nd VWAP band (+1.5σ) → VWAP: 15 pts
Structure: Close breaks swing low → Structure: 25 pts
CVD: Price HH + CVD LH (bearish div) → CVD: 25 pts
Time: 2:00 PM NY (off-hours) → Time: 0 pts
Direction: SHORT (price above VWAP) → Valid
Grade: A+ (65/100)
```
**Interpretation:** Strong setup despite off-hours, bearish divergence adds confidence.
---
### Example 3: Filtered Setup (Score: 0)
```
Price: In upper 3rd VWAP band (+2.5σ) → VWAP: 25 pts (if allowed)
Structure: Close breaks swing high → Structure: BLOCKED
CVD: Price HH + CVD HH (confirmation) → CVD: 20 pts (if allowed)
Time: 10:00 AM NY → Time: 25 pts (if allowed)
Direction: LONG (price ABOVE VWAP) → ❌ INVALID ZONE
Grade: None (0/100) - NO ALERT
```
**Interpretation:** VWAP filter blocked long signal in upper band - prevents counter-trend trade.
---
## 🛠️ Troubleshooting
### No Signals Appearing
- ✅ Verify you're on **1-minute chart**
- ✅ Check **Tick Size** matches your symbol
- ✅ Ensure **VWAP Bands** are visible
- ✅ Wait for confirmed pivots (requires at least 5 bars of history)
### Alerts Not Firing
- ✅ Confirm alert is set to **"Once Per Bar Close"**
- ✅ Check score threshold (must be ≥60 by default)
- ✅ Verify VWAP zone filter isn't blocking signals
- ✅ Check that structure shift is actually occurring
### Score Always Zero
- ✅ No structure shift detected (hard gate active)
- ✅ Price may not be in valid VWAP zone (2nd or 3rd band)
- ✅ Insufficient swing history (wait for pivots to form)
### Too Many/Too Few Signals
**Too many signals:**
- Increase **A Setup Threshold** (e.g., 70 instead of 60)
- Increase **Tick Buffer Count** (reduces false breaks)
**Too few signals:**
- Decrease **A Setup Threshold** (e.g., 50 instead of 60)
- Decrease **Tick Buffer Count** (more sensitive to breaks)
---
## 📜 License
This indicator is provided under the **Mozilla Public License 2.0**.
---
## 🤝 Credits
Developed as a professional trading tool for systematic opportunity identification.
**Philosophy:** Reduce noise. Enforce discipline. Keep the human in control.
---
## 📞 Support
For questions, issues, or feature requests, please consult:
1. This README documentation
2. The specification document (`pinescript_market_state_engine_spec.docx`)
3. Inline code comments in `market_state_engine.pine`
---
## 🔄 Version History
**v1.0** (Current)
- Initial release
- 4-component scoring model (VWAP + Structure + CVD + Time)
- VWAP zone directional filtering
- Alert de-duplication
- Configurable inputs
- Real-time score panel
- Session-aware logic
---
## 🎓 Understanding the Numbers
### Quick Reference Card
| Score Range | Grade | Quality | Typical Use |
|-------------|-------|---------|-------------|
| 90-100 | A++ | Premium | Highest conviction trades |
| 75-89 | A+ | High | Strong probability setups |
| 60-74 | A | Good | Acceptable with discretion |
| 0-59 | None | Filtered | Skip or wait for confluence |
### Component Contribution Examples
**Minimum A Setup (60 points):**
- Structure (25) + VWAP 3rd band (25) + Time (25) = 75 ✅
**Typical A+ Setup (75 points):**
- Structure (25) + VWAP 2nd band (15) + CVD confirm (20) + Time (25) = 85 ✅
**Maximum A++ Setup (100 points):**
- Structure (25) + VWAP 3rd band (25) + CVD divergence (25) + Time (25) = 100 ✅
---
## 🎯 Final Reminder
**This is NOT a trading bot.**
**This is NOT financial advice.**
**This is a decision-support tool.**
Always:
- ✅ Use proper risk management
- ✅ Understand the logic before trading
- ✅ Backtest on your symbols
- ✅ Keep the human in control
**Happy Trading! 📈**
Liquidity Retest Strategy (Apicode) - TP/SL Lines FixedTechnical Documentation:
1. Purpose and underlying concept
This strategy targets a common behavior in liquid markets: liquidity sweeps around meaningful support/resistance levels, followed by a retest and rejection (reversal) with confirmation.
The core thesis is that many initial “breaks” are not continuation moves, but rather stop-runs and order harvesting. After the sweep, price reclaims the level and closes back on the opposite side, offering a structured entry with defined risk.
The strategy includes:
Support/Resistance detection via pivots
Dynamic selection of the “working” level using an ATR-based proximity window
Rejection validation via candle structure (wick + close)
Optional filters: volume, VWAP-like bias, and EMA trend
Risk management with static TP/SL (ATR-based or %), plus trailing stop (ATR-based or %), with per-trade lines plotted
2. Main components
2.1. Volatility metric: ATR
atr = ta.atr(atrLength) is used in two essential places:
Level selection (proximity to S/R): prevents trading levels that are too far from current price.
Sweep validation (minimum wick size): requires the wick to extend beyond the level by a volatility-relative amount.
Optionally, ATR can also be used for:
Static TP/SL (when usePercent = false)
Trailing stop (when useTrailPercent = false)
2.2. Building S/R levels with pivots
Pivots are detected using:
pivotHigh = ta.pivothigh(pivotLookback, rightBars)
pivotLow = ta.pivotlow(pivotLookback, rightBars)
Each confirmed pivot is stored in arrays:
resistanceLevels for resistance
supportLevels for support
The array size is capped by maxLevels, which reduces noise and manages chart resource usage (lines).
2.3. Selecting the “best” level each bar
On each bar, a single support S and/or resistance R candidate is chosen:
Support: nearest level below price (L < price)
Resistance: nearest level above price (L > price)
Only levels within atr * maxDistATR are considered
This produces dynamic “working levels” that adapt to price location and volatility.
2.4. Rejection pattern (retest + sweep)
After selecting the working level:
Support rejection (long setup)
Conditions:
Low touches/crosses support: low <= S
Close reclaims above: close > S
Bullish candle: close > open
Sufficient wick below the level (liquidity sweep): (S - low) >= atr * minWickATR
This aims to capture a stop sweep below support followed by immediate recovery.
Resistance rejection (short setup)
Symmetric conditions:
High touches/crosses resistance: high >= R
Close rejects back below: close < R
Bearish candle: close < open
Sufficient wick above the level: (high - R) >= atr * minWickATR
2.5. Optional filters
Final signals are the rejection pattern AND enabled filters:
1.- Volume filter
High volume is defined as: volume > SMA(volume, 20) * volMult
When useVolFilter = true, setups require relatively elevated participation
2.- VWAP-like bias filter
A VWAP-like series is computed over vwapLength (typical price weighted by volume)
When useVWAPFilter = true:
- Longs only if close > vwap
- Shorts only if close < vwap
3.- EMA trend filter
Uptrend if EMA(fast) > EMA(slow)
When useTrendFilter = true:
- Longs only in uptrend
- Shorts only in downtrend
2.6. Backtest time window (time filter)
To keep testing focused and reduce long-history noise:
useMaxLookbackDays enables the filter
maxLookbackDays defines how many days back from timenow entries are allowed
Entries are permitted only when time >= startTime.
3. Entry rules and position control
3.1. Entries
strategy.entry('Long', strategy.long) when longSetup and no long position is open
strategy.entry('Short', strategy.short) when shortSetup and no short position is open
No pyramiding is allowed (pyramiding = 0). Position gating is handled by:
Long allowed if strategy.position_size <= 0
Short allowed if strategy.position_size >= 0
4. Risk management: TP/SL and trailing (with plotted lines)
4.1. Detecting entry/exit events
Events are identified via changes in strategy.position_size:
LongEntry: transition into a long
shortEntry: transition into a short
flatExit: transition back to flat
This drives per-trade line creation, updates, and cleanup of state variables.
4.2. Static TP/SL
On entry, entryPrice := strategy.position_avg_price is stored.
Percent mode (usePercent = true)
Long:
staticSL = entryPrice*(1 - slPerc/100)
staticTP = entryPrice*(1 + tpPerc/100)
Short:
staticSL = entryPrice*(1 + slPerc/100)
staticTP = entryPrice*(1 - tpPerc/100)
ATR mode (usePercent = false)
Long:
staticSL = entryPrice - atrAtEntry*slATR
staticTP = entryPrice + atrAtEntry*tpATR
Short:
staticSL = entryPrice + atrAtEntry*slATR
staticTP = entryPrice - atrAtEntry*tpATR
4.3. Trailing stop (custom)
While a position is open, the script tracks the most favorable excursion:
Long: hhSinceEntry = highest high since entry
Short: llSinceEntry = lowest low since entry
A trailing candidate is computed:
Percent trailing (useTrailPercent = true)
Long: trailCandidate = hhSinceEntry*(1 - trailPerc/100)
Short: trailCandidate = llSinceEntry*(1 + trailPerc/100)
ATR trailing (useTrailPercent = false)
Long: trailCandidate = hhSinceEntry - atr*trailATR
Short: trailCandidate = llSinceEntry + atr*trailATR
Then the effective stop is selected:
Long: slUsed = max(staticSL, trailCandidate) when useTrail is enabled
Short: slUsed = min(staticSL, trailCandidate) when useTrail is enabled
If useTrail is disabled, slUsed remains the static stop.
Take profit remains static:
tpUsed = staticTP
Exit orders are issued via:
strategy.exit(..., stop=slUsed, limit=tpUsed)
4.4. Per-trade TP/SL lines
On each entry, two lines are created (SL and TP) via f_createLines().
During the trade, the SL line updates when trailing moves the stop; TP remains fixed.
On exit (flatExit), both lines are finalized on the exit bar and left on the chart as historical references.
This makes it straightforward to visually audit each trade: entry context, intended TP, and trailing evolution until exit.
5. Visualization and debugging
BUY/SELL labels with configurable size (xsize)
Debug mode (showDebug) plots the chosen working support/resistance level each bar
Stored pivot levels are drawn using reusable line slots, projected a fixed 20 bars to the right to keep the chart readable and efficient
6. Parameter guidance and practical notes
pivotLookback / rightBars: controls pivot significance vs responsiveness. Lower rightBars confirms pivots earlier but can increase noise.
maxDistATR: too low may reject valid levels; too high may select distant, less relevant levels.
minWickATR: key quality gate for “real” sweeps. Higher values reduce frequency but often improve signal quality.
Filters:
Volume filter tends to help in ranges and active sessions.
VWAP bias is useful intraday to align trades with session positioning.
EMA trend filter is helpful in directional markets but may remove good mean-reversion setups.
Percent TP/SL: provides consistent behavior across assets with variable volatility, but is less adaptive to sudden regime shifts.
Percent trailing: can capture extensions well; calibrate trailPerc per asset/timeframe (too tight = premature exits).
7. Known limitations
Pivot-derived levels are a heuristic; in strong trends, valid retests may be limited.
The time filter uses timenow; behavior may vary depending on historical context and how the platform evaluates “current time.”
TP/SL and trailing are computed from bar OHLC; in live trading, intrabar sequencing and fills may differ from bar-close simulation.
GIGANEVA V6.61 PublicThis enhanced Fibonacci script for TradingView is a powerful, all-in-one tool that calculates Fibonacci Levels, Fans, Time Pivots, and Golden Pivots on both logarithmic and linear scales. Its ability to compute time pivots via fan intersections and Range interactions, combined with user-friendly features like Bool Fib Right, sets it apart. The script maximizes TradingView’s plotting capabilities, making it a unique and versatile tool for technical analysis across various markets.
1. Overview of the Script
The script appears to be a custom technical analysis tool built for TradingView, improving upon an existing script from TradingView’s Community Scripts. It calculates and plots:
Fibonacci Levels: Standard retracement levels (e.g., 0.236, 0.382, 0.5, 0.618, etc.) based on a user-defined price range.
Fibonacci Fans: Trendlines drawn from a high or low point, radiating at Fibonacci ratios to project potential support/resistance zones.
Time Pivots: Points in time where significant price action is expected, determined by the intersection of Fibonacci Fans or their interaction with key price levels.
Golden Pivots: Specific time pivots calculated when the 0.5 Fibonacci Fan (on a logarithmic or linear scale) intersects with its counterpart.
The script supports both logarithmic and linear price scales, ensuring versatility across different charting preferences. It also includes a feature to extend Fibonacci Fans to the right, regardless of whether the user selects the top or bottom of the range first.
2. Key Components Explained
a) Fibonacci Levels and Fans from Top and Bottom of the "Range"
Fibonacci Levels: These are horizontal lines plotted at standard Fibonacci retracement ratios (e.g., 0.236, 0.382, 0.5, 0.618, etc.) based on a user-defined price range (the "Range"). The Range is typically the distance between a significant high (top) and low (bottom) on the chart.
Example: If the high is $100 and the low is $50, the 0.618 retracement level would be at $80.90 ($50 + 0.618 × $50).
Fibonacci Fans: These are diagonal lines drawn from either the top or bottom of the Range, radiating at Fibonacci ratios (e.g., 0.382, 0.5, 0.618). They project potential dynamic support or resistance zones as price evolves over time.
From Top: Fans drawn downward from the high of the Range.
From Bottom: Fans drawn upward from the low of the Range.
Log and Linear Scale:
Logarithmic Scale: Adjusts price intervals to account for percentage changes, which is useful for assets with large price ranges (e.g., cryptocurrencies or stocks with exponential growth). Fibonacci calculations on a log scale ensure ratios are proportional to percentage moves.
Linear Scale: Uses absolute price differences, suitable for assets with smaller, more stable price ranges.
The script’s ability to plot on both scales makes it adaptable to different markets and user preferences.
b) Time Pivots
Time pivots are points in time where significant price action (e.g., reversals, breakouts) is anticipated. The script calculates these in two ways:
Fans Crossing Each Other:
When two Fibonacci Fans (e.g., one from the top and one from the bottom) intersect, their crossing point represents a potential time pivot. This is because the intersection indicates a convergence of dynamic support/resistance zones, increasing the likelihood of a price reaction.
Example: A 0.618 fan from the top crosses a 0.382 fan from the bottom at a specific bar on the chart, marking that bar as a time pivot.
Fans Crossing Top and Bottom of the Range:
A fan line (e.g., 0.5 fan from the bottom) may intersect the top or bottom price level of the Range at a specific time. This intersection highlights a moment where the fan’s projected support/resistance aligns with a key price level, signaling a potential pivot.
Example: The 0.618 fan from the bottom reaches the top of the Range ($100) at bar 50, marking bar 50 as a time pivot.
c) Golden Pivots
Definition: Golden pivots are a special type of time pivot calculated when the 0.5 Fibonacci Fan on one scale (logarithmic or linear) intersects with the 0.5 fan on the opposite scale (or vice versa).
Significance: The 0.5 level is the midpoint of the Fibonacci sequence and often acts as a critical balance point in price action. When fans at this level cross, it suggests a high-probability moment for a price reversal or significant move.
Example: If the 0.5 fan on a logarithmic scale (drawn from the bottom) crosses the 0.5 fan on a linear scale (drawn from the top) at bar 100, this intersection is labeled a "Golden Pivot" due to its confluence of key Fibonacci levels.
d) Bool Fib Right
This is a user-configurable setting (a boolean input in the script) that extends Fibonacci Fans to the right side of the chart.
Functionality: When enabled, the fans project forward in time, regardless of whether the user selected the top or bottom of the Range first. This ensures consistency in visualization, as the direction of the Range selection (top-to-bottom or bottom-to-top) does not affect the fan’s extension.
Use Case: Traders can use this to project future support/resistance zones without worrying about how they defined the Range, improving usability.
3. Why Is This Code Unique?
Original calculation of Log levels were taken from zekicanozkanli code. Thank you for giving me great Foundation, later modified and applied to Fib fans. The script’s uniqueness stems from its comprehensive integration of Fibonacci-based tools and its optimization for TradingView’s plotting capabilities. Here’s a detailed breakdown:
All-in-One Fibonacci Tool:
Most Fibonacci scripts on TradingView focus on either retracement levels, extensions, or fans.
This script combines:
Fibonacci Levels: Static horizontal lines for retracement and extension.
Fibonacci Fans: Dynamic trendlines for projecting support/resistance.
Time Pivots: Temporal analysis based on fan intersections and Range interactions.
Golden Pivots: Specialized pivots based on 0.5 fan confluences.
By integrating these functions, the script provides a holistic Fibonacci analysis tool, reducing the need for multiple scripts.
Log and Linear Scale Support:
Many Fibonacci tools are designed for linear scales only, which can distort projections for assets with exponential price movements. By supporting both logarithmic and linear scales, the script caters to a wider range of markets (e.g., stocks, forex, crypto) and user preferences.
Time Pivot Calculations:
Calculating time pivots based on fan intersections and Range interactions is a novel feature. Most TradingView scripts focus on price-based Fibonacci levels, not temporal analysis. This adds a predictive element, helping traders anticipate when significant price action might occur.
Golden Pivot Innovation:
The concept of "Golden Pivots" (0.5 fan intersections across scales) is a unique addition. It leverages the symmetry of the 0.5 level and the differences between log and linear scales to identify high-probability pivot points.
Maximized Plot Capabilities:
TradingView imposes limits on the number of plots (lines, labels, etc.) a script can render. This script is coded to fully utilize these limits, ensuring that all Fibonacci levels, fans, pivots, and labels are plotted without exceeding TradingView’s constraints.
This optimization likely involves efficient use of arrays, loops, and conditional plotting to manage resources while delivering a rich visual output.
User-Friendly Features:
The Bool Fib Right option simplifies fan projection, making the tool intuitive even for users who may not consistently select the Range in the same order.
The script’s flexibility in handling top/bottom Range selection enhances usability.
4. Potential Use Cases
Trend Analysis: Traders can use Fibonacci Fans to identify dynamic support/resistance zones in trending markets.
Reversal Trading: Time pivots and Golden Pivots help pinpoint moments for potential price reversals.
Range Trading: Fibonacci Levels provide key price zones for trading within a defined range.
Cross-Market Application: Log/linear scale support makes the script suitable for stocks, forex, commodities, and cryptocurrencies.
The original code was from zekicanozkanli . Thank you for giving me great Foundation.






















