EMA Pullback & Dual Crossover Pro Strategy,EMA Pullback & Dual Crossover Pro Strategy,
(EMA 20 / 50 / 200 Trend-Based System)
🔍 Strategy Overview
The EMA Pullback & Dual Crossover Pro Strategy is a trend-following and trend-reversal trading system designed to capture high-probability entries while filtering out low-quality trades during market noise.
The strategy combines:
Trend continuation trades using EMA 20/50 pullbacks
Major trend reversal trades using EMA 20/200 crossovers
A smart EMA 200 trend filter is applied only to pullback trades, ensuring trades align with the dominant market direction.
This hybrid approach allows the strategy to perform well in:
Strong trending markets
Early trend reversals
Controlled pullback environments
📐 Indicators Used
Indicator Purpose
EMA 20 Fast momentum & entry timing
EMA 50 Pullback structure
EMA 200 Long-term trend direction
🧠 Strategy Logic Breakdown
1️⃣ Trend Definition (EMA 200)
The EMA 200 defines the dominant market trend:
Bullish Trend → Price above EMA 200
Bearish Trend → Price below EMA 200
This trend filter is only applied to EMA 20/50 trades.
2️⃣ EMA 20 / 50 Pullback Trades (Trend Continuation)
These trades capture pullbacks within an existing trend.
🔼 BUY Conditions (20/50 Pullback)
EMA 20 crosses above EMA 50
Price is above EMA 200
Close confirms above EMA 20
Trade triggers after confirmation bars
🔽 SELL Conditions (20/50 Pullback)
EMA 20 crosses below EMA 50
Price is below EMA 200
Close confirms below EMA 20
Trade triggers after confirmation bars
🛑 Counter-trend 20/50 trades are blocked automatically.
3️⃣ EMA 20 / 200 Crossover Trades (Trend Reversal)
These trades capture major market reversals and breakouts.
🔼 BUY Conditions (20/200 Crossover)
EMA 20 crosses above EMA 200
Close confirms above EMA 20
🔽 SELL Conditions (20/200 Crossover)
EMA 20 crosses below EMA 200
Close confirms below EMA 20
🚀 These trades are not trend-filtered to allow early participation in new trends.
⏱ Confirmation Logic
To reduce false signals:
Entries are triggered only after confirmation bars
Price must close in the direction of the trade
Prevents wick-based and noise-induced entries
⚙️ Strategy Settings
Parameter Description
EMA 20 / 50 / 200 Adjustable lengths
Confirmation Bars Signal validation
Enable 20/50 Trades Toggle pullback trades
Enable 20/200 Trades Toggle reversal trades
EMA 200 Trend Filter Applies to 20/50 only
🎯 Trade Types Summary
Trade Type Purpose Trend Filter
EMA 20/50 Trend continuation (pullback) ✅ Yes
EMA 20/200 Trend reversal / breakout ❌ No
📊 Best Use Cases
Markets: XAUUSD, Indices, Major Forex Pairs
Timeframes: M5, M15, H1
Market Conditions: Trending & breakout environments
⚠️ Risk Disclaimer
This strategy is designed for systematic trading and should be used with:
Proper risk management
Fixed position sizing
Stop-loss rules defined by the trader
Backtesting and forward testing are strongly recommended before live deployment.
🧩 Final Notes
This strategy is structured like a professional institutional system:
One engine captures trend pullbacks
One engine captures trend shifts
Noise is filtered using EMA structure and confirmations
It is not a scalping bot, but a trend-aligned trading framework suitable for disciplined traders.
"bot"に関するスクリプトを検索
OrangePulse v3.0 Lite - Educational DCA StrategyThis open-source script is a simplified version of the OrangePulse algorithm, designed for educational purposes to demonstrate the power of Dollar Cost Averaging (DCA) and Mean Reversion.
📈 Strategy Logic:
The script uses a combination of Bollinger Bands and RSI (Relative Strength Index) to identify potential mean reversion opportunities.
- Entry: Triggered when price pushes below the lower Bollinger Band while RSI is in oversold territory.
- Management: Utilizes up to 3 Safety Orders (DCA) to improve the average entry price during pullbacks.
🎯 Features:
• Customizable Volume Scale and Step Scale for Safety Orders.
• Visual AVG price line and TP/SL levels.
• Time-window filter for backtesting.
• Real-time Status Table for position monitoring.
This script is shared in the spirit of open-source development on TradingView. It is intended to help traders understand how automated position building and risk management work in volatile markets.
Check my profile status/bio for more information on our project.
⚠️ Disclaimer: For educational purposes only. Past performance does not guarantee future results.
TradingHelperLibLibrary "TradingHelperLib"
Trading Helper Library - Limit order, pip calculation and utility functions for trading bots
f_pipValue()
Calculates pip value based on symbol info
Returns: Pip value
f_pipsToPrice(pips)
Converts pip count to price difference
Parameters:
pips (float) : Number of pips
Returns: Price difference
calcExpireBarCount(minutesToExpire)
Converts minutes to bar count based on timeframe
Parameters:
minutesToExpire (float) : Duration in minutes
Returns: Bar count
calcLimitPrice(isLong, signalPrice, deviation, deviationType)
Calculates limit order price with deviation
Parameters:
isLong (bool) : True for long, false for short
signalPrice (float) : Signal price
deviation (float) : Deviation amount
deviationType (string) : Deviation type ("USDT" or "%")
Returns: Limit price
checkLimitFill(isLong, limitPrice)
Checks if limit order is filled
Parameters:
isLong (bool) : True for long, false for short
limitPrice (float) : Limit price to check
Returns: True if filled
f_multiplier(lvl, mode)
Calculates DCA multiplier based on level and mode
Parameters:
lvl (int) : DCA level
mode (string) : Multiplier mode ("Sabit", "Fibonacci", "Martingale", etc.)
Returns: Multiplier value
f_pctToPrice(pct, basePrice)
Converts percentage value to price difference
Parameters:
pct (float) : Percentage value (e.g. 2.0 = 2%)
basePrice (float) : Reference price
Returns: Price difference
f_priceChange_toPct(priceChange, basePrice)
Converts price change to percentage
Parameters:
priceChange (float) : Price difference
basePrice (float) : Reference price
Returns: Percentage value
calcMargin(notional, leverage)
Calculates margin from notional value
Parameters:
notional (float) : Trade size (e.g. $1000)
leverage (int) : Leverage value (e.g. 100)
Returns: Margin value
calcNotional(margin, leverage)
Calculates notional from margin
Parameters:
margin (float) : Collateral value
leverage (int) : Leverage value
Returns: Notional value
calcLiqPriceLongSimple(avgPrice, leverage)
Calculates simple liquidation price for Long position
Parameters:
avgPrice (float) : Average entry price
leverage (int) : Leverage value
Returns: Estimated liquidation price
calcLiqPriceShortSimple(avgPrice, leverage)
Calculates simple liquidation price for Short position
Parameters:
avgPrice (float) : Average entry price
leverage (int) : Leverage value
Returns: Estimated liquidation price
calcPnlLong(entryPrice, currentPrice, notional)
Calculates Long position PNL
Parameters:
entryPrice (float) : Entry price
currentPrice (float) : Current price
notional (float) : Position size
Returns: PNL value
calcPnlShort(entryPrice, currentPrice, notional)
Calculates Short position PNL
Parameters:
entryPrice (float) : Entry price
currentPrice (float) : Current price
notional (float) : Position size
Returns: PNL value
calcFee(notional, feeRate)
Calculates trading fee
Parameters:
notional (float) : Trade size
feeRate (float) : Fee rate in percentage (e.g. 0.1 = 0.1%)
Returns: Fee value
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! 📈**
TRIZONACCI_Mean reversal_signalsMarket 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
Open TradingView
Open the Pine Editor (bottom panel)
Click "New" → "Blank indicator"
Delete all default code
Paste the contents of market_state_engine.pine
Click "Add to Chart"
Step 3: Configure for Your Symbol
Click the gear icon next to the indicator name
Adjust Tick Size for your instrument:
ES futures: 0.25
NQ futures: 0.25
Stocks: 0.01
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
Click "Create Alert" in TradingView
Select Market State Engine as condition
Choose alert type:
Bullish Setup - Long signals only
Bearish Setup - Short signals only
Any Setup - All signals
Set to "Once Per Bar Close"
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
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:
This README documentation
The specification document (pinescript_market_state_engine_spec.docx)
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! 📈
(5M) REG SuperTrend Pullback SystemThis indicator implements a rule-based SuperTrend pullback system
designed for short-term trend continuation.
Core features:
• Regression-based SuperTrend with flip detection
• Pullback + reclaim entry logic (non-repainting, bar-close confirmed)
• Regime filter (Trend vs Range suppression)
• Exhaustion detection to avoid late entries
• ADX + EMA bias alignment
• USDT Dominance risk filter (risk-on / risk-off)
• Clear BUY / SELL and Pullback AI-style entry labels
This is NOT a trading bot and does NOT place orders.
All signals are for analytical and educational purposes only.
Silver Futures Adaptive Strategy 1-18-20261. Hybrid Trading Logic
The strategy doesn't rely on a single method; instead, it switches between three distinct entry archetypes depending on market conditions:
Trend Following: Activated when ADX is high. It looks for "Golden Crosses" (EMA 21/50) confirmed by a long-term 200 EMA filter.
Breakout: Enters when the price exceeds the 20-period highest high or lowest low, provided there is a "Volume Spike" to confirm the move.
Mean Reversion: Activated when ADX is low (ranging market). It uses Bollinger Bands and RSI to buy oversold dips or sell overbought peaks.
2. Key Technical Indicators
The strategy uses a robust stack of indicators to filter out "noise":
ADX (Average Directional Index): Acts as the "brain" that determines if the market is trending (ADX > 20) or ranging.
Triple EMA Filter: Uses 21, 50, and 200 EMAs to ensure trades are only taken in the direction of the dominant trend.
Volume Filter: Requires volume to be 20% higher than the 20-period average to validate an entry, preventing "fake-outs."
Silver-Adjusted ATR: Calculates volatility specifically for Silver, applying a 1.2x multiplier to account for the metal's unique price action.
3. Advanced Risk Management
The strategy is built for execution with the following safeguards:
Dynamic Stops/TP: Stop losses and take profits are not fixed dollar amounts; they are based on ATR (Average True Range), meaning they widen during high volatility and tighten during low volatility.
Trailing Stop: Includes an optional trailing stop feature to lock in profits as the trade moves in your favor.
Position Sizing: Defaults to 10% of equity per trade with a maximum of 3 "pyramiding" entries (scaling into a winning position).
4. Automation & UI Features
JSON Alert Messages: The script generates machine-readable JSON alerts. This makes it "plug-and-play" for automated trading bots, sending the action, price, SL, and TP in a single message.
Dashboard Info Panel: A table on the top-right of the chart displays real-time data:
Market State: Trending vs. Ranging.
Live Stats: Current ADX, RSI, and ATR values.
Visual Cues: It plots support/resistance steplines and labels entries with green/red triangles for easy backtesting.
Spot Taker Flow & Early Warning System How Does This Code Detect a "Fake" Rise?
Spot VWMA Logic: The moving average looks not only at the price but also at how much "spot volume" is circulating at that price.
Fake Rise Scenario: If the price (candles) is going up but the Yellow (Binance) or Blue (Coinbase) lines we've drawn are below it, or the price is drooping to the level of these lines; know that the rise is being triggered by bots in futures trading, not spot buyers. This is a "Fake" rise.
Confirmed Rise: If the price is above all these L1 lines, there may be "real money behind it".
Grid Bot Strategy V1The strategy of grid trading. Allows you to test the strategy at any time, set the range width and the number of levels.
BUZARA// © Buzzara
// =================================
// PLEASE SUPPORT THE TEAM
// =================================
//
// Telegram: t.me
// =================================
//@version=5
VERSION = ' Buzzara2.0'
strategy('ALGOX V6_1_24', shorttitle = '🚀〄 Buzzara2.0 〄🚀'+ VERSION, overlay = true, explicit_plot_zorder = true, pyramiding = 0, default_qty_type = strategy.percent_of_equity, initial_capital = 1000, default_qty_value = 1, calc_on_every_tick = false, process_orders_on_close = true)
G_SCRIPT01 = '■ ' + 'SAIYAN OCC'
//#region ———— <↓↓↓ G_SCRIPT01 ↓↓↓> {
// === INPUTS ===
res = input.timeframe('15', 'TIMEFRAME', group ="NON REPAINT")
useRes = input(true, 'Use Alternate Signals')
intRes = input(10, 'Multiplier for Alernate Signals')
basisType = input.string('ALMA', 'MA Type: ', options= )
basisLen = input.int(50, 'MA Period', minval=1)
offsetSigma = input.int(5, 'Offset for LSMA / Sigma for ALMA', minval=0)
offsetALMA = input.float(2, 'Offset for ALMA', minval=0, step=0.01)
scolor = input(false, 'Show coloured Bars to indicate Trend?')
delayOffset = input.int(0, 'Delay Open/Close MA', minval=0, step=1,
tooltip = 'Forces Non-Repainting')
tradeType = input.string('BOTH', 'What trades should be taken : ',
options = )
//=== /INPUTS ===
h = input(false, 'Signals for Heikin Ashi Candles')
//INDICATOR SETTINGS
swing_length = input.int(10, 'Swing High/Low Length', group = 'Settings', minval = 1, maxval = 50)
history_of_demand_to_keep = input.int(20, 'History To Keep', minval = 5, maxval = 50)
box_width = input.float(2.5, 'Supply/Demand Box Width', group = 'Settings', minval = 1, maxval = 10, step = 0.5)
//INDICATOR VISUAL SETTINGS
show_zigzag = input.bool(false, 'Show Zig Zag', group = 'Visual Settings', inline = '1')
show_price_action_labels = input.bool(false, 'Show Price Action Labels', group = 'Visual Settings', inline = '2')
supply_color = input.color(#00000000, 'Supply', group = 'Visual Settings', inline = '3')
supply_outline_color = input.color(#00000000, 'Outline', group = 'Visual Settings', inline = '3')
demand_color = input.color(#00000000, 'Demand', group = 'Visual Settings', inline = '4')
demand_outline_color = input.color(#00000000, 'Outline', group = 'Visual Settings', inline = '4')
bos_label_color = input.color(#00000000, 'BOS Label', group = 'Visual Settings', inline = '5')
poi_label_color = input.color(#00000000, 'POI Label', group = 'Visual Settings', inline = '7')
poi_border_color = input.color(#00000000, 'POI border', group = 'Visual Settings', inline = '7')
swing_type_color = input.color(#00000000, 'Price Action Label', group = 'Visual Settings', inline = '8')
zigzag_color = input.color(#00000000, 'Zig Zag', group = 'Visual Settings', inline = '9')
//END SETTINGS
// FUNCTION TO ADD NEW AND REMOVE LAST IN ARRAY
f_array_add_pop(array, new_value_to_add) =>
array.unshift(array, new_value_to_add)
array.pop(array)
// FUNCTION SWING H & L LABELS
f_sh_sl_labels(array, swing_type) =>
var string label_text = na
if swing_type == 1
if array.get(array, 0) >= array.get(array, 1)
label_text := 'HH'
else
label_text := 'LH'
label.new(
bar_index - swing_length,
array.get(array,0),
text = label_text,
style = label.style_label_down,
textcolor = swing_type_color,
color = swing_type_color,
size = size.tiny)
else if swing_type == -1
if array.get(array, 0) >= array.get(array, 1)
label_text := 'HL'
else
label_text := 'LL'
label.new(
bar_index - swing_length,
array.get(array,0),
text = label_text,
style = label.style_label_up,
textcolor = swing_type_color,
color = swing_type_color,
size = size.tiny)
// FUNCTION MAKE SURE SUPPLY ISNT OVERLAPPING
f_check_overlapping(new_poi, box_array, atrValue) =>
atr_threshold = atrValue * 2
okay_to_draw = true
for i = 0 to array.size(box_array) - 1
top = box.get_top(array.get(box_array, i))
bottom = box.get_bottom(array.get(box_array, i))
poi = (top + bottom) / 2
upper_boundary = poi + atr_threshold
lower_boundary = poi - atr_threshold
if new_poi >= lower_boundary and new_poi <= upper_boundary
okay_to_draw := false
break
else
okay_to_draw := true
okay_to_draw
// FUNCTION TO DRAW SUPPLY OR DEMAND ZONE
f_supply_demand(value_array, bn_array, box_array, label_array, box_type, atrValue) =>
atr_buffer = atrValue * (box_width / 10)
box_left = array.get(bn_array, 0)
box_right = bar_index
var float box_top = 0.00
var float box_bottom = 0.00
var float poi = 0.00
if box_type == 1
box_top := array.get(value_array, 0)
box_bottom := box_top - atr_buffer
poi := (box_top + box_bottom) / 2
else if box_type == -1
box_bottom := array.get(value_array, 0)
box_top := box_bottom + atr_buffer
poi := (box_top + box_bottom) / 2
okay_to_draw = f_check_overlapping(poi, box_array, atrValue)
// okay_to_draw = true
//delete oldest box, and then create a new box and add it to the array
if box_type == 1 and okay_to_draw
box.delete( array.get(box_array, array.size(box_array) - 1) )
f_array_add_pop(box_array, box.new( left = box_left, top = box_top, right = box_right, bottom = box_bottom, border_color = supply_outline_color,
bgcolor = supply_color, extend = extend.right, text = 'SUPPLY', text_halign = text.align_center, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index))
box.delete( array.get(label_array, array.size(label_array) - 1) )
f_array_add_pop(label_array, box.new( left = box_left, top = poi, right = box_right, bottom = poi, border_color = poi_border_color,
bgcolor = poi_border_color, extend = extend.right, text = 'POI', text_halign = text.align_left, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index))
else if box_type == -1 and okay_to_draw
box.delete( array.get(box_array, array.size(box_array) - 1) )
f_array_add_pop(box_array, box.new( left = box_left, top = box_top, right = box_right, bottom = box_bottom, border_color = demand_outline_color,
bgcolor = demand_color, extend = extend.right, text = 'DEMAND', text_halign = text.align_center, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index))
box.delete( array.get(label_array, array.size(label_array) - 1) )
f_array_add_pop(label_array, box.new( left = box_left, top = poi, right = box_right, bottom = poi, border_color = poi_border_color,
bgcolor = poi_border_color, extend = extend.right, text = 'POI', text_halign = text.align_left, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index))
// FUNCTION TO CHANGE SUPPLY/DEMAND TO A BOS IF BROKEN
f_sd_to_bos(box_array, bos_array, label_array, zone_type) =>
if zone_type == 1
for i = 0 to array.size(box_array) - 1
level_to_break = box.get_top(array.get(box_array,i))
// if ta.crossover(close, level_to_break)
if close >= level_to_break
copied_box = box.copy(array.get(box_array,i))
f_array_add_pop(bos_array, copied_box)
mid = (box.get_top(array.get(box_array,i)) + box.get_bottom(array.get(box_array,i))) / 2
box.set_top(array.get(bos_array,0), mid)
box.set_bottom(array.get(bos_array,0), mid)
box.set_extend( array.get(bos_array,0), extend.none)
box.set_right( array.get(bos_array,0), bar_index)
box.set_text( array.get(bos_array,0), 'BOS' )
box.set_text_color( array.get(bos_array,0), bos_label_color)
box.set_text_size( array.get(bos_array,0), size.small)
box.set_text_halign( array.get(bos_array,0), text.align_center)
box.set_text_valign( array.get(bos_array,0), text.align_center)
box.delete(array.get(box_array, i))
box.delete(array.get(label_array, i))
if zone_type == -1
for i = 0 to array.size(box_array) - 1
level_to_break = box.get_bottom(array.get(box_array,i))
// if ta.crossunder(close, level_to_break)
if close <= level_to_break
copied_box = box.copy(array.get(box_array,i))
f_array_add_pop(bos_array, copied_box)
mid = (box.get_top(array.get(box_array,i)) + box.get_bottom(array.get(box_array,i))) / 2
box.set_top(array.get(bos_array,0), mid)
box.set_bottom(array.get(bos_array,0), mid)
box.set_extend( array.get(bos_array,0), extend.none)
box.set_right( array.get(bos_array,0), bar_index)
box.set_text( array.get(bos_array,0), 'BOS' )
box.set_text_color( array.get(bos_array,0), bos_label_color)
box.set_text_size( array.get(bos_array,0), size.small)
box.set_text_halign( array.get(bos_array,0), text.align_center)
box.set_text_valign( array.get(bos_array,0), text.align_center)
box.delete(array.get(box_array, i))
box.delete(array.get(label_array, i))
// FUNCTION MANAGE CURRENT BOXES BY CHANGING ENDPOINT
f_extend_box_endpoint(box_array) =>
for i = 0 to array.size(box_array) - 1
box.set_right(array.get(box_array, i), bar_index + 100)
//
stratRes = timeframe.ismonthly ? str.tostring(timeframe.multiplier * intRes, '###M') :
timeframe.isweekly ? str.tostring(timeframe.multiplier * intRes, '###W') :
timeframe.isdaily ? str.tostring(timeframe.multiplier * intRes, '###D') :
timeframe.isintraday ? str.tostring(timeframe.multiplier * intRes, '####') :
'60'
src = h ? request.security(ticker.heikinashi(syminfo.tickerid),
timeframe.period, close, lookahead = barmerge.lookahead_off) : close
// CALCULATE ATR
atrValue = ta.atr(50)
// CALCULATE SWING HIGHS & SWING LOWS
swing_high = ta.pivothigh(high, swing_length, swing_length)
swing_low = ta.pivotlow(low, swing_length, swing_length)
// ARRAYS FOR SWING H/L & BN
var swing_high_values = array.new_float(5,0.00)
var swing_low_values = array.new_float(5,0.00)
var swing_high_bns = array.new_int(5,0)
var swing_low_bns = array.new_int(5,0)
// ARRAYS FOR SUPPLY / DEMAND
var current_supply_box = array.new_box(history_of_demand_to_keep, na)
var current_demand_box = array.new_box(history_of_demand_to_keep, na)
// ARRAYS FOR SUPPLY / DEMAND POI LABELS
var current_supply_poi = array.new_box(history_of_demand_to_keep, na)
var current_demand_poi = array.new_box(history_of_demand_to_keep, na)
// ARRAYS FOR BOS
var supply_bos = array.new_box(5, na)
var demand_bos = array.new_box(5, na)
//END CALCULATIONS
// NEW SWING HIGH
if not na(swing_high)
//MANAGE SWING HIGH VALUES
f_array_add_pop(swing_high_values, swing_high)
f_array_add_pop(swing_high_bns, bar_index )
if show_price_action_labels
f_sh_sl_labels(swing_high_values, 1)
f_supply_demand(swing_high_values, swing_high_bns, current_supply_box, current_supply_poi, 1, atrValue)
// NEW SWING LOW
else if not na(swing_low)
//MANAGE SWING LOW VALUES
f_array_add_pop(swing_low_values, swing_low)
f_array_add_pop(swing_low_bns, bar_index )
if show_price_action_labels
f_sh_sl_labels(swing_low_values, -1)
f_supply_demand(swing_low_values, swing_low_bns, current_demand_box, current_demand_poi, -1, atrValue)
f_sd_to_bos(current_supply_box, supply_bos, current_supply_poi, 1)
f_sd_to_bos(current_demand_box, demand_bos, current_demand_poi, -1)
f_extend_box_endpoint(current_supply_box)
f_extend_box_endpoint(current_demand_box)
channelBal = input.bool(false, "Channel Balance", group = "CHART")
lr_slope(_src, _len) =>
x = 0.0, y = 0.0, x2 = 0.0, xy = 0.0
for i = 0 to _len - 1
val = _src
per = i + 1
x += per
y += val
x2 += per * per
xy += val * per
_slp = (_len * xy - x * y) / (_len * x2 - x * x)
_avg = y / _len
_int = _avg - _slp * x / _len + _slp
lr_dev(_src, _len, _slp, _avg, _int) =>
upDev = 0.0, dnDev = 0.0
val = _int
for j = 0 to _len - 1
price = high - val
if price > upDev
upDev := price
price := val - low
if price > dnDev
dnDev := price
price := _src
val += _slp
//
= ta.kc(close, 80, 10.5)
= ta.kc(close, 80, 9.5)
= ta.kc(close, 80, 8)
= ta.kc(close, 80, 3)
barsL = 10
barsR = 10
pivotHigh = fixnan(ta.pivothigh(barsL, barsR) )
pivotLow = fixnan(ta.pivotlow(barsL, barsR) )
source = close, period = 150
= lr_slope(source, period)
= lr_dev(source, period, s, a, i)
y1 = low - (ta.atr(30) * 2), y1B = low - ta.atr(30)
y2 = high + (ta.atr(30) * 2), y2B = high + ta.atr(30)
x1 = bar_index - period + 1, _y1 = i + s * (period - 1), x2 = bar_index, _y2 = i
//Functions
//Line Style function
get_line_style(style) =>
out = switch style
'???' => line.style_solid
'----' => line.style_dashed
' ' => line.style_dotted
//Function to get order block coordinates
get_coordinates(condition, top, btm, ob_val)=>
var ob_top = array.new_float(0)
var ob_btm = array.new_float(0)
var ob_avg = array.new_float(0)
var ob_left = array.new_int(0)
float ob = na
//Append coordinates to arrays
if condition
avg = math.avg(top, btm)
array.unshift(ob_top, top)
array.unshift(ob_btm, btm)
array.unshift(ob_avg, avg)
ob := ob_val
//Function to remove mitigated order blocks from coordinate arrays
remove_mitigated(ob_top, ob_btm, ob_left, ob_avg, target, bull)=>
mitigated = false
target_array = bull ? ob_btm : ob_top
for element in target_array
idx = array.indexof(target_array, element)
if (bull ? target < element : target > element)
mitigated := true
array.remove(ob_top, idx)
array.remove(ob_btm, idx)
array.remove(ob_avg, idx)
array.remove(ob_left, idx)
mitigated
//Function to set order blocks
set_order_blocks(ob_top, ob_btm, ob_left, ob_avg, ext_last, bg_css, border_css, lvl_css)=>
var ob_box = array.new_box(0)
var ob_lvl = array.new_line(0)
//Global elements
var os = 0
var target_bull = 0.
var target_bear = 0.
// Create non-repainting security function
rp_security(_symbol, _res, _src) =>
request.security(_symbol, _res, _src )
htfHigh = rp_security(syminfo.tickerid, res, high)
htfLow = rp_security(syminfo.tickerid, res, low)
// Main Indicator
// Functions
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x ), t)
smoothrng = ta.ema(avrng, wper) * m
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt ) ? x - r < nz(rngfilt ) ? nz(rngfilt ) : x - r : x + r > nz(rngfilt ) ? nz(rngfilt ) : x + r
percWidth(len, perc) => (ta.highest(len) - ta.lowest(len)) * perc / 100
securityNoRep(sym, res, src) => request.security(sym, res, src, barmerge.gaps_off, barmerge.lookahead_on)
swingPoints(prd) =>
pivHi = ta.pivothigh(prd, prd)
pivLo = ta.pivotlow (prd, prd)
last_pivHi = ta.valuewhen(pivHi, pivHi, 1)
last_pivLo = ta.valuewhen(pivLo, pivLo, 1)
hh = pivHi and pivHi > last_pivHi ? pivHi : na
lh = pivHi and pivHi < last_pivHi ? pivHi : na
hl = pivLo and pivLo > last_pivLo ? pivLo : na
ll = pivLo and pivLo < last_pivLo ? pivLo : na
f_chartTfInMinutes() =>
float _resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1 :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 60. * 24 :
timeframe.isweekly ? 60. * 24 * 7 :
timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
f_kc(src, len, sensitivity) =>
basis = ta.sma(src, len)
span = ta.atr(len)
wavetrend(src, chlLen, avgLen) =>
esa = ta.ema(src, chlLen)
d = ta.ema(math.abs(src - esa), chlLen)
ci = (src - esa) / (0.015 * d)
wt1 = ta.ema(ci, avgLen)
wt2 = ta.sma(wt1, 3)
f_top_fractal(_src) => _src < _src and _src < _src and _src > _src and _src > _src
f_bot_fractal(_src) => _src > _src and _src > _src and _src < _src and _src < _src
top_fractal = f_top_fractal(src)
bot_fractal = f_bot_fractal(src)
f_fractalize (_src) => top_fractal ? 1 : bot_fractal ? -1 : 0
f_findDivs(src, topLimit, botLimit) =>
fractalTop = f_fractalize(src) > 0 and src >= topLimit ? src : na
fractalBot = f_fractalize(src) < 0 and src <= botLimit ? src : na
highPrev = ta.valuewhen(fractalTop, src , 0)
highPrice = ta.valuewhen(fractalTop, high , 0)
lowPrev = ta.valuewhen(fractalBot, src , 0)
lowPrice = ta.valuewhen(fractalBot, low , 0)
bearSignal = fractalTop and high > highPrice and src < highPrev
bullSignal = fractalBot and low < lowPrice and src > lowPrev
// Get user input
enableSR = input(false , "SR On/Off", group="SR")
colorSup = input(#00000000 , "Support Color", group="SR")
colorRes = input(#00000000 , "Resistance Color", group="SR")
strengthSR = input.int(2 , "S/R Strength", 1, group="SR")
lineStyle = input.string("Dotted", "Line Style", , group="SR")
lineWidth = input.int(2 , "S/R Line Width", 1, group="SR")
useZones = input(true , "Zones On/Off", group="SR")
useHLZones = input(true , "High Low Zones On/Off", group="SR")
zoneWidth = input.int(2 , "Zone Width %", 0,
tooltip = "it's calculated using % of the distance between highest/lowest in last 300 bars", group="SR")
expandSR = input(true , "Expand SR")
// Get components
rb = 10
prd = 284
ChannelW = 10
label_loc = 55
style = lineStyle == "Solid" ? line.style_solid :
lineStyle == "Dotted" ? line.style_dotted : line.style_dashed
ph = ta.pivothigh(rb, rb)
pl = ta.pivotlow (rb, rb)
sr_levels = array.new_float(21, na)
prdhighest = ta.highest(prd)
prdlowest = ta.lowest(prd)
cwidth = percWidth(prd, ChannelW)
zonePerc = percWidth(300, zoneWidth)
aas = array.new_bool(41, true)
u1 = 0.0, u1 := nz(u1 )
d1 = 0.0, d1 := nz(d1 )
highestph = 0.0, highestph := highestph
lowestpl = 0.0, lowestpl := lowestpl
var sr_levs = array.new_float(21, na)
label hlabel = na, label.delete(hlabel )
label llabel = na, label.delete(llabel )
var sr_lines = array.new_line(21, na)
var sr_linesH = array.new_line(21, na)
var sr_linesL = array.new_line(21, na)
var sr_linesF = array.new_linefill(21, na)
var sr_labels = array.new_label(21, na)
if (not na(ph) or not na(pl))
for x = 0 to array.size(sr_levels) - 1
array.set(sr_levels, x, na)
highestph := prdlowest
lowestpl := prdhighest
countpp = 0
for x = 0 to prd
if na(close )
break
if not na(ph ) or not na(pl )
highestph := math.max(highestph, nz(ph , prdlowest), nz(pl , prdlowest))
lowestpl := math.min(lowestpl, nz(ph , prdhighest), nz(pl , prdhighest))
countpp += 1
if countpp > 40
break
if array.get(aas, countpp)
upl = (not na(ph ) and (ph != 0) ? high : low ) + cwidth
dnl = (not na(ph ) and (ph != 0) ? high : low ) - cwidth
u1 := countpp == 1 ? upl : u1
d1 := countpp == 1 ? dnl : d1
tmp = array.new_bool(41, true)
cnt = 0
tpoint = 0
for xx = 0 to prd
if na(close )
break
if not na(ph ) or not na(pl )
chg = false
cnt += 1
if cnt > 40
break
if array.get(aas, cnt)
if not na(ph )
if high <= upl and high >= dnl
tpoint += 1
chg := true
if not na(pl )
if low <= upl and low >= dnl
tpoint += 1
chg := true
if chg and cnt < 41
array.set(tmp, cnt, false)
if tpoint >= strengthSR
for g = 0 to 40 by 1
if not array.get(tmp, g)
array.set(aas, g, false)
if (not na(ph ) and countpp < 21)
array.set(sr_levels, countpp, high )
if (not na(pl ) and countpp < 21)
array.set(sr_levels, countpp, low )
// Plot
var line highest_ = na, line.delete(highest_)
var line lowest_ = na, line.delete(lowest_)
var line highest_fill1 = na, line.delete(highest_fill1)
var line highest_fill2 = na, line.delete(highest_fill2)
var line lowest_fill1 = na, line.delete(lowest_fill1)
var line lowest_fill2 = na, line.delete(lowest_fill2)
hi_col = close >= highestph ? colorSup : colorRes
lo_col = close >= lowestpl ? colorSup : colorRes
if enableSR
highest_ := line.new(bar_index - 311, highestph, bar_index, highestph, xloc.bar_index, expandSR ? extend.both : extend.right, hi_col, style, lineWidth)
lowest_ := line.new(bar_index - 311, lowestpl , bar_index, lowestpl , xloc.bar_index, expandSR ? extend.both : extend.right, lo_col, style, lineWidth)
if useHLZones
highest_fill1 := line.new(bar_index - 311, highestph + zonePerc, bar_index, highestph + zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na)
highest_fill2 := line.new(bar_index - 311, highestph - zonePerc, bar_index, highestph - zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na)
lowest_fill1 := line.new(bar_index - 311, lowestpl + zonePerc , bar_index, lowestpl + zonePerc , xloc.bar_index, expandSR ? extend.both : extend.right, na)
lowest_fill2 := line.new(bar_index - 311, lowestpl - zonePerc , bar_index, lowestpl - zonePerc , xloc.bar_index, expandSR ? extend.both : extend.right, na)
linefill.new(highest_fill1, highest_fill2, hi_col)
linefill.new(lowest_fill1 , lowest_fill2 , lo_col)
if (not na(ph) or not na(pl))
for x = 0 to array.size(sr_lines) - 1
array.set(sr_levs, x, array.get(sr_levels, x))
for x = 0 to array.size(sr_lines) - 1
line.delete(array.get(sr_lines, x))
line.delete(array.get(sr_linesH, x))
line.delete(array.get(sr_linesL, x))
linefill.delete(array.get(sr_linesF, x))
if (not na(array.get(sr_levs, x)) and enableSR)
line_col = close >= array.get(sr_levs, x) ? colorSup : colorRes
array.set(sr_lines, x, line.new(bar_index - 355, array.get(sr_levs, x), bar_index, array.get(sr_levs, x), xloc.bar_index, expandSR ? extend.both : extend.right, line_col, style, lineWidth))
if useZones
array.set(sr_linesH, x, line.new(bar_index - 355, array.get(sr_levs, x) + zonePerc, bar_index, array.get(sr_levs, x) + zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na))
array.set(sr_linesL, x, line.new(bar_index - 355, array.get(sr_levs, x) - zonePerc, bar_index, array.get(sr_levs, x) - zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na))
array.set(sr_linesF, x, linefill.new(array.get(sr_linesH, x), array.get(sr_linesL, x), line_col))
for x = 0 to array.size(sr_labels) - 1
label.delete(array.get(sr_labels, x))
if (not na(array.get(sr_levs, x)) and enableSR)
lab_loc = close >= array.get(sr_levs, x) ? label.style_label_up : label.style_label_down
lab_col = close >= array.get(sr_levs, x) ? colorSup : colorRes
array.set(sr_labels, x, label.new(bar_index + label_loc, array.get(sr_levs, x), str.tostring(math.round_to_mintick(array.get(sr_levs, x))), color=lab_col , textcolor=#000000, style=lab_loc))
hlabel := enableSR ? label.new(bar_index + label_loc + math.round(math.sign(label_loc)) * 20, highestph, "High Level : " + str.tostring(highestph), color=hi_col, textcolor=#000000, style=label.style_label_down) : na
llabel := enableSR ? label.new(bar_index + label_loc + math.round(math.sign(label_loc)) * 20, lowestpl , "Low Level : " + str.tostring(lowestpl) , color=lo_col, textcolor=#000000, style=label.style_label_up ) : na
// Get components
rsi = ta.rsi(close, 28)
//rsiOb = rsi > 78 and rsi > ta.ema(rsi, 10)
//rsiOs = rsi < 27 and rsi < ta.ema(rsi, 10)
rsiOb = rsi > 65 and rsi > ta.ema(rsi, 10)
rsiOs = rsi < 35 and rsi < ta.ema(rsi, 10)
dHigh = securityNoRep(syminfo.tickerid, "D", high )
dLow = securityNoRep(syminfo.tickerid, "D", low )
dClose = securityNoRep(syminfo.tickerid, "D", close )
ema = ta.ema(close, 144)
emaBull = close > ema
equal_tf(res) => str.tonumber(res) == f_chartTfInMinutes() and not timeframe.isseconds
higher_tf(res) => str.tonumber(res) > f_chartTfInMinutes() or timeframe.isseconds
too_small_tf(res) => (timeframe.isweekly and res=="1") or (timeframe.ismonthly and str.tonumber(res) < 10)
securityNoRep1(sym, res, src) =>
bool bull_ = na
bull_ := equal_tf(res) ? src : bull_
bull_ := higher_tf(res) ? request.security(sym, res, src, barmerge.gaps_off, barmerge.lookahead_on) : bull_
bull_array = request.security_lower_tf(syminfo.tickerid, higher_tf(res) ? str.tostring(f_chartTfInMinutes()) + (timeframe.isseconds ? "S" : "") : too_small_tf(res) ? (timeframe.isweekly ? "3" : "10") : res, src)
if array.size(bull_array) > 1 and not equal_tf(res) and not higher_tf(res)
bull_ := array.pop(bull_array)
array.clear(bull_array)
bull_
// === BASE FUNCTIONS ===
// Returns MA input selection variant, default to SMA if blank or typo.
variant(type, src, len, offSig, offALMA) =>
v1 = ta.sma(src, len) // Simple
v2 = ta.ema(src, len) // Exponential
v3 = 2 * v2 - ta.ema(v2, len) // Double Exponential
v4 = 3 * (v2 - ta.ema(v2, len)) + ta.ema(ta.ema(v2, len), len) // Triple Exponential
v5 = ta.wma(src, len) // Weighted
v6 = ta.vwma(src, len) // Volume Weighted
v7 = 0.0
sma_1 = ta.sma(src, len) // Smoothed
v7 := na(v7 ) ? sma_1 : (v7 * (len - 1) + src) / len
v8 = ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len))) // Hull
v9 = ta.linreg(src, len, offSig) // Least Squares
v10 = ta.alma(src, len, offALMA, offSig) // Arnaud Legoux
v11 = ta.sma(v1, len) // Triangular (extreme smooth)
// SuperSmoother filter
// 2013 John F. Ehlers
a1 = math.exp(-1.414 * 3.14159 / len)
b1 = 2 * a1 * math.cos(1.414 * 3.14159 / len)
c2 = b1
c3 = -a1 * a1
c1 = 1 - c2 - c3
v12 = 0.0
v12 := c1 * (src + nz(src )) / 2 + c2 * nz(v12 ) + c3 * nz(v12 )
type == 'EMA' ? v2 : type == 'DEMA' ? v3 : type == 'TEMA' ? v4 : type == 'WMA' ? v5 : type == 'VWMA' ? v6 : type == 'SMMA' ? v7 : type == 'HullMA' ? v8 : type == 'LSMA' ? v9 : type == 'ALMA' ? v10 : type == 'TMA' ? v11 : type == 'SSMA' ? v12 : v1
// security wrapper for repeat calls
reso(exp, use, res) =>
security_1 = request.security(syminfo.tickerid, res, exp, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
use ? security_1 : exp
// === /BASE FUNCTIONS ===
// === SERIES SETUP ===
closeSeries = variant(basisType, close , basisLen, offsetSigma, offsetALMA)
openSeries = variant(basisType, open , basisLen, offsetSigma, offsetALMA)
// === /SERIES ===
// Get Alternate resolution Series if selected.
closeSeriesAlt = reso(closeSeries, useRes, stratRes)
openSeriesAlt = reso(openSeries, useRes, stratRes)
//
lxTrigger = false
sxTrigger = false
leTrigger = ta.crossover (closeSeriesAlt, openSeriesAlt)
seTrigger = ta.crossunder(closeSeriesAlt, openSeriesAlt)
G_RISK = '■ ' + 'Risk Management'
//#region ———— <↓↓↓ G_RISK ↓↓↓> {
// ———————————
//Tooltip
T_LVL = '(%) Exit Level'
T_QTY = '(%) Adjust trade exit volume'
T_MSG = 'Paste JSON message for your bot'
//Webhook Message
O_LEMSG = 'Long Entry'
O_LXMSGSL = 'Long SL'
O_LXMSGTP1 = 'Long TP1'
O_LXMSGTP2 = 'Long TP2'
O_LXMSGTP3 = 'Long TP3'
O_LXMSG = 'Long Exit'
O_SEMSG = 'Short Entry'
O_SXMSGSL = 'Short SL'
O_SXMSGA = 'Short TP1'
O_SXMSGB = 'Short TP2'
O_SXMSGC = 'Short TP3'
O_SXMSGX = 'Short Exit'
// ——————————— | | | Line length guide |
i_lxLvlTP1 = input.float (0.2, 'Level TP1' , group = G_RISK,
tooltip = T_LVL)
i_lxQtyTP1 = input.float (80.0, 'Qty TP1' , group = G_RISK,
tooltip = T_QTY)
i_lxLvlTP2 = input.float (0.5, 'Level TP2' , group = G_RISK,
tooltip = T_LVL)
i_lxQtyTP2 = input.float (10.0, 'Qty TP2' , group = G_RISK,
tooltip = T_QTY)
i_lxLvlTP3 = input.float (7.0, 'Level TP3' , group = G_RISK,
tooltip = T_LVL)
i_lxQtyTP3 = input.float (2, 'Qty TP3' , group = G_RISK,
tooltip = T_QTY)
i_lxLvlSL = input.float (0.5, 'Stop Loss' , group = G_RISK,
tooltip = T_LVL)
i_sxLvlTP1 = i_lxLvlTP1
i_sxQtyTP1 = i_lxQtyTP1
i_sxLvlTP2 = i_lxLvlTP2
i_sxQtyTP2 = i_lxQtyTP2
i_sxLvlTP3 = i_lxLvlTP3
i_sxQtyTP3 = i_lxQtyTP3
i_sxLvlSL = i_lxLvlSL
G_MSG = '■ ' + 'Webhook Message'
i_leMsg = input.string (O_LEMSG ,'Long Entry' , group = G_MSG, tooltip = T_MSG)
i_lxMsgSL = input.string (O_LXMSGSL ,'Long SL' , group = G_MSG, tooltip = T_MSG)
i_lxMsgTP1 = input.string (O_LXMSGTP1,'Long TP1' , group = G_MSG, tooltip = T_MSG)
i_lxMsgTP2 = input.string (O_LXMSGTP2,'Long TP2' , group = G_MSG, tooltip = T_MSG)
i_lxMsgTP3 = input.string (O_LXMSGTP3,'Long TP3' , group = G_MSG, tooltip = T_MSG)
i_lxMsg = input.string (O_LXMSG ,'Long Exit' , group = G_MSG, tooltip = T_MSG)
i_seMsg = input.string (O_SEMSG ,'Short Entry' , group = G_MSG, tooltip = T_MSG)
i_sxMsgSL = input.string (O_SXMSGSL ,'Short SL' , group = G_MSG, tooltip = T_MSG)
i_sxMsgTP1 = input.string (O_SXMSGA ,'Short TP1' , group = G_MSG, tooltip = T_MSG)
i_sxMsgTP2 = input.string (O_SXMSGB ,'Short TP2' , group = G_MSG, tooltip = T_MSG)
i_sxMsgTP3 = input.string (O_SXMSGC ,'Short TP3' , group = G_MSG, tooltip = T_MSG)
i_sxMsg = input.string (O_SXMSGX ,'Short Exit' , group = G_MSG, tooltip = T_MSG)
i_src = close
G_DISPLAY = 'Display'
//
i_alertOn = input.bool (true, 'Alert Labels On/Off' , group = G_DISPLAY)
i_barColOn = input.bool (true, 'Bar Color On/Off' , group = G_DISPLAY)
// ———————————
// @function Calculate the Take Profit line, and the crossover or crossunder
f_tp(_condition, _conditionValue, _leTrigger, _seTrigger, _src, _lxLvlTP, _sxLvlTP)=>
var float _tpLine = 0.0
_topLvl = _src + (_src * (_lxLvlTP / 100))
_botLvl = _src - (_src * (_sxLvlTP / 100))
_tpLine := _condition != _conditionValue and _leTrigger ? _topLvl :
_condition != -_conditionValue and _seTrigger ? _botLvl :
nz(_tpLine )
// @function Similar to "ta.crossover" or "ta.crossunder"
f_cross(_scr1, _scr2, _over)=>
_cross = _over ? _scr1 > _scr2 and _scr1 < _scr2 :
_scr1 < _scr2 and _scr1 > _scr2
// ———————————
//
var float condition = 0.0
var float slLine = 0.0
var float entryLine = 0.0
//
entryLine := leTrigger and condition <= 0.0 ? close :
seTrigger and condition >= 0.0 ? close : nz(entryLine )
//
slTopLvl = i_src + (i_src * (i_lxLvlSL / 100))
slBotLvl = i_src - (i_src * (i_sxLvlSL / 100))
slLine := condition <= 0.0 and leTrigger ? slBotLvl :
condition >= 0.0 and seTrigger ? slTopLvl : nz(slLine )
slLong = f_cross(low, slLine, false)
slShort = f_cross(high, slLine, true )
//
= f_tp(condition, 1.2,leTrigger, seTrigger, i_src, i_lxLvlTP3, i_sxLvlTP3)
= f_tp(condition, 1.1,leTrigger, seTrigger, i_src, i_lxLvlTP2, i_sxLvlTP2)
= f_tp(condition, 1.0,leTrigger, seTrigger, i_src, i_lxLvlTP1, i_sxLvlTP1)
tp3Long = f_cross(high, tp3Line, true )
tp3Short = f_cross(low, tp3Line, false)
tp2Long = f_cross(high, tp2Line, true )
tp2Short = f_cross(low, tp2Line, false)
tp1Long = f_cross(high, tp1Line, true )
tp1Short = f_cross(low, tp1Line, false)
switch
leTrigger and condition <= 0.0 => condition := 1.0
seTrigger and condition >= 0.0 => condition := -1.0
tp3Long and condition == 1.2 => condition := 1.3
tp3Short and condition == -1.2 => condition := -1.3
tp2Long and condition == 1.1 => condition := 1.2
tp2Short and condition == -1.1 => condition := -1.2
tp1Long and condition == 1.0 => condition := 1.1
tp1Short and condition == -1.0 => condition := -1.1
slLong and condition >= 1.0 => condition := 0.0
slShort and condition <= -1.0 => condition := 0.0
lxTrigger and condition >= 1.0 => condition := 0.0
sxTrigger and condition <= -1.0 => condition := 0.0
longE = leTrigger and condition <= 0.0 and condition == 1.0
shortE = seTrigger and condition >= 0.0 and condition == -1.0
longX = lxTrigger and condition >= 1.0 and condition == 0.0
shortX = sxTrigger and condition <= -1.0 and condition == 0.0
longSL = slLong and condition >= 1.0 and condition == 0.0
shortSL = slShort and condition <= -1.0 and condition == 0.0
longTP3 = tp3Long and condition == 1.2 and condition == 1.3
shortTP3 = tp3Short and condition == -1.2 and condition == -1.3
longTP2 = tp2Long and condition == 1.1 and condition == 1.2
shortTP2 = tp2Short and condition == -1.1 and condition == -1.2
longTP1 = tp1Long and condition == 1.0 and condition == 1.1
shortTP1 = tp1Short and condition == -1.0 and condition == -1.1
// ——————————— {
//
if strategy.position_size <= 0 and longE and barstate.isconfirmed
strategy.entry(
'Long',
strategy.long,
alert_message = i_leMsg,
comment = 'LE')
if strategy.position_size > 0 and condition == 1.0
strategy.exit(
id = 'LXTP1',
from_entry = 'Long',
qty_percent = i_lxQtyTP1,
limit = tp1Line,
stop = slLine,
comment_profit = 'LXTP1',
comment_loss = 'SL',
alert_profit = i_lxMsgTP1,
alert_loss = i_lxMsgSL)
if strategy.position_size > 0 and condition == 1.1
strategy.exit(
id = 'LXTP2',
from_entry = 'Long',
qty_percent = i_lxQtyTP2,
limit = tp2Line,
stop = slLine,
comment_profit = 'LXTP2',
comment_loss = 'SL',
alert_profit = i_lxMsgTP2,
alert_loss = i_lxMsgSL)
if strategy.position_size > 0 and condition == 1.2
strategy.exit(
id = 'LXTP3',
from_entry = 'Long',
qty_percent = i_lxQtyTP3,
limit = tp3Line,
stop = slLine,
comment_profit = 'LXTP3',
comment_loss = 'SL',
alert_profit = i_lxMsgTP3,
alert_loss = i_lxMsgSL)
if longX
strategy.close(
'Long',
alert_message = i_lxMsg,
comment = 'LX')
//
if strategy.position_size >= 0 and shortE and barstate.isconfirmed
strategy.entry(
'Short',
strategy.short,
alert_message = i_leMsg,
comment = 'SE')
if strategy.position_size < 0 and condition == -1.0
strategy.exit(
id = 'SXTP1',
from_entry = 'Short',
qty_percent = i_sxQtyTP1,
limit = tp1Line,
stop = slLine,
comment_profit = 'SXTP1',
comment_loss = 'SL',
alert_profit = i_sxMsgTP1,
alert_loss = i_sxMsgSL)
if strategy.position_size < 0 and condition == -1.1
strategy.exit(
id = 'SXTP2',
from_entry = 'Short',
qty_percent = i_sxQtyTP2,
limit = tp2Line,
stop = slLine,
comment_profit = 'SXTP2',
comment_loss = 'SL',
alert_profit = i_sxMsgTP2,
alert_loss = i_sxMsgSL)
if strategy.position_size < 0 and condition == -1.2
strategy.exit(
id = 'SXTP3',
from_entry = 'Short',
qty_percent = i_sxQtyTP3,
limit = tp3Line,
stop = slLine,
comment_profit = 'SXTP3',
comment_loss = 'SL',
alert_profit = i_sxMsgTP3,
alert_loss = i_sxMsgSL)
if shortX
strategy.close(
'Short',
alert_message = i_sxMsg,
comment = 'SX')
// ———————————
c_tp = leTrigger or seTrigger ? na :
condition == 0.0 ? na : color.green
c_entry = leTrigger or seTrigger ? na :
condition == 0.0 ? na : color.blue
c_sl = leTrigger or seTrigger ? na :
condition == 0.0 ? na : color.red
p_tp1Line = plot (
condition == 1.0 or
condition == -1.0 ? tp1Line : na,
title = "TP Line 1",
color = c_tp,
linewidth = 1,
style = plot.style_linebr)
p_tp2Line = plot (
condition == 1.0 or
condition == -1.0 or
condition == 1.1 or
condition == -1.1 ? tp2Line : na,
title = "TP Line 2",
color = c_tp,
linewidth = 1,
style = plot.style_linebr)
p_tp3Line = plot (
condition == 1.0 or
condition == -1.0 or
condition == 1.1 or
condition == -1.1 or
condition == 1.2 or
condition == -1.2 ? tp3Line : na,
title = "TP Line 3",
color = c_tp,
linewidth = 1,
style = plot.style_linebr)
p_entryLine = plot (
condition >= 1.0 or
condition <= -1.0 ? entryLine : na,
title = "Entry Line",
color = c_entry,
linewidth = 1,
style = plot.style_linebr)
p_slLine = plot (
condition == 1.0 or
condition == -1.0 or
condition == 1.1 or
condition == -1.1 or
condition == 1.2 or
condition == -1.2 ? slLine : na,
title = "SL Line",
color = c_sl,
linewidth = 1,
style = plot.style_linebr)
fill(
p_tp3Line, p_entryLine,
color = leTrigger or seTrigger ? na :color.new(color.green, 90))
fill(
p_entryLine, p_slLine,
color = leTrigger or seTrigger ? na :color.new(color.red, 90))
//
plotshape(
i_alertOn and longE,
title = 'Long',
text = 'Long',
textcolor = color.white,
color = color.green,
style = shape.labelup,
size = size.tiny,
location = location.belowbar)
plotshape(
i_alertOn and shortE,
title = 'Short',
text = 'Short',
textcolor = color.white,
color = color.red,
style = shape.labeldown,
size = size.tiny,
location = location.abovebar)
plotshape(
i_alertOn and (longX or shortX) ? close : na,
title = 'Close',
text = 'Close',
textcolor = color.white,
color = color.gray,
style = shape.labelup,
size = size.tiny,
location = location.absolute)
l_tp = i_alertOn and (longTP1 or shortTP1) ? close : na
plotshape(
l_tp,
title = "TP1 Cross",
text = "TP1",
textcolor = color.white,
color = color.olive,
style = shape.labelup,
size = size.tiny,
location = location.absolute)
plotshape(
i_alertOn and (longTP2 or shortTP2) ? close : na,
title = "TP2 Cross",
text = "TP2",
textcolor = color.white,
color = color.olive,
style = shape.labelup,
size = size.tiny,
location = location.absolute)
plotshape(
i_alertOn and (longTP3 or shortTP3) ? close : na,
title = "TP3 Cross",
text = "TP3",
textcolor = color.white,
color = color.olive,
style = shape.labelup,
size = size.tiny,
location = location.absolute)
plotshape(
i_alertOn and (longSL or shortSL) ? close : na,
title = "SL Cross",
text = "SL",
textcolor = color.white,
color = color.maroon,
style = shape.labelup,
size = size.tiny,
location = location.absolute)
//
plot(
na,
title = "─── ───",
editable = false,
display = display.data_window)
plot(
condition,
title = "condition",
editable = false,
display = display.data_window)
plot(
strategy.position_size * 100,
title = ".position_size",
editable = false,
display = display.data_window)
//#endregion }
// ——————————— <↑↑↑ G_RISK ↑↑↑>
//#region ———— <↓↓↓ G_SCRIPT02 ↓↓↓> {
// @function Queues a new element in an array and de-queues its first element.
f_qDq(_array, _val) =>
array.push(_array, _val)
_return = array.shift(_array)
_return
var line a_slLine = array.new_line(1)
var line a_entryLine = array.new_line(1)
var line a_tp3Line = array.new_line(1)
var line a_tp2Line = array.new_line(1)
var line a_tp1Line = array.new_line(1)
var label a_slLabel = array.new_label(1)
var label a_tp3label = array.new_label(1)
var label a_tp2label = array.new_label(1)
var label a_tp1label = array.new_label(1)
var label a_entryLabel = array.new_label(1)
newEntry = longE or shortE
entryIndex = 1
entryIndex := newEntry ? bar_index : nz(entryIndex )
lasTrade = bar_index >= entryIndex
l_right = 10
line.delete(
f_qDq(a_slLine,
line.new(
entryIndex,
slLine,
last_bar_index + l_right,
slLine,
style = line.style_solid,
color = c_sl)))
line.delete(
f_qDq(a_entryLine,
line.new(
entryIndex,
entryLine,
last_bar_index + l_right,
entryLine,
style = line.style_solid,
color = color.blue)))
line.delete(
f_qDq(a_tp3Line,
line.new(
entryIndex,
tp3Line,
last_bar_index + l_right,
tp3Line,
style = line.style_solid,
color = c_tp)))
line.delete(
f_qDq(a_tp2Line,
line.new(
entryIndex,
tp2Line,
last_bar_index + l_right,
tp2Line,
style = line.style_solid,
color = c_tp)))
line.delete(
f_qDq(a_tp1Line,
line.new(
entryIndex,
tp1Line,
last_bar_index + l_right,
tp1Line,
style = line.style_solid,
color = c_tp)))
label.delete(
f_qDq(a_slLabel,
label.new(
last_bar_index + l_right,
slLine,
'SL: ' + str.tostring(slLine, '##.###'),
style = label.style_label_left,
textcolor = color.white,
color = c_sl)))
label.delete(
f_qDq(a_entryLabel,
label.new(
last_bar_index + l_right,
entryLine,
'Entry: ' + str.tostring(entryLine, '##.###'),
style = label.style_label_left,
textcolor = color.white,
color = color.blue)))
label.delete(
f_qDq(a_tp3label,
label.new(
last_bar_index + l_right,
tp3Line,
'TP3: ' + str.tostring(tp3Line, '##.###'),
style = label.style_label_left,
textcolor = color.white,
color = c_tp)))
label.delete(
f_qDq(a_tp2label,
label.new(
last_bar_index + l_right,
tp2Line,
'TP2: ' + str.tostring(tp2Line, '##.###'),
style = label.style_label_left,
textcolor = color.white,
color = c_tp)))
label.delete(
f_qDq(a_tp1label,
label.new(
last_bar_index + l_right,
tp1Line,
'TP1: ' + str.tostring(tp1Line, '##.###'),
style = label.style_label_left,
textcolor = color.white,
color = c_tp)))
// ———————————
//
if longE or shortE or longX or shortX
alert(message = 'Any Alert', freq = alert.freq_once_per_bar_close)
if longE
alert(message = 'Long Entry', freq = alert.freq_once_per_bar_close)
if shortE
alert(message = 'Short Entry', freq = alert.freq_once_per_bar_close)
if longX
alert(message = 'Long Exit', freq = alert.freq_once_per_bar_close)
if shortX
alert(message = 'Short Exit', freq = alert.freq_once_per_bar_close)
//#endregion }
// ——————————— <↑↑↑ G_SCRIPT03 ↑↑↑>
UT Bot Alerts with R-Targets & Results< DONE BY RM ALOWAIS >
Indicator Overview
This indicator provides rule-based BUY and SELL signals with automatic risk management levels.
Each trade setup includes a predefined Stop Loss and up to three Take Profit targets (TP1, TP2, TP3), allowing traders to manage risk and scale exits systematically.
How It Works
BUY and SELL signals are generated based on internal market conditions.
Each signal plots:
Entry point
Stop Loss (SL)
Take Profit levels (TP1, TP2, TP3)
After price action completes, the indicator displays the actual result of the trade:
Result: TP1 / TP2 / TP3 / SL
Exit labels may appear when a trade is closed early due to invalidation or opposite conditions.
Key Features
Non-repainting signals
Built-in risk-to-reward structure
Visual trade tracking with clear outcomes
Suitable for intraday and swing trading
Works on multiple markets and timeframes
Usage Notes
This indicator is a decision-support tool, not financial advice.
Best results are achieved when used with proper risk management and higher-timeframe confirmation.
Performance may vary depending on market conditions (trend vs range).
Disclaimer
This script is provided for educational and informational purposes only.
The author is not responsible for any financial losses. Always test and validate before using in live trading.
Alpha Accumulator v3.4OVERVIEW
Alpha Accumulator is an intelligent accumulation strategy that outperforms traditional Dollar-Cost Averaging (DCA) by deploying capital proportionally to market dip severity. Instead of buying the same amount every week regardless of price, Alpha Accumulator "starves" small pullbacks and "feasts" on corrections.
The core philosophy: When the market gives you a real opportunity, take it seriously.
HOW IT WORKS
For Example:
Traditional DCA: Buy $100 every week, no matter what.
Alpha Accumulator: Buy based on how deep the dip is.
┌─────────────────┬───────────────┬─────────────────┐
│ Market Dip │ DCA Buys │ Alpha Buys │
├─────────────────┼───────────────┼─────────────────┤
│ -5% pullback │ $100 │ $200 (2x) │
│ -10% correction│ $100 │ $1200 (12x) │
│ -16% deep dip │ $100 │ $3800 (38x) │
└─────────────────┴───────────────┴─────────────────┘
The result? Lower average cost, higher returns, same or similar total capital deployed.
KEY FEATURES
⯁ SMART DIP DETECTION
Combines multiple technical signals to identify high-probability accumulation zones:
• Volume spike confirmation (panic selling = opportunity)
• Volatility expansion (ATR/StdDev spike)
• Price below EMAs (discount to trend)
• Bearish structure (EMA20 < EMA50)
⯁ AUTO-DETECT SYMBOL PROFILES
Automatically selects optimized multipliers based on your chart:
• 🔵 SPY: Low volatility → Higher multipliers (fewer signals, must capitalize)
• 🟢 QQQ: Medium volatility → Balanced multipliers
• 🔴 SMH: High volatility → Lower multipliers (more frequent signals)
10-TIER MULTIPLIER SYSTEM
⯁ PROFESSIONAL METRICS DASHBOARD
Real-time comparison between Alpha Accumulator and traditional DCA:
• CAGR (Compound Annual Growth Rate) - Time-weighted returns
• Sortino Ratio - Risk-adjusted performance
• Maximum Drawdown - Worst decline experienced
• Capital Ratio - How much capital deployed vs DCA
• Cost Advantage - Average cost basis improvement
MULTIPLIER PROFILES
The indicator includes 9 pre-built profiles for different risk tolerances:
SYMBOL-SPECIFIC (Auto-detected):
• SPY Optimized
• QQQ Optimized
• SMH Optimized
GENERIC PROFILES:
• Conservative - Cap ~1.0x, Max 35x (Match DCA capital)
• Balanced - Cap ~1.2x, Max 45x
• CAGR Balanced - Cap ~1.5x, Max 50x
• Aggressive - Cap ~1.8x, Max 60x
• CAGR Optimized - Cap ~2.0x, Max 65x
• Custom - Define your own 10-tier multiplier ladder
VISUAL SIGNALS
🔵 Blue Triangle = STARVE signal (low multiplier, small buy)
🟠 Orange Triangle = RAMP signal (medium multiplier)
🟡 Yellow Triangle = TRANSITION signal
🟢 Green Triangle = FEAST signal (high multiplier, big buy)
💚 Bright Green = MAX FEAST signal (maximum deployment)
Each signal displays:
• Current multiplier (e.g., "12.5x")
• Dollar amount to deploy
• Entry price
SETTINGS GUIDE
DIP FINDER SETTINGS (Match to your Dip Finder indicator):
• Vol Lookback: 65 (bars for volume average)
• Vol Spike: 2.0x (volume must exceed this multiple)
• Fast/Slow EMA: 20/50
• Volatility Len: 14
• Dip %: 2.0% (minimum price drop)
• Min Gap: 5 bars (cooldown between signals)
STRATEGY SETTINGS:
• DCA Buy Amount: Your regular DCA amount (e.g., $100/week)
• Base Lump-Sum: Base amount for Alpha signals (multiplied by tier)
• Start Date: Backtest start date
INTERPRETING RESULTS
The results table shows head-to-head comparison:
✅ ALPHA WINS when:
• Higher CAGR (better returns)
• Higher Sortino (better risk-adjusted returns)
• Lower Avg Cost (buying at better prices)
• Positive Cost Advantage %
📊 CAP RATIO explained:
• 1.0x = Alpha deployed same capital as DCA
• 0.5x = Alpha deployed half the capital
• 1.5x = Alpha deployed 50% more capital
🎯 IDEAL SETUP:
• Cap Ratio: 0.9x - 1.3x (similar capital to DCA)
• Cost Advantage: +5% to +15%
• CAGR Outperformance: +1% to +5%
█ BEST PRACTICES
1. MATCH YOUR DIP FINDER
If you use a separate Dip Finder indicator, match its settings here for consistency.
2. SET REALISTIC BASE AMOUNTS
Base Lump-Sum × Max Multiplier = Maximum single buy
3. HAVE CAPITAL READY
Alpha Accumulator requires available capital when signals fire.
Keep a "dry powder" reserve for deep corrections.
4. TRUST THE SIGNALS
The system is designed to deploy heavily in corrections.
If you can't stomach a higher buy during a crash, lower your base amount.
5. LONG-TERM MINDSET
Best results come from multi-year holding periods.
This is an accumulation strategy, not a trading system.
ALERTS
Set up alerts to never miss a signal:
• "Buy Signal" - Triggers on every valid dip signal
• Includes: Symbol, Price, Multiplier, Dollar Amount, Shares to Buy
• Bot-friendly JSON format for automated trading
DISCLAIMER
This indicator is for educational purposes only. Past performance does not guarantee future results. Always do your own research and never invest more than you can afford to lose. The multiplier system can result in very large position sizes during market corrections - ensure you have appropriate risk management in place.
Developed by Sahebson
Built for long-term accumulators who believe in buying fear
EMA - SHORT (8/20)EMA SHORT (8/20) trades only the short side by waiting for bearish regime alignment and then capturing continuation once momentum confirms. It ignores long signals entirely and filters out sideways chop or late entries.
Built to:
✔ Confirm bearish direction
✔ Avoid compression phases
✔ Filter weak flips
✔ Simulate short execution visually
✔ Enable automation via Webhooks
Ideal for:
Futures traders (short bias)
Breakout & momentum traders
Signal providers
Copy-trading systems
Bot builders
Works across timeframes from scalping to swing, with strong performance in futures, crypto, and FX.
EMA - LONG (8/20)EMA LONG (8/20) trades only the long side by waiting for bullish regime alignment and then capturing continuation after momentum confirms. It ignores short signals entirely and avoids early flip entries, focusing on cleaner post-flip continuation legs.
Designed to:
✔ Filter out sideways compression
✔ Avoid counter-trend shorts
✔ Confirm long-side momentum
✔ Simulate entries/exits visually
✔ Enable alerts for automation
Works across timeframes and instruments, with strong use cases in futures, crypto, and FX.
Ideal for:
Trend continuation traders
Long-biased futures traders
Bot automation / signal providers
Copy trading setups
Precision Trend Signal V5Strategy Logic OverviewThis indicator is a "Triple-Confirmation" trend-following system. It combines volume-weighted smoothing, immediate price action, and momentum filtering.1. Core ComponentsEMA 1 (The Trigger): Since the period is set to 1, this represents the raw price action. It acts as the fastest possible trigger to capture entries at the exact moment a trend shifts.SALMA (The Baseline): This is a double-smoothed moving average. It provides a stabilized support/resistance line that filters out market noise better than a standard SMA.Tillson T3 (The Trend Filter): Known for its low lag and extreme smoothness. We use this as a "Guardrail." We only take BUY signals when price is above the T3 and SELL signals when price is below it.RSI (The Momentum Filter): Ensures that we only enter a trade when there is sufficient strength ($> 50$ for Long, $< 50$ for Short).2. Signal Rules🚀 BUY SignalA green BUY label appears when:Crossover: EMA 1 crosses above the SALMA line.Trend: The current price is trading above the Tillson T3 line.Momentum: RSI is greater than 50.🔻 SELL SignalA red SELL label appears when:Crossunder: EMA 1 crosses below the SALMA line.Trend: The current price is trading below the Tillson T3 line.Momentum: RSI is less than 50.3. Execution & ManagementTake Profit (TP): Based on your preference, the suggested target is 2%.Alerts: The script includes alertcondition functions. You can set up TradingView alerts to send Webhooks to your quant infrastructure or bot, solving the "manual execution" problem you mentioned.
Crash Prevention OpenSource by exp3rtsOpen Source Version - no updates!
Crash Prevention OpenSource by exp3rts – Automated Exit Strategy for TradingView
This indicator allows you to automatically close positions based on dynamic price levels derived from the previous candle with a configurable offset. Perfect for risk management and automated “hard stop” exits.
Key Features:
Flexible Exit Directions: Choose to trigger exits for Long, Short, or Both directions.
Dynamic Exit Levels: Lines are automatically calculated above/below the previous candle plus/minus a user-defined offset in points.
Visual Cues: Clear arrows indicate the exact bar where price touched the exit line.
Session-Independent: Works on any chart and timeframe without manual adjustments.
Webhook Alerts: Sends JSON alerts on touch, enabling integration with external systems or bots.
Auto-Close Logic: Ensures positions are closed immediately when the threshold is breached, keeping trades in check.
How it works:
For Long exits, the line is drawn below the previous bar’s low minus the offset.
For Short exits, the line is drawn above the previous bar’s high plus the offset.
When price crosses the line, the position is closed, an arrow is plotted on the chart, and an alert is fired.
Ideal for traders who want strict stop management or automated exit conditions while keeping visual clarity on the chart.
CVDSKYuses CVD and price action to determine pivot points this is a private bot only used by my active members on the discord.
Kalman Absorption/Distribution Tracker (1 Second)The Microstructure Revolution: Kalman Filtering and the Physics of Order Flow
The evolution of technical analysis has historically been constrained by the limitations of available data and the processing power required to interpret it. For decades, retail traders have relied on indicators derived from Open, High, Low, and Close prices—metrics that are inherently reactive and fundamentally lagging. While these tools can effectively map the history of market movement, they often fail to capture the immediate, aggressive intent that dictates future price action. The financial markets are not merely a sequence of price prints; they are a continuous, high-velocity auction where liquidity is provided and consumed in milliseconds. To truly understand the mechanics of price delivery, one must look beyond the candlestick and into the microstructure of the order flow itself. The Kalman Absorption/Distribution Tracker, specifically designed to operate on 1-second intrabar intervals, represents a paradigm shift in this analytical approach. It abandons the simplistic smoothing of moving averages in favor of a state-space model that applies aerospace-grade signal processing to the chaotic environment of high-frequency market data.
At the core of this concept is the understanding that volume alone is insufficient; it is the relationship between aggressive volume and price displacement that reveals the hand of institutional participants. Traditional volume analysis is often binary, categorizing bars as simply "up" or "down," a method that obscures the nuances of the battle taking place within the timeframe. By drilling down to the 1-second level, this script effectively bypasses the limitations of time-based charting, treating the market stream almost as a tick chart. In this granular domain, the noise is immense. Algorithms, high-frequency trading bots, and market makers generate a blizzard of data that can easily deceive a standard cumulative volume delta (CVD) indicator. This is where the Kalman Filter becomes indispensable. Originally developed for trajectory estimation in navigation systems, the Kalman Filter excels at separating the "signal"—the true vector of buying or selling pressure—from the "noise" of random market chatter. By estimating the velocity and position of order flow in real-time, the tracker provides a smoothed yet highly responsive visualization of market intent, allowing traders to discern between genuine momentum and the deceptive phenomena of absorption and distribution.
The shift to 1-second intrabar resolution transforms the nature of the data being analyzed. In a standard 1-minute or 5-minute timeframe, the internal battle is aggregated into a single bar, hiding the specific sequence of events. A candle might close green, looking bullish, but the 1-second data might reveal that 90% of the buying occurred in the first ten seconds, followed by fifty seconds of passive selling that absorbed all further upside attempts. The 1-second processing logic implemented in this script utilizes a "Close-to-Close" methodology, which acts as a pseudo-tick reader. If the price of the current second is higher than the previous second, the volume is classified as aggressive buying; if lower, aggressive selling. This granularity offers a near-perfect correlation with true bid/ask data, providing the trader with an X-ray view of the auction. This level of detail is crucial because institutional accumulation and distribution rarely happen in obvious, large-block trades that spike volume histograms. Instead, they occur in a steady stream of smaller, algorithmic executions designed to mask intent. The 1-second granularity catches these footprints that larger timeframes simply average out.
A critical innovation within this framework is the handling of "flat ticks"—moments where volume executes but price remains unchanged. In the world of microstructure, these moments are often the most significant. When aggressive buying volume pours into the market but price refuses to tick higher, it signifies the presence of a "limit wall" or a passive seller absorbing the demand. Standard indicators often discard this data or split it arbitrarily. This script, however, offers advanced logic to assign this volume based on the previous tick's direction, recognizing that in a high-velocity momentum move, a flat tick is often a continuation of the immediate aggressor's effort meeting temporary resistance. By accurately categorizing this "effort without result," the script identifies Absorption with pinpoint accuracy. It flags the precise moment when the laws of supply and demand seemingly break—when effort (volume) fails to produce a result (price change)—alerting the trader to a potential reversal or exhaustion point long before the price pattern confirms it.
The concept of "Market Efficiency Benchmarking" serves as the analytical engine driving the script’s diagnostic capabilities. The market is not a static environment; liquidity conditions change depending on the time of day, the asset class, and the prevailing volatility regime. A 500-contract buy order might shatter resistance during the Asian session but barely move the needle during the New York open. To account for this, the tracker calculates a dynamic "Price per CVD" metric, effectively learning the current exchange rate between volume and price displacement. It utilizes an exponential decay mechanism to maintain a rolling baseline of market efficiency. By constantly asking, "How much price movement should this amount of volume create?", the script establishes a standard of normalcy. When the market deviates from this standard—for example, when a massive surge in buying velocity results in minimal price gain—the script registers a Distribution event. Conversely, when selling pressure evaporates into a stable price, it registers Absorption. This dynamic benchmarking ensures that the tool remains robust and adaptive, requiring less manual tuning as market conditions shift.
The Kalman Filter’s role in this process is to calculate the "velocity" of the order flow. While cumulative volume delta (CVD) tells you the position of buyers versus sellers (who has bought more in total), the Kalman velocity tells you the rate of change of that aggression. This is analogous to the difference between a car’s odometer and its speedometer. In trading, the speed of the move matters. A slow, grinding move upward suggests a lack of aggressive selling, while a rapid vertical spike suggests an emotional imbalance. The script detects these velocity shifts instantly. When the velocity exceeds a specific threshold, the system enters a "Trend State." It is during these states that the benchmarking logic is most active, comparing the predicted price trajectory against reality. If the velocity is high but the price lags behind the Kalman prediction, the divergence is mathematically quantified. This removes the subjectivity from reading divergence; instead of "eyeballing" a chart, the trader receives a definitive, data-driven signal that the current trend is unhealthy.
The visual interface of the tracker, the dashboard, is designed to synthesize this complex data into actionable intelligence. Trading is a game of context, and a single signal in isolation is often meaningless. The dashboard provides a multi-day memory, aggregating events from "Today," "Yesterday," and "Day Before (D-2)." This temporal perspective is vital because institutional campaigns often span several days. A single day of distribution might be a pause in a trend, but three consecutive days of distribution events in a rising market constitute a screaming warning sign of a reversal. The dashboard tracks "Confirmed" events (where price moves in harmony with volume) and "Hidden" events (Absorption/Distribution). By calculating the "Net" counts for each day, the script offers a directional bias summary. If the "Hidden Net" is positive, it implies that passive buyers are accumulating positions, supporting the trend. If negative, it implies smart money is using liquidity to exit. This high-level view allows the trader to align their intraday execution with the broader structural narrative of the market.
One of the most powerful metrics presented on the dashboard is the "Ease of Movement" ratio. Derived from Wyckoff logic, this ratio compares the efficiency of buyers versus sellers. If the script calculates that it takes 1,000 contracts of buying to move the price 5 points, but 1,000 contracts of selling only moves it 2 points, the ratio reveals a fundamental asymmetry. The path of least resistance is up. This metric allows traders to filter their setups with a bias toward the "easier" side of the market. Even if a short setup presents itself technically, a high Ease of Movement ratio warns that the trade will be fighting against the market’s internal physics. This insight is invaluable for risk management, helping traders avoid "choppy" trades and focus on high-probability expansions where price and volume are working in concert.
The granularity of the 1-second data also necessitates a discussion on the "State Change" counter. In a healthy, trending market, the Kalman state should remain relatively stable, holding a bullish or bearish velocity for extended periods. However, in a volatile, indecisive market, the state may flip rapidly back and forth. The "State Changes" metric quantifies this turbulence. A high number of state changes relative to the time elapsed indicates a "choppy" or "balanced" auction where neither side has seized control. This is an environment that destroys trend-following strategies. By observing this counter, a trader can gauge the "texture" of the market volatility. Is the market flowing smoothly, or is it erratic? This allows for dynamic strategy adjustment—tightening stops in high-state-change environments or letting winners run when the state is stable.
The practical application of this tool requires a nuanced understanding of the four primary events it detects: Confirmed Bullish, Confirmed Bearish, Absorption, and Distribution. A "Confirmed" event is the market functioning efficiently. Aggressive buyers step in, velocity spikes, and price expands proportionally. These are the waves traders want to ride. They signify agreement between aggressive and passive participants. However, the edge lies in identifying the anomalies. An "Absorption" event (Cyan on the dashboard) often marks the bottom of a pullback. It visually represents the moment when sellers run out of ammunition or hit a limit buy wall. Seeing a cluster of Absorption events at a key support level provides the confidence to enter a long position with a tight stop, knowing that the structural support is real, not just a line on a chart. Conversely, "Distribution" (Orange) at highs is the hallmark of a "bull trap." Retail traders see the breakout and buy, but the tracker sees that the buying volume is not translating into price distance, indicating that a larger player is feeding the bulls their exit liquidity.
The "Current State" section of the dashboard brings this analysis into the immediate present. It functions as a real-time monitor for the active candle or swing. By projecting an "Expected Price" based on the accumulated CVD of the current move, it gives the trader a live performance review of the trend. If the actual price is trading below the expected price during an uptrend, the text will flash "Distribution Risk." This is a leading indicator in the truest sense. It warns the trader before the candle closes, before the moving average crosses, and before the price structure breaks. This latency advantage is the primary benefit of the Kalman filter’s predictive capability. It allows for proactive trade management—taking partial profits as distribution appears, rather than waiting for the market to reverse and stop out the trade.
It is important to acknowledge the technical sophistication required to run such a script. Processing 1-second arrays for an entire trading session pushes the Pine Script engine to its limits. The sheer volume of data points—tens of thousands per session—requires efficient coding and array management to prevent timeouts. This complexity is the barrier to entry that keeps such analysis out of the hands of the casual amateur. It is a tool for the serious market participant who understands that the quality of their output is dependent on the resolution of their input. The script’s ability to handle this data load and persist the calculations across sessions using var variables demonstrates a mastery of the platform’s capabilities, turning TradingView into a workstation that rivals professional institutional terminals.
The psychological impact of using the Kalman Absorption/Distribution Tracker cannot be overstated. Uncertainty is the root of emotional error in trading. When a trader buys a pullback, the fear of the price continuing to drop is palpable. However, if that trader has quantitative evidence that selling pressure is being absorbed—if they can see the "Hidden Net" turning positive and the Kalman velocity slowing down despite the red candles—that fear is replaced by conviction. The tool acts as an objective third party, decoupling the decision-making process from the emotional sway of price ticks. It anchors the trader in the reality of the order flow. It fosters a mindset of "buying strength in weakness" and "selling weakness in strength," which is the antithesis of the typical retail urge to chase price.
Furthermore, the adaptability of the script through its inputs allows it to be tuned to specific assets. The "Alpha" and "Beta" settings of the Kalman filter control its sensitivity. A higher Alpha makes the filter more responsive to recent price changes, suitable for scalping volatile assets like cryptocurrencies. A lower Alpha smooths the data further, ideal for capturing broader trends in thicker markets like the ES or Treasuries. The "Price Follow Threshold" allows the user to define what constitutes "efficiency" for a specific instrument. By tweaking these parameters, the trader effectively calibrates their radar to the specific frequency of the market they are trading, ensuring that the signals generated are relevant and actionable. This customizability ensures that the tool is not a black box but a transparent framework for market analysis.
The distinction between "Confirmed Net" and "Hidden Net" on the dashboard offers a dual-layer view of market sentiment. "Confirmed Net" tracks the visible trend—the moves that everyone sees. A high positive Confirmed Net means the trend is healthy and obvious. "Hidden Net," however, tracks the invisible war. A divergence between these two is a powerful signal. For instance, if the market is grinding higher (Positive Confirmed Net) but the Hidden Net is deeply negative (Distribution), it indicates a "hollow rally." The price is rising due to a lack of selling, not the presence of strong buying, and passive sellers are unloading into the move. This setup often precedes a violent correction. Identifying this "hollow" structure allows the trader to avoid buying the top or to position themselves for a mean reversion trade.
The 1-second granularity also shines during news events and the market open. These periods are characterized by extreme volatility and noise. Standard indicators often blow out or provide false signals during these times due to the sheer magnitude of the variance. The Kalman filter, however, is designed to handle noisy data streams. By dynamically adjusting its state estimates, it can track the dominant flow of capital even through the chaos of an FOMC release or the opening bell. The "Close-to-Close" logic ensures that every tick is accounted for, providing a cumulative picture of who won the opening battle. If the first minute of the session sees high volatility but the script registers massive "Absorption," it suggests that the initial volatility was a liquidity grab, setting the stage for a steady move in the opposite direction.
Ultimately, the Kalman Absorption/Distribution Tracker is more than just a technical indicator; it is a philosophy of market engagement. It rejects the notion that price is the only truth, arguing instead that price is the result of a negotiation between aggression and liquidity. By quantifying this negotiation with the precision of 1-second intervals and the mathematical rigor of Kalman filtering, it provides a window into the "why" behind the move. It transforms the chart from a historical record of what happened into a real-time display of what is happening now.
For the trader with the right mindset—one who values process over prediction and risk management over gambling—this tool offers a significant edge. It does not promise to predict the future, but it offers the most accurate possible description of the present. In the zero-sum game of trading, having a clearer, faster, and more detailed view of the battlefield is often the deciding factor between profitability and ruin. The script bridges the gap between the retail trader and the institutional algorithm, democratizing access to high-frequency order flow analysis and empowering the user to make decisions based on the structural reality of the market rather than the deceptive surface of price action. It is a testament to the power of modern scripting languages and a valuable addition to the arsenal of any serious technical analyst.
# Trading View's premium subscription is required to run this script.
SKYLERBOTyeah so basically the bot uses price action divergences with cvd delta volume to find areas of selling or buying dont use it as a main use it as double confirmation with regular cvd divergence analysis
SOL Short EMA165 Failed ReclaimThis script identifies short opportunities on SOL when price attempts to reclaim the EMA 165 but fails.
A signal is generated when price trades above the EMA 165 and then closes back below it on the selected timeframe.
The script plots the EMA 165 and triggers an alert() for use with external execution (e.g. Bitget signal bots).
Designed for reliability and clean alert execution.
Pressure Reversal Engine - Scalp [BullByte]PRESSURE REVERSAL ENGINE - SCALP
OVERVIEW
Pressure Reversal Engine - Scalp is a professional reversal indicator built for scalping and active trading on any market including Forex, CFDs, crypto, and stocks. This multi-engine buy sell signal system works without volume data, making it ideal for instruments where volume is unavailable or unreliable.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
THE PROBLEM THIS INDICATOR SOLVES
Traditional reversal indicators and buy sell signal systems often struggle with:
- Dependence on volume data (unavailable for Forex pairs, CFD instruments, and many markets)
- Single-indicator approaches that generate excessive false signals and noise
- Static parameters that fail to adapt to changing volatility conditions
- Lack of confluence validation across multiple analytical dimensions
PRE Scalp addresses these limitations through a six-engine confluence architecture. Signals generate only when multiple independent analytical engines align, filtering noise while identifying potential reversal conditions across any timeframe.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DEVELOPMENT APPROACH - MULTI-ENGINE ARCHITECTURE - NOT A MASHUP
The Pressure Reversal Engine was developed to address specific limitations observed in traditional reversal detection and scalping indicator methods:
Challenge 1: Volume Dependency
Most reversal indicators require volume data, which is unreliable or unavailable for Forex, CFDs, indices, and many international instruments. The SAI engine was specifically designed to derive activity measurements purely from price action and candle structure.
Challenge 2: Single-Dimension Analysis
Individual indicators measuring only one aspect of price action generate excessive false signals. The multi-engine confluence approach requires confirmation across six independent analytical dimensions before generating buy or sell signals.
Challenge 3: Static Parameters
Fixed lookback periods fail during changing volatility conditions. The AVR engine dynamically adapts all parameters based on current market state, improving signal quality across different market environments.
Challenge 4: Subjective Pattern Recognition
Visual pattern identification is subjective and inconsistent. The DNA engine provides objective mathematical pattern matching with quantifiable scores for reversal candle detection.
Each engine addresses a specific analytical dimension. The confluence requirement emerged from observation that aligned signals across multiple engines produced significantly higher quality reversal identification than any single method.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
THE SIX ANALYTICAL ENGINES EXPLAINED
Each engine provides a unique analytical perspective. Buy and sell signals generate only when multiple engines confirm confluence:
ENGINE 1: SYNTHETIC ACTIVITY INDEX (SAI) - Volumeless Activity Detection
Purpose: Derives market activity from price structure without requiring volume data. Essential for Forex trading, CFD analysis, and any instrument lacking reliable volume.
Calculation: Weighted composite of range expansion, body momentum, directional pressure, wick rejection, price acceleration, and volatility burst measurements.
Formula: SAI = (RangeExpansion x 0.25) + (BodyMomentum x 0.20) + (DirectionalPressure x 0.15) + (WickRejection x 0.15) + (PriceAcceleration x 0.15) + (VolatilityBurst x 0.10)
Signal Contribution: Validates that meaningful market activity is occurring at the potential reversal point. Without activity confirmation, apparent reversals may lack follow-through.
ENGINE 2: PRESSURE WAVE OSCILLATOR (PWO) - Exhaustion Detection
Purpose: Measures the balance between buying pressure and selling pressure through price geometry analysis.
Calculation: Net pressure (buying minus selling) weighted by activity level, normalized by standard deviation over extended period.
Formula: PWO = SMA(NetPressure x SAI, length) / StdDev(cumulative, length x 2)
Signal Contribution: Identifies pressure exhaustion conditions using percentile ranking to detect when buyers or sellers are running out of momentum. Exhaustion often precedes trend reversal.
ENGINE 3: FRACTAL CONFLUENCE MATRIX (FCM) - Multi-Timeframe Structure Analysis
Purpose: Analyzes price position across multiple structural timeframes simultaneously for multi-timeframe confluence.
Calculation: Evaluates price position within range at five Fibonacci-based periods (5, 8, 13, 21, 34 bars). These periods capture nested market structures from micro to macro.
Formula: FractalPosition = (Close - LowestLow) / (HighestHigh - LowestLow) at each period
Signal Contribution: Confirms that multiple structural levels align at extremes, indicating potential reversal zones where larger and smaller timeframes agree on price position.
ENGINE 4: ENTROPIC EXHAUSTION DETECTOR (EED) - Information Theory Analysis
Purpose: Applies Shannon entropy from information theory to measure market disorder and directional exhaustion.
Calculation: Shannon entropy of bullish/bearish bar distribution over the lookback period.
Formula: H = -Sum(p(x) x log2(p(x))) where p(x) is probability of bullish or bearish bars
Range: 0 (complete order, all bars same direction) to 1 (maximum disorder, 50/50 distribution)
Signal Contribution: High entropy combined with a directional streak breaking suggests the market has reached maximum uncertainty and may resolve in a new direction.
ENGINE 5: CANDLE DNA FINGERPRINTING - Pattern Recognition System
Purpose: Mathematical pattern recognition comparing current candle structure against ideal reversal patterns including hammer, shooting star, and engulfing formations.
Calculation: Weighted similarity scoring across body ratio, upper wick ratio, lower wick ratio, close position, and range versus ATR.
Formula: Score = Sum((1 - |actual - ideal|) x weight) for each metric
Signal Contribution: Identifies candles with reversal characteristics through objective mathematical measurement rather than subjective visual pattern recognition.
ENGINE 6: ADAPTIVE VOLATILITY REGIME (AVR) - Dynamic Parameter Adjustment
Purpose: Dynamically adjusts all lookback parameters based on current volatility conditions for adaptive indicator behavior.
Calculation: Ratio of fast ATR to slow ATR determines volatility regime classification.
Formula: VolatilityRatio = ATR(fast period) / ATR(slow period)
States: High volatility (ratio > 1.3) uses shorter lookbacks for faster adaptation. Low volatility (ratio < 0.7) uses longer lookbacks for noise reduction. Normal volatility maintains base parameters.
Signal Contribution: Ensures the entire system adapts appropriately to current market conditions rather than using static parameters that may fail in different environments.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
WHY ENGINE SYNERGY MATTERS FOR SIGNAL QUALITY
The effectiveness of PRE comes from requiring multiple engines to align before generating buy or sell signals:
- SAI confirms activity is present (something meaningful is happening in price action)
- PWO confirms pressure exhaustion (the current move is running out of steam)
- FCM confirms structural alignment (multiple timeframes agree on position)
- EED confirms disorder state (market uncertainty is elevated near potential turning point)
- DNA confirms candle structure (the bar exhibits reversal pattern characteristics)
- AVR ensures parameters are appropriate (system is calibrated to current volatility)
A single indicator measuring one dimension generates many false signals. By requiring confluence across six independent analytical dimensions, this reversal indicator filters noise while identifying potential trading opportunities.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SIGNAL GENERATION PROCESS FOR BUY AND SELL SIGNALS
Step 1: ANCHOR DETECTION
The system identifies potential reversal anchors when price breaks beyond recent structure using a mean-reversion approach. A bullish anchor forms when price breaks below prior lows, suggesting potential oversold conditions. A bearish anchor forms when price breaks above prior highs, suggesting potential overbought conditions.
Step 2: ENGINE SCORING
Each enabled engine contributes to a cumulative quality score. The anchor must achieve minimum scoring thresholds to activate a setup.
Step 3: CONFIRMATION TRIGGER
Price must confirm the setup by crossing back through the anchor zone within the confirmation window. This crossover or crossunder is validated at bar close to prevent repainting.
Step 4: SIGNAL QUALITY SCORE
The final buy or sell signal displays a quality score representing the total engine confluence. Higher scores indicate stronger alignment across more analytical engines.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
READING THE BUY SELL SIGNAL LABELS
BUY Signal Label:
- Displays "BUY" with quality score in brackets
- Shows engine contribution breakdown when enabled in settings
- indicates engine contributed to signal
- indicates engine did not contribute
- Higher total scores suggest stronger multi-engine confluence
SELL Signal Label:
- Displays "SELL" with quality score in brackets
- Same engine breakdown format as BUY signals
- Identical scoring interpretation
Score Interpretation Guide:
- Score 3-4: Minimum threshold met, basic confluence achieved
- Score 5-6: Good confluence across multiple engines
- S core 7-8: Strong confluence with most engines aligned
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ENGINE STATUS DASHBOARD - REAL-TIME ANALYSIS DISPLAY
The Engine Status Panel displays real-time readings from all six analytical engines:
Synthetic Activity Row:
- HIGH ACTIVITY: SAI above threshold, significant price action detected (value shown)
- ACTIVE: SAI above confirmation level, moderate activity present
- LOW: SAI below activity thresholds, quiet market conditions
- DISABLED: Engine turned off in settings
Pressure Wave Row:
- BULL EXHAUSTION: PWO in lower percentile tail and reversing upward, potential bottom
- BEAR EXHAUSTION: PWO in upper percentile tail and reversing downward, potential top
- NEUTRAL: PWO in normal range, no exhaustion detected
Fractal Matrix Row:
- BULL CONFLUENCE: Multiple fractal levels show price near structural lows (score shown)
- BEAR CONFLUENCE: Multiple fractal levels show price near structural highs
- NO CONFLUENCE: Insufficient alignment across fractal timeframe levels
Entropic Exhaustion Row:
- HIGH ENTROPY: Shannon entropy above threshold, maximum market disorder detected
- ORDERED: Entropy below threshold, clear directional consistency present
Candle DNA Row:
- BULL PATTERN: Current candle matches bullish reversal profile (hammer-like structure)
- BEAR PATTERN: Current candle matches bearish reversal profile (shooting star-like)
- NO MATCH: Current candle does not match reversal pattern characteristics
Market Regime Row:
Shows DETECTED market conditions based on price action analysis:
- FRESH MOVE: New directional move beginning, momentum increasing
- NORMAL: Standard market conditions, no extreme factors detected
- SCALP CONDITIONS: Extended move or decreasing momentum detected
- CAUTION ZONE: Multiple warning factors present requiring conservative approach
Note : This displays what market conditions look like, not necessarily what targets will be applied.
Applied Style Row:
Shows what target style is ACTUALLY being applied to trades and why:
When Trade Style Setting = Auto:
- RUNNER (Auto): System detected FRESH conditions, applying wide targets (0.8R, 1.8R, 3.0R)
- EXTENDED (Auto): System detected NORMAL conditions, applying balanced targets (0.6R, 1.2R, 2.0R)
- SCALP (Auto): System detected SCALP conditions, applying tight targets (0.4R, 0.8R, 1.2R)
- CAUTION (Auto): System detected CAUTION conditions, applying very tight targets (0.3R, 0.5R, 0.8R)
When Trade Style Setting = User Override:
- SCALP (User): You selected Scalp style manually
- EXTENDED (User): You selected Extended style manually
- RUNNER (User): You selected Runner style manually
This dual-row display ensures complete transparency. You always see both what market conditions exist AND what targets you are receiving.
Volatility State Row:
- HIGH VOLATILITY: Fast ATR significantly exceeds slow ATR, adaptive parameters shortened
- NORMAL: Volatility ratio within standard range
- LOW VOLATILITY: Fast ATR significantly below slow ATR, adaptive parameters extended
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
REGIME VS APPLIED STYLE - COMPLETE TRANSPARENCY
The Engine Status Panel displays TWO separate rows for complete trading transparency:
1. Market Regime: What current market conditions look like based on analysis
2. Applied Style: What target calculations are actually being used for trades
Why Two Separate Rows?
When Trade Style is set to "Auto", the Applied Style will match the detected Regime automatically. For example:
- Regime: FRESH MOVE leads to Applied Style: RUNNER (Auto)
- Regime : NORMAL leads to Applied Style: EXTENDED (Auto)
When you manually select a Trade Style (Scalp, Extended, or Runner), the Applied Style will show your selection regardless of the detected Regime:
- Regime: FRESH MOVE but Applied Style: SCALP (User)
(Market conditions look fresh, but you chose tight targets)
This transparency ensures you always know:
- What conditions is the market is currently showing
- What targets you will you actually receive on signals
- Whether the system chose automatically or you overrode the selection
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
TRADE PANEL - POSITION MANAGEMENT DISPLAY
During Active Trade:
- Position type (LONG/SHORT) with entry price level
- Running P&L displayed in points (current price versus entry)
- TP1, TP2, TP3 target levels with booking percentages for each
- Current stop loss level (initial, protected, or trailing depending on trade progress)
- Risk to Reward ratio (displayed before TP1 is reached)
- Profit booked percentage showing locked gains
- Trade status and total bars in trade count
When Scanning for Signals:
- Shows "SCANNING FOR SIGNALS" status message
- Displays any active setup waiting for a confirmation trigger
- Shows next signal TP multipliers based on the current detected regime
- Indicates remaining bars in confirmation window before setup expires
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
TRADE MANAGEMENT AND RISK CONTROL FEATURES
Take Profit System:
- Supports 2 or 3 TP target levels for flexible exit strategy
- Three calculation modes available: Auto (regime-based), Manual ATR, Fixed R:R
- Configurable booking percentages at each level for position scaling
- Visual lines and labels display all target levels on chart
Stop Loss System:
- Two calculation modes : Auto (anchor-based) or Manual ATR distance
- Configurable buffer beyond calculated stop level for additional protection
- Optional maximum stop loss cap in points to limit risk exposure
- Visual display shows current stop level throughout trade
Breakeven Protection:
- None: Stop remains at original level after TP1 is reached
- Buffer: Stop moves to entry plus percentage of original risk
- Lock at TP1: Stop moves to TP1 level, securing that profit amount
Trailing Stop Options:
- ATR Trailing: Follows at dynamic ATR distance from price extreme
- Step Trailing: Moves in fixed point increments as price advances favorably
- Swing Trailing: Follows recent swing structure levels for dynamic protection
- Configurable start point: Begin trailing from entry or only after TP1 achieved
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
KEY SETTINGS GUIDE FOR CONFIGURATION
Core Engine Settings:
- Base Lookback Period: Foundation for anchor detection, automatically adjusted by AVR engine
- Confirmation Window: Number of bars allowed for price to confirm setup after anchor
- Minimum Signal Quality Score : Required confluence level for valid buy sell signals
- Signal Cooldown: Minimum bars between consecutive signals to prevent clustering
Engine Toggles:
Each of the six analytical engines can be independently enabled or disabled. Disabling engines reduces confluence requirements but may affect overall signal quality.
Trade Style Options:
- Auto: Automatically selects style based on detected market regime
(FRESH leads to Runner, NORMAL leads to Extended, SCALP leads to Scalp, CAUTION leads to Caution)
- Scalp: Forces tight targets for quick profit taking (TP1: 0.4R, TP2: 0.8R, TP3: 1.2R)
- Extended: Forces balanced targets with room to develop (TP1: 0.6R, TP2: 1.2R, TP3: 2.0R)
- Runner: Forces wide targets to capture larger moves (TP1: 0.8R, TP2: 1.8R, TP3: 3.0R)
Aggressiveness Level:
- Conservative: Tighter targets with earlier profit taking
- Normal: Balanced approach as calculated
- Aggressive: Extended targets for larger potential moves
Session Filter:
Optional restriction of signals to specific trading sessions including London, New York, Tokyo, Sydney, London plus New York overlap, or custom hours in UTC.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
VISUAL ELEMENTS AND DISPLAY OPTIONS
Chart Display Elements:
- BUY and SELL labels with quality scores and optional engine breakdown
- Entry line displayed as dashed yellow
- TP levels displayed as dotted green gradient
- Stop loss line displayed as solid red
- Protected and trailing stop line displayed as solid blue
- Hit markers appear when TP or SL levels are reached
- Optional regime label showing current market state classification
Color Theme Options:
- Vibrant: High contrast modern colors (default selection)
- Classic : Traditional trading platform colors
- Dark Pro: Subdued professional color scheme
- Minimal : Low saturation subtle colors for clean charts
Dashboard Display Modes:
- Full : Complete detailed information display
- Compact : Essential information only for smaller footprint
- Ultra Compact : Minimal footprint display for maximum chart space
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ALERT SYSTEM FOR NOTIFICATIONS
Individual Alert Conditions Available:
- PRE Buy Signal: Triggers on new buy signal generation
- PRE Sell Signal: Triggers on new sell signal generation
- TP1 Achieved: Triggers when first target is reached
- TP2 Achieved: Triggers when second target is reached
- TP3 Achieved: Triggers when third target is reached
- Stop Loss Hit: Triggers when stop level is reached before any TP
- Protected Exit: Triggers when stop is hit after partial profit taken
- Momentum Warning: Triggers when momentum weakening is detected in profitable trade
Alert Format Options:
- Standard: Brief notification with symbol and signal score
- Detailed : Comprehensive information including all price levels
- Webhook JSON: Machine-readable format for automated trading systems and bots
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CHART EXAMPLES - VISUAL DEMONSTRATIONS
Chart 1: Dashboard and Engine Status Overview
This chart demonstrates the PRE indicator in scanning mode, showing the comprehensive Engine Status Panel (top right) and Trade Panel (bottom right). The dashboard provides real-time visibility into all six analytical engines and current market conditions.
Key Features Shown:
- Synthetic Activity Index (SAI): Currently showing HIGH ACTIVITY (50.6) detecting significant price action
- Pressure Wave Oscillator (PWO): NEUTRAL (2.99) with no exhaustion detected yet
- F ractal Confluence Matrix (FCM): BEAR CONFLUENCE (5) showing price at multi-timeframe highs
- Entropic Exhaustion Detector (EED): HIGH ENTROPY (0.99) indicating maximum market uncertainty
- Candle DNA Fingerprinting: BULL PATTERN (0.74) with reversal pattern detected
- Market Regime: SCALP CONDITIONS suggesting tighter targets appropriate
- Applied Style: SCALP (Auto) with system automatically selecting scalp mode based on regime
- Volatility State: NORMAL (0.76)
- Trade Panel: Shows SCANNING FOR SIGNALS with a BEARISH setup active (3 bars remaining)
What This Demonstrates:
The dashboard provides complete transparency into the indicator decision-making process. You can see exactly which engines are active, their current readings, and what trade style will be applied to the next signal. The Applied Style row shows both the detected regime AND the style that will be used.
Chart 2: Trade Style Comparison - Extended vs Runner
This split-screen comparison shows the SAME SELL signal and trade with two different trade style settings applied. The left panel uses EXTENDED (User) style while the right panel uses RUNNER (User) style. This demonstrates how manually selecting different trade styles affects take profit targets and position booking strategy for identical market conditions.
Key Features Shown:
LEFT PANEL - EXTENDED (User) Style:
- Engine Status: Market Regime shows FRESH MOVE but Applied Style shows EXTENDED (User)
- Entry: 4492.5
- TP1: 4487.75 at 4.6 pts away
- TP2: 4483.01 at 9.4 pts away
- Stop Loss: 4500.4 (8 pts)
- Risk to Reward: 1:0.6
- Running P&L: -0.13 points
- Position Booking: Balanced 50/50 split
RIGHT PANEL - RUNNER (User) Style:
- Engine Status: Same FRESH MOVE regime but Applied Style shows RUNNER (User)
- Entry: 4492.5 (same entry)
- TP1: 4486.17 at 6.2 pts away (WIDER target)
- TP2: 4478.26 at 14.1 pts away (MUCH WIDER target)
- Stop Loss: 4500.4 (8 pts - same stop)
- Risk to Reward: 1:0.8 (better ratio)
- Running P&L: -0.13 points (same moment)
- Position Booking: Aggressive 35/65 split keeping more for runner
What This Demonstrates:
Both panels show the exact same trade at the same moment with same P&L, entry, and stop. The ONLY difference is the trade style setting. EXTENDED uses balanced approach with 50/50 booking at closer targets. RUNNER uses wider targets with 35/65 booking to let winners run further.
Chart 3: Auto Mode vs Manual Override Comparison
This split-screen comparison shows the SAME SELL signal with two different style control modes. The left panel uses RUNNER (Auto) where the system automatically selected Runner style based on detecting FRESH MOVE conditions. The right panel uses SCALP (User) where the trader manually forced Scalp style, overriding the system recommendation.
Key Features Shown:
LEFT PANEL - RUNNER (Auto) Style:
- Engine Status: Market Regime shows FRESH MOVE and Applied Style shows RUNNER (Auto)
- Entry: 4492.5
- TP1: 4489.33 at 3 pts away
- TP2: 4487.17 at 6.2 pts away
- Stop Loss : 4500.4 (8 pts)
- Control Mode: System automatically selected this style
RIGHT PANEL - SCALP (User) Style:
- Engine Status: Same FRESH MOVE regime but Applied Style shows SCALP (User)
- Entry: 4492.5 (same)
- TP1: 4489.33 at 3 pts away (TIGHTER booking percentage)
- TP2: 4487.17 at 6.2 pts away (SMALLER remainder)
- Risk to Reward: 1:0.4 (more conservative)
- Control Mode: User manually forced this style overriding system
What This Demonstrates:
The Applied Style row shows WHO is in control. (Auto) means system decides based on regime. (User) means you override. This complete transparency shows when you are trading WITH or AGAINST the system analysis.
Chart 4: Trade Management and Protection System
This split-screen comparison shows the SAME SHORT trade at DIFFERENT stages of execution. The left panel shows the trade at entry and setup phase while the right panel shows the trade after TP1 has been hit with protection activated.
Key Features Shown:
LEFT PANEL - Trade Setup and Initial Entry:
- Engine Status: Market Regime shows FRESH MOVE and Applied Style shows RUNNER (Auto)
- Trade Panel: Shows SCANNING FOR SIGNALS with BULLISH setup active (3 bars remaining)
- TP Mode: Auto with Next Signal TP showing 0.8R / 1.8R (Runner style targets)
- Exit Marker: Shows Exit @ +50% label indicating completed previous trade
- Setup Phase: System ready for next signal with runner-focused targets pre-calculated
RIGHT PANEL - Active Trade with TP1 Hit:
- Engine Status: Same FRESH MOVE regime but Applied Style shows SCALP (User)
- Entry: 4492.5 (yellow dashed line)
- TP1: 4486.17 showing + HIT (green marker indicating TP1 reached)
- TP2: 4486.17 at 11.4 pts away (green dotted line)
- Protected Stop: 4491.31 (3.8 pts) shown as BLUE LINE (stop moved from initial level)
- Running P&L: +4.96 points (in profit)
- Profit Booked: 65% shown in trade panel
- Trade Status: RUNNING TO TP2
- Bars in Trade: 10
- Protection Active: Stop loss moved to protect profits after TP1 achievement
What This Demonstrates:
Complete trade lifecycle and protection system. Initial stop placement, TP1 achievement, breakeven protection activation, position booking, and remaining position management with zero risk after partial profit taken.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
RECOMMENDED USE CASES AND APPLICATIONS
Suitable Instruments:
- Forex pairs including all majors, minors, and exotics (no volume required)
- CFD instruments including indices, commodities, and metals
- Cryptocurrency pairs on all exchanges
- Stocks and ETFs with or without volume consideration
- Futures contracts across all markets
Suggested Timeframes:
- Primary for scalping: 1-minute, 3-minute, 5-minute, 15-minute charts
- Also effective on: 30-minute, 1-hour, 4-hour for swing entry identification
Optimal Conditions:
- Markets with clear structure and adequate liquidity
- During active trading sessions with participation
- When multiple engines show alignment and confluence
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
LIMITATIONS AND IMPORTANT CONSIDERATIONS
What This Indicator Cannot Do:
- Predict future price movements with certainty
- Guarantee profitable trades or specific returns
- Replace proper risk management and position sizing
- Work effectively in all market conditions at all times
- Eliminate all false signals completely
Conditions Where Performance May Vary:
- Extremely low liquidity periods with wide spreads
- Major news events and high-impact economic releases
- Strongly trending markets without meaningful pullbacks
- Unusual market conditions or flash crash events
The P&L tracking displayed is for the current visualized trade only and does not represent historical performance, backtested results, or guaranteed future outcomes.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SIGNAL CONFIRMATION AND NON-REPAINTING BEHAVIOR
This indicator is specifically designed to prevent repainting:
- All signals are confirmed at bar close only using barstate.isconfirmed
- Signals do not appear and disappear during intra-bar price action
- Once a signal prints on the chart, it remains permanently
- Historical signals accurately represent what would have been visible in real-time trading
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
RISK DISCLAIMER AND IMPORTANT NOTICES
This indicator is provided for educational and informational purposes only. It does not constitute financial advice, investment recommendations, or trading signals that guarantee profits.
Trading financial instruments carries substantial risk of loss and is not suitable for all investors. Past performance of any trading system or methodology is not necessarily indicative of future results.
Users should:
- Conduct their own analysis before making any trading decisions
- Never risk more than they can afford to lose
- Understand that no indicator can predict market movements with certainty
- Use proper risk management and position sizing at all times
- Consider consulting a licensed financial advisor before trading
The author accepts no liability for any losses incurred through the use of this indicator.
-BullByte






















