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! 📈**
Candlestick analysis
Pro Structure: Precision MSS/BOS & Extended FVG1. Precision Structure Mapping (BOS & MSS) Unlike standard ZigZag indicators that just connect pivots, this script visualizes the exact "Break" point:
MSS (Market Structure Shift): Displayed as a Thick Solid Line. This signals a potential trend reversal (e.g., breaking a Lower High in a downtrend).
BOS (Break of Structure): Displayed as a Thin Dashed Line. This signals trend continuation in the current direction.
Visual Logic: The lines originate exactly from the Swing Pivot and terminate exactly at the candle that closes beyond that pivot, providing instant visual confirmation of the break.
2. Trend-Filtered Fair Value Gaps (FVG) To reduce "Analysis Paralysis," this indicator uses an active trend filter:
Bullish Trend: Only Bullish FVGs (Green) are highlighted. Bearish FVGs are hidden to prevent counter-trend confusion.
Bearish Trend: Only Bearish FVGs (Red) are highlighted.
Extended Zones: FVG boxes are automatically projected forward (default: 5 candles) to help identify immediate entry zones before price returns to them.
3. Clean Aesthetics The chart remains minimal. Labels are non-intrusive, and color coding is strictly defined (Green for Bullish structure/FVGs, Red for Bearish structure/FVGs), allowing for rapid decision-making.
Settings
Swing Detection Length: Customize the sensitivity of the structure (lower for scalping, higher for macro trends).
FVG Extension: Control how far into the future the FVG boxes are drawn.
Visuals: Fully customizable colors and label options.
This tool is intended to assist in identifying high-probability structural points and aligned entry zones.
SMA 14/28 CrossBy analyzing the XAUUSD chart on the 2H timeframe, we can observe that after a strong bullish market structure, Gold continued to trade higher and successfully expanded toward the 4,850 – 4,890 region, which is marked as a key liquidity and resistance zone on the chart.
Following this impulsive upside move, price is now showing short-term exhaustion, with multiple rejections forming just below the recent highs. The market is currently trading around 4,825, where we can see repeated attempts to break higher, increased volatility, and signs that buy-side liquidity above the highs has been partially taken.
This price behavior has created a short-term liquidity imbalance, and based on the current structure, a pullback is expected before any further bullish continuation. As highlighted on the chart, price may retrace toward the 4,760 – 4,600 support zone, which aligns with previous consolidation, internal structure, and resting liquidity below current price.
4H Institutional Zones - EugenioTheDog Comunidade Mackaqui 4H Supply & Demand – Institutional Zones is a clean and objective indicator designed to identify institutional Supply and Demand zones based on the 4-hour timeframe, while working seamlessly on any lower timeframe chart.
The script detects zones formed after impulsive 4H candles, projecting high-probability areas where price may react, absorb liquidity, or reverse.
Zones are automatically removed after 50% mitigation, keeping the chart clean and focused only on relevant institutional levels.
🔹 Key Features
Automatic detection of 4H Supply & Demand zones
Works on any timeframe (MTF logic)
Zones based on impulsive 4H candles
50% mitigation rule (zones are deleted after partial fill)
ATR-based filters to avoid distant or irrelevant zones
Fully customizable colors and transparency
Clean and minimal visual design for discretionary traders
🔹 How to Use
This indicator is intended for context and higher-timeframe bias, not for blind entries.
Best used in confluence with:
Market structure (BOS / CHoCH)
Liquidity concepts (equal highs/lows, stop hunts)
Lower timeframe execution models
Price action confirmation
Ideal for scalping, day trading, and swing trading, always aligned with higher-timeframe context.
⚠️ Disclaimer
This indicator is for educational purposes only
It does not constitute financial or investment advice.
Always use proper risk management.
👤 Author
Developed by EugenioTheDog
Exclusive release for Grupo VIP MackAqui
Prop Firm EMA RSI Pullback (HTF Bias)by ShuvoHigher Timeframe (HTF) Bias — The Boss Sets the Rules
Purpose:
You don’t fight institutions. You follow their footprints.
Logic:
Use a Higher Timeframe (usually H4 or D1)
Apply:
EMA 200 (trend ruler)
Optional: EMA 50 for confirmation
Bias Rules:
Bullish Bias
Price above EMA 200
EMA 200 sloping up
Bearish Bias
Price below EMA 200
EMA 200 sloping down
🚫 If price is chopping around EMA 200 → NO TRADE
Prop firms love discipline, not gamblers.
XAUUSD Pro Swing Strategy (RR 1:2)//@version=5
strategy("XAUUSD Pro Swing Strategy (RR 1:2)", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=2)
// ===== INPUTS =====
emaFastLen = input.int(20, "Fast EMA")
emaMidLen = input.int(50, "Mid EMA")
emaTrendLen = input.int(200, "Trend EMA (HTF)")
rsiLen = input.int(14, "RSI Length")
atrLen = input.int(14, "ATR Length")
atrSLMult = input.float(1.5, "ATR SL Multiplier")
rr = input.float(2.0, "Risk Reward")
// ===== HTF TREND =====
htfEMA = request.security(syminfo.tickerid, "D", ta.ema(close, emaTrendLen))
// ===== INDICATORS =====
emaFast = ta.ema(close, emaFastLen)
emaMid = ta.ema(close, emaMidLen)
rsi = ta.rsi(close, rsiLen)
atr = ta.atr(atrLen)
// ===== TREND CONDITIONS =====
bullTrend = close > htfEMA and emaFast > emaMid
bearTrend = close < htfEMA and emaFast < emaMid
// ===== ENTRY CONDITIONS =====
buyCond = bullTrend and ta.crossover(emaFast, emaMid) and rsi > 55
sellCond = bearTrend and ta.crossunder(emaFast, emaMid) and rsi < 45
// ===== SL & TP =====
buySL = close - atr * atrSLMult
buyTP = close + (atr * atrSLMult * rr)
sellSL = close + atr * atrSLMult
sellTP = close - (atr * atrSLMult * rr)
// ===== ORDERS =====
if buyCond
strategy.entry("BUY", strategy.long)
strategy.exit("BUY EXIT", "BUY", stop=buySL, limit=buyTP)
if sellCond
strategy.entry("SELL", strategy.short)
strategy.exit("SELL EXIT", "SELL", stop=sellSL, limit=sellTP)
// ===== PLOTS =====
plot(emaFast, color=color.orange)
plot(emaMid, color=color.blue)
plot(htfEMA, color=color.red, linewidth=2)
plotshape(buyCond, style=shape.labelup, text="BUY", color=color.green, location=location.belowbar)
plotshape(sellCond, style=shape.labeldown, text="SELL", color=color.red, location=location.abovebar)
Trend Double Pullback [Stable 20]v1.0Trend Double Pullback Trend Double Pullback Trend Double Pullback Trend Double Pullback Trend Double Pullback Trend Double
Anhnga4.0 - Filter ToggleINPUTS:
1.5 0.8 (OR 1.6 0.5/0.6)
BE=0.45
1
MAs: 35 135
7
This Pine Script code defines a trading strategy named **"Anhnga4.0 - Filter Toggle"**. It is a trend-following strategy that uses momentum oscillators and moving averages to identify entries, while featuring a specific "Overextension Filter" to avoid buying at the top or selling at the bottom.
Here is a breakdown of how the script works:
---
## 1. Core Trading Logic (The Entry)
The strategy looks for a "perfect storm" of three factors before entering a trade:
* **Momentum (WaveTrend):** It uses the WaveTrend oscillator (`wt1` and `wt2`).
* **Long:** A bullish crossover happens while the oscillator is below the zero line (oversold).
* **Short:** A bearish crossunder happens while the oscillator is above the zero line (overbought).
* **Trend Confirmation:** The price must be on the "correct" side of three different lines: the 20-period Moving Average (BB Basis), the 50-period SMA, and the 200-period SMA.
* **The Window:** You don't have to enter exactly on the cross. The `Signal Window` allows the trade to trigger up to 4 bars after the momentum cross, provided the trend filters align.
## 2. The "Overextension" Filter
This is a unique feature of this script. It calculates the distance between the current price and the **50-period Moving Average**.
* If the price is too far away from the MA (defined by the **ATR Limit**), the script assumes the move is "exhausted."
* If `Enable Overextension Filter?` is on, the strategy will skip these trades to avoid "chasing the pump."
* **Visual Cue:** The chart background turns **purple** when the price is considered overextended.
---
## 3. Risk Management & Exit Strategy
The script manages trades dynamically using Bollinger Bands and Risk:Reward ratios:
| Feature | Description |
| --- | --- |
| **Stop Loss (SL)** | Set at the **Lower Bollinger Band** for Longs and **Upper Band** for Shorts. |
| **Take Profit (TP)** | Calculated based on your **RR Ratio** (default is 2.0). If your risk is $10, it sets the target at $20 profit. |
| **Breakeven** | A "protection" feature. Once the price moves in your favor by a certain amount (the `Breakeven Trigger`), the script moves the Stop Loss to your entry price to ensure a "risk-free" trade. |
---
## 4. Visual Elements on the Chart
* **Green Lines:** Your target price (TP).
* **Red Lines:** Your initial Stop Loss.
* **Yellow Lines:** Indicates the Stop Loss has been moved to **Breakeven**.
* **Purple Background:** High alert—price is overextended; trades are likely being filtered out.
---
## Summary of Settings
* **BB Multiplier:** Controls how wide your initial stop loss is.
* **ATR Limit:** Controls how sensitive the "Overextension" filter is (higher = more trades allowed; lower = stricter filtering).
* **Breakeven Trigger:** Set to 1.0 by default, meaning once you are "1R" (profit equals initial risk) in profit, the stop moves to entry.
N Option Selling 1
**NIFTY Weekly Option Seller – Regime & Risk Framework (HTF + RSI)**
This indicator is a **decision-support tool for NIFTY option sellers**, designed to identify whether current market conditions favor:
* **Iron Condor (IC)** – range / mean-reversion
* **Put Credit Spread (PCS)** – bullish bias
* **Call Credit Spread (CCS)** – bearish bias
The script focuses on **structure selection and risk management**, not trade execution.
---
## Core logic
### 1) Multi-timeframe context
* Signals are calculated on the **active chart timeframe** (commonly 4H).
* **Daily (HTF) EMA trend and Daily ADX** are used as **gating conditions**, ensuring strong directional scores are not allowed against the higher-timeframe context.
This prevents aggressive trend selling when the daily structure does not support it.
---
### 2) Three independent regime scores (0–5)
The script computes three capped and smoothed scores:
* **IC score (Range quality)**
Based on low ADX, price inside CPR, proximity to VWAP, Camarilla H3–L3, daily range confirmation, and mid-band RSI.
* **PCS score (Bullish structure)**
Based on EMA up-stack, trend strength (ADX), price relative to CPR/VWAP, with RSI and Daily trend acting as **brakes**, not entry signals.
* **CCS score (Bearish structure)**
Based on EMA down-stack, trend strength (ADX), price relative to CPR/VWAP, with RSI and Daily trend acting as **brakes**, not entry signals.
RSI is used only to **cap aggressiveness at extremes**, not to predict reversals.
---
### 3) Cross-penalty & smoothing
* When multiple regimes score high simultaneously, **cross-penalties reduce conflicting scores** so only one regime dominates.
* Final scores are **smoothed across bars** to avoid frequent regime flips and unstable sizing decisions.
---
### 4) Regime selection
The script selects **one primary regime** (IC / PCS / CCS) based on the highest adjusted score, with tie-break logic that prefers trend regimes only when ADX confirms strength; otherwise it defaults to IC.
---
### 5) Non-repainting reference levels
The indicator plots key **previous-day, non-repainting levels**:
* CPR (Low / High with Narrow–Wide classification)
* Camarilla H3, L3, H4, L4
* VWAP
These are contextual reference levels for structure and risk placement.
---
### 6) DEFEND / HARVEST prompts
Using ATR-based proximity logic, the script provides:
* **DEFEND** alerts when price approaches modeled risk zones
* **HARVEST** alerts when sufficient cushion exists
* **REGIME** alerts on confirmed regime changes
These are **risk-management prompts**, not buy/sell signals.
---
### 7) Visual dashboard
A compact panel displays:
* Active regime and score
* ADX / RSI
* CPR width classification
* EMA structure and tightness
* VWAP proximity
* IC / PCS / CCS scores
* Key level snapshot
---
## Intended use
* Designed for **weekly option selling**
* Best used on **4H charts with Daily context**
* Suitable for traders who manage positions **once per day**
* Encourages **structure-first thinking** (IC base with controlled directional bias)
---
## Disclaimer
This indicator does **not place trades** and does not calculate position size or P&L.
It is a **market regime and risk-awareness tool** and must be used with proper capital management and execution discipline.
Consecutive Candles Futures Bot + BE (MGC 15m)Activates after three consecutive candles with a configurable percentage.
The default options are correct for MGC on the 15m timeframe, yielding a profit factor of 2.5 (can be improved to 2.6 by increasing the Break Even to 30 pips).
If you manage to push it further, send me a message
Nerot YapanimCandle Patterns Pro: Momentum & Multilingual
Overview
Candle Patterns Pro is an advanced, high-conviction candlestick pattern detector built for Pine Script v5. Unlike standard indicators that trigger on every technical occurrence, this script utilizes Momentum-Verified Logic to filter out market noise and "indecisive" price action.
Designed for clarity and precision, it features a unique Multilingual Toggle, allowing users to switch between professional English and Hebrew terminology instantly.
Key Features
1. Momentum-Verified Logic (Anti-Doji Filter)
Most pattern detectors fail by triggering on small-bodied "Doji" candles that lack direction. This indicator uses a custom isStrong algorithm: a signal only triggers if the real body of the candle represents at least 50% of the total candle range. This ensures you only see patterns where bulls or bears have shown true dominance.
2. "Real Body" Engulfing
To prioritize high-probability reversals, the Engulfing logic is calculated using Real Bodies (Open to Close) rather than wicks. By ignoring the "noise" of the thicks/wicks, the signals identify much stronger shifts in institutional pressure.
Shutterstock
3. Integrated Trend Filter (Moving Average)
Align your trades with the primary trend. When the MA Filter is enabled, bullish signals are only displayed if the price is above the Moving Average, while bearish signals appear only when the price is below it.
4. Professional Multilingual Support
This indicator is built for a global audience. Through the settings menu, users can toggle between English and Professional Hebrew labels.
English: Engulfing, 3 Soldiers, 3 Crows, Dark Cloud, etc.
Hebrew: בולען, שלושה חיילים, שלושה עורבים, ענן כהה, etc.
Supported Patterns
Engulfing (Body-Only): Clean reversal signals optimized for momentum.
Three Soldiers & Three Crows: Momentum-verified (Filtered for strength).
Morning & Evening Star: Three-candle structural reversals.
Meeting Line: Precise alignment strike patterns.
Piercing Line & Dark Cloud: Deep-penetration momentum shifts.
Harami: Traditional inside-bar setups.
User Instructions
Selection: Toggle specific patterns on or off in the inputs tab.
Clean UI: The indicator is pre-configured to keep your Status Line clean by hiding values and inputs by default.
Y-Axis Fix: If labels appear "static" or do not move with price, right-click your Price Scale and select "Merge All Scales into One (Right)".
Language: Switch between English and Hebrew via the "Language / שפה" dropdown in settings.
Technical Specifications
Version: Pine Script v5
Execution: Real-time calculation on bar close.
Alerts: Fully compatible with TradingView alerts (Push, Email, Webhook).
200 EMA Multi-Timeframe Bias (5m / 1h / 4h)200 EMA align with 5min, 1hr and 4 hr. it will have a background green if the three timeframes are align .
Previous Day Range MarkerThis indicator highlights the high and low of the last confirmed candle on the current timeframe and optionally displays the range of the previous trading day (Daily) on lower timeframes.
It also calculates and shows the candle range in percent, helping traders quickly assess volatility and higher-timeframe context.
All levels are plotted forward into the future and can be individually enabled or disabled.
ICT 7/8/9am lines NY session + 7.30/8.30/9.30 linesThis script show the 7, 8, 9 AM NY session lines, together with the 7.30, 8.30 and 9.30AM lines, like ICT teaches in the 2024 Mentorship, lesson 2.
Feel free to use it!
XAUUSD Bullish Continuation StrategyThis strategy is designed for trading Gold (XAUUSD) on the M15 timeframe using a bullish continuation and breakout structure.
It identifies strong uptrend conditions using EMA trend confirmation and enters buy positions on either a breakout above resistance or a retest of the breakout zone. The strategy follows a disciplined risk-management model with a fixed stop loss and multiple take-profit targets for partial profit scaling.
Core Features:
• Trend confirmation using EMA 20 & EMA 50
• Breakout and retest buy entries
• Strong momentum continuation logic
• Fixed stop-loss protection
• Multi take-profit scaling (TP1, TP2, TP3)
• Backtest-ready TradingView strategy
Best Market Conditions:
Works best during strong bullish sessions (London & New York) when gold shows high volatility and directional momentum.
Recommended Timeframe:
M15 (can be optimized for M5–M30)
Bar Count & EMABar Count & EMA Indicator
A clean and lightweight indicator designed for intraday price action traders.
Features:
1. Bar Count
Displays bar numbers only on 3-minute and 5-minute timeframes
Works during Regular Trading Hours (RTH) only
Shows bar 1 and multiples of 3 (3, 6, 9, 12, 15...)
Color-coded for key bars: Bar 18 & 48 (Red), Bar 6 (Light Green), Multiples of 12 (Sky Blue), Others (Gray)
2. EMA 20
Simple 20-period Exponential Moving Average
Customizable source, length, offset, and color
Why these specific timeframes?
5-Minute Chart (US Markets):
Bar 6, 12, 18, 24... represent 30-min, 1-hour, 1.5-hour intervals
Bar 18 and 48 often mark significant intraday turning points
Best for: ES, NQ, SPY, QQQ
3-Minute Chart (China A-Share Markets):
Bar 10, 20, 30... represent 30-min, 1-hour, 1.5-hour intervals
Designed for CSI 1000 Index Futures (IM) and other China futures
Helps track the 4-hour trading session rhythm (9:30-11:30, 13:00-15:00)
Why Bar Count Matters:
Tracking bar numbers helps traders identify market rhythm, timing cycles, and potential reversal zones throughout the trading session.
Look-back Value V1新增 MA10 與 MA120 的計算、繪圖、表格顯示。
新增 table_pos 參數,可選擇表格顯示位置(top_left, top_right, bottom_left, bottom_right)。
所有 table.cell 改用 具名參數 text_color,避免誤判成 width。
這樣你就能靈活選擇表格位置,並同時觀察 MA5、MA10、MA20、MA60、MA120、MA240 的扣抵分析。
Cryptocurrency Dual-System Color-Changing Moving AveragesCryptocurrency Dual-System Color-Changing Moving Averages: Advanced Multi-Timeframe Trend Analysis
Innovative Core Concept
Our indicator introduces a revolutionary approach to trend analysis by integrating dual moving average systems with intelligent visual feedback mechanisms. Unlike traditional moving average indicators that simply display lines or basic crossovers, our system provides dynamic, multi-dimensional trend intelligence through three key innovations:
Dual Independent Moving Average Systems - Two complete 7-period moving average systems operate simultaneously, offering independent trend confirmation while maintaining visual harmony through unified color coding.
Intelligent Color-Changing Algorithm - Each moving average dynamically changes color based on its individual trend strength, creating a visual heatmap of momentum across different timeframes.
Holistic Market State Visualization - The entire candlestick chart changes color based on overall trend alignment, providing immediate visual confirmation of market regimes.
Comprehensive Functionality and Implementation
What It Does
This indicator performs multi-timeframe trend analysis across 14 moving averages (7 for each system), calculating individual trend strength for each line and determining overall market alignment to provide clear visual signals for different market conditions.
How It Works
Primary Trend Strength Calculation:
For each moving average, the indicator calculates a proprietary trend strength value by analyzing the net directional movement over a user-defined lookback period. This quantifies whether the moving average is consistently rising, falling, or consolidating.
Color Coding Logic:
Blue: Moving average shows strong upward momentum (trend strength exceeds positive threshold)
Orange: Moving average shows strong downward momentum (trend strength falls below negative threshold)
Gray: Moving average shows neutral/consolidating behavior
Market Regime Detection:
The system analyzes the alignment of three key moving averages (short-term, medium-term, and long-term) from the Main MA System to determine the overall market state:
Bullish Alignment: Short-term MA > Medium-term MA > Long-term MA (candlesticks turn blue)
Bearish Alignment: Short-term MA < Medium-term MA < Long-term MA (candlesticks turn orange)
Consolidation: No clear alignment pattern (candlesticks turn white)
Implementation Methodology
Our approach combines several established technical analysis concepts with unique enhancements:
Multiple Timeframe Analysis (MTFA) - We simultaneously analyze 7 different time periods (21, 55, 89, 144, 200, 450, 800) to capture trend dynamics across short, medium, and long time horizons.
Trend Strength Quantification - Instead of relying on simple crossovers, we calculate a proprietary trend strength metric that measures both direction and momentum consistency.
Visual Pattern Recognition Enhancement - By color-coding both the moving averages and the price bars, we leverage human visual processing capabilities to quickly identify market states and potential reversals.
Dual Confirmation System - The two independent moving average systems (Main System and EMA System) provide layered confirmation, reducing false signals and increasing reliability.
Practical Application and Usage Guidelines
Setup and Configuration
Main Moving Average System:
Configure your preferred moving average type (SMA, EMA, WMA, or HMA) and select which of the 7 periods to display. Each period can be individually enabled or disabled based on your analysis needs.
EMA System Configuration:
The secondary EMA system provides additional trend confirmation. Adjust its transparency to visually distinguish it from the Main System while maintaining chart clarity.
Trend Sensitivity Adjustment:
The "Trend Strength Threshold" parameter allows fine-tuning of color change sensitivity. Lower values make the indicator more responsive to minor trends, while higher values require stronger momentum for color changes.
Strategic Trading Applications
1. Trend Identification and Confirmation Strategy
Bullish Confirmation: Look for predominantly blue moving averages across multiple timeframes accompanied by blue candlesticks
Bearish Confirmation: Look for predominantly orange moving averages across multiple timeframes accompanied by orange candlesticks
Trend Weakness Detection: Watch for moving averages changing from blue to gray/orange or from orange to gray/blue
2. Multi-Timeframe Alignment Trading
High-Probability Entries: Enter positions when all three key timeframes (short, medium, long) align in the same direction
Exit Signals: Consider reducing positions when timeframes begin to diverge or when candlestick color changes to white (consolidation)
3. Support and Resistance Identification
Moving averages serve as dynamic support/resistance levels
Color changes at these levels indicate whether support/resistance is strengthening or weakening
4. Market Regime Adaptation
Trend-Following Mode: During blue/orange candlestick periods, employ trend-following strategies
Range-Trading Mode: During white candlestick periods, employ range-bound or mean-reversion strategies
Core Philosophical Framework and Calculation Logic
Underlying Technical Analysis Principles
Our indicator is built upon the principle that trends exist simultaneously across multiple timeframes, and the convergence or divergence of these timeframes provides valuable information about trend strength and potential reversals.
Calculation Methodology
Trend Strength Formula:
For each moving average, we calculate:
Sum of upward movements over the lookback period
Sum of downward movements over the lookback period
Net directional bias as a normalized value between -1 and +1
This approach provides a more nuanced understanding of trend momentum compared to simple directional analysis.
Threshold-Based Classification:
Values above the positive threshold indicate sustainable upward momentum
Values below the negative threshold indicate sustainable downward momentum
Values within the threshold range indicate consolidation or weak trends
Why This Approach Is Effective
Early Warning System: Color changes in individual moving averages often precede overall market regime changes, providing early reversal signals.
Noise Reduction: By requiring alignment across multiple timeframes for candlestick coloring, we filter out false signals common in single-timeframe analysis.
Visual Processing Efficiency: The color-coded system allows rapid interpretation of complex multi-timeframe information, reducing cognitive load during fast market conditions.
Adaptability: Configurable parameters allow adjustment for different market conditions (high volatility vs. low volatility) and trading styles (scalping vs. position trading).
This indicator is particularly valuable for cryptocurrency trading due to the market's characteristic high volatility and strong trend tendencies. By providing clear visual cues about trend strength and alignment across multiple timeframes, it helps traders remain aligned with the dominant market direction while avoiding periods of choppy, directionless price action.
The system's dual-layer confirmation (moving average colors + candlestick colors) creates a robust framework for identifying high-probability trading opportunities while maintaining flexibility to adapt to changing market conditions.
MTF Institutional Zone - EugenioTheDog MackaquiThis script plots Institutional Supply & Demand Zones (MTF) on any chart timeframe, so you can track higher timeframe decision areas while executing on lower timeframes.
What it does
Up to 3 selectable timeframes (TF1 / TF2 / TF3)
Automatically detects Demand (buy) zones and Supply (sell) zones
Zones are created when a strong impulse candle appears (body vs ATR), using the last opposite candle as the zone source
Zones are extended to the right in real time
Zones are removed after 50% mitigation (midpoint touched)
Alerts included
Formation alerts
TF1 / TF2 / TF3: Demand formed
TF1 / TF2 / TF3: Supply formed
Combined: TF1+TF2 and TF1+TF2+TF3 zone formed
Proximity alerts (before touch)
Alerts when price is approaching a zone (configurable % distance)
Combined alerts: TF1+TF2 and TF1+TF2+TF3
How to use (important)
This indicator is NOT a standalone entry signal.
Zones must be traded with context:
Align with trend / market structure
Look for liquidity grabs / sweeps
Wait for reaction and confirmation before entering
Visual settings
You can customize colors and transparencies for Demand/Supply in the settings.
Made for EugenioTheDog – Grupo VIP Mackaqui.
Not financial advice. Use at your own risk.
Time LineUse it to mark out start times, using it personally to mark 8am starting zone but I'm sure you may have other uses






















