OPEN-SOURCE SCRIPT
Actualizado

Smart Adaptive Double Patterns [The_lurker]

14 526
Smart Adaptive Double Patterns

This is an advanced technical indicator that combines two of the strongest and most renowned classical price reversal patterns:

✅ Double Bottom Pattern — a bullish reversal pattern that forms after a downtrend
✅ Double Top Pattern — a bearish reversal pattern that forms after an uptrend

The indicator does not merely detect patterns — it provides a fully integrated, intelligent system that includes:

✅ Precise quality scoring for each pattern using 5 technical criteria
✅ Automatic price target calculation at three levels (Conservative, Balanced, Aggressive)
✅ Multi-layer dynamic filtering to avoid false signals
✅ Live pattern tracking from formation to target achievement or failure
✅ Comprehensive alert system covering all possible trading scenarios

🎯 Why Is This Indicator Unique?

1️⃣ High Detection Accuracy
Unlike traditional indicators that rely on simple rules, this one applies 5 strict structural conditions to confirm pattern validity:

A clear trend must precede the pattern
High symmetry between the two bottoms or two tops
No break of critical price levels during formation
Logical spacing between key points
Technical confirmation from ADX, ATR, and Volume

2️⃣ Advanced Quality Scoring System
Each pattern is scored out of 100 based on 5 weighted criteria:

Symmetry (30%): How closely the two bottoms or tops match
Trend Strength (20%): Strength of the prior trend
Volume Behavior (20%): Trading activity at critical points
Pattern Depth (15%): Vertical distance between neckline and bottom/top
Structural Integrity (15%): Full compliance with structural rules
3️⃣ Smart Target Management

Separate targets for bullish (Double Bottom) and bearish (Double Top) patterns
Separate projections for success and failure cases
Multiple options: Conservative (0.618) / Balanced (1.0) / Aggressive (1.618)
Live tracking with dynamic moving lines

4️⃣ Professional Failure Handling
Failed patterns are not ignored — they are turned into counter-trend opportunities:

Failed Double Bottom → triggers a bearish signal with downside targets
Failed Double Top → triggers a bullish signal with upside targets
Automatic color change for clear visual distinction

5️⃣ Full Customization Flexibility

Enable/disable each pattern independently
22+ adjustable settings
Unique colors for each pattern and quality level
Full bilingual support (Arabic / English)

📐 Pattern Details

🟦 Double Bottom Pattern

imagen

Sequence of points:

🔹 Point 1: Peak marking the start of a strong downtrend
🔹 Point 2 (Bottom 1): First low — first key bounce
🔹 Point 3: Intermediate high — forms the neckline (resistance)
🔹 Point 4 (Bottom 2): Second low — should closely match Bottom 1
🔹 Point 5: Breakout point — pattern confirmation

Mandatory Conditions:

✅ Clear downtrend before Point 2
✅ Bottoms 2 & 4 nearly identical (≤1.5% difference by default)
✅ Point 3 higher than both bottoms
✅ Neither bottom is broken during formation
✅ Sufficient time between points (≥10 candles by default)

✅ Success Scenario
→ Price breaks above the neckline (Point 3)
→ Point 5 is plotted at breakout candle
→ Dashed vertical line drawn from Point 5 to target
→ Horizontal dashed line tracks price toward target
→ Dashboard shows: Pattern Type | Quality | Rating | Target | Status
→ When target hits: line turns green + ✅ appears

🎯 Target Calculation
Pattern Height = Point 3 − Point 4
• Conservative: Point 3 + (Height × 0.618 × Quality Factor)
• Balanced: Point 3 + (Height × 1.0 × Quality Factor)
• Aggressive: Point 3 + (Height × 1.618 × Quality Factor)

❌ Failure Scenario

imagen

→ Price breaks below both Bottom 1 or Bottom 2 before neckline breakout

Visual Changes:

All lines turn red
Red ✖ appears at breakdown candle
Neckline stops expanding
Red dashed vertical line from breakdown point to bearish target
Red horizontal tracking line follows price
Dashboard updates to:
⚠ Failed Bottom – Bearish
→ Shows new bearish target
→ Indicates target mode for failure case
→ Status: Bearish Reversal
→ Fully red display

🟥 Double Top Pattern

Sequence of points:

🔹 Point 1: Trough marking the start of a strong uptrend
🔹 Point 2 (Top 1): First peak — first key resistance
🔹 Point 3: Intermediate low — forms the neckline (support)
🔹 Point 4 (Top 2): Second peak — should closely match Top 1
🔹 Point 5: Breakdown point — pattern confirmation

Mandatory Conditions:
imagen

✅ Clear uptrend before Point 2
✅ Tops 2 & 4 nearly identical (≤1.5% difference by default)
✅ Point 3 lower than both tops
✅ Neither top is breached during formation
✅ Sufficient time between points (≥10 candles by default)

✅ Success Scenario
→ Price breaks below the neckline (Point 3)
→ Point 5 is plotted at breakdown candle
→ Dashed vertical line drawn to target
→ Horizontal tracking line moves with price
→ Dashboard updates accordingly
→ Green line + ✅ on hit

🎯 Target Calculation
Pattern Height = Point 4 − Point 3
• Conservative: Point 3 − (Height × 0.618 × Quality Factor)
• Balanced: Point 3 − (Height × 1.0 × Quality Factor)
• Aggressive: Point 3 − (Height × 1.618 × Quality Factor)

❌ Failure Scenario
imagen

→ Price breaks above either Top 1 or Top 2 before neckline breakdown

Visual Changes:

All lines turn cyan (light blue)
Cyan ✖ appears at breakout candle
Neckline stops expanding
Cyan dashed vertical line to bullish target
Cyan horizontal tracking line follows price
Dashboard updates to:
⚠ Failed Top – Bullish
→ Shows new bullish target
→ Indicates target mode for failure case
→ Status: Bullish Reversal
→ Fully cyan display

🎯 Upside Target (after Double Top failure)
Max Top = max(Point 2, Point 4)
Height = Max Top − Point 3
• Conservative: Max Top + (Height × 0.618)
• Balanced: Max Top + (Height × 1.0)
• Aggressive: Max Top + (Height × 1.618)

📊 Quality Scoring System (0–100)

1️⃣ Symmetry (30%)
Measures price match between the two bottoms or two tops.

High score (25–30): Near-perfect symmetry → very strong pattern
Medium (15–24): Good match → reliable signal
Low (5–14): Weak symmetry → use caution
Zero: No symmetry → invalid pattern
2️⃣ Trend Strength (20%)
Uses ADX and DI indicators.

20 pts: Strong trend confirmed (e.g., ADX ≥ 20 + correct DI alignment)
10 pts: Trend filter disabled
6 pts: Weak or sideways trend
3️⃣ Volume Behavior (20%)
Declining volume on second touch is a positive sign (shows exhaustion).

15–20 pts: Clear volume drop → strong signal
10 pts: Neutral volume
6 pts: Rising volume → higher risk of continuation
4️⃣ Pattern Depth (15%)
Deeper patterns = stronger reversals.

12–15 pts: Deep → high reversal power
8–11 pts: Medium → acceptable
<8 pts: Shallow → weak signal
5️⃣ Structural Integrity (15%)
Checks logical structure (e.g., Point 1 > Point 3 in Double Bottom).

12–15 pts: Ideal structure
8–11 pts: Minor flaws
<8 pts: Poor setup
📈 Final Quality Rating & Colors

• 85–100 → ⭐ Excellent
 → Double Bottom: Cyan #00BCD4
 → Double Top: Light Red #FF5252

• 75–84 → ✨ Very Good
• 65–74 → ✓ Good
• 60–64 → ○ Acceptable
 → All use Amber #FFC107

• <60 → ❌ Rejected (not shown)
 → Gray #9E9E9E

🔧 Dynamic Filters

1️⃣ ATR Filter (Volatility Check)
Rejects patterns in abnormally high volatility periods.
→ If current ATR > 1.8 × 50-period ATR MA → pattern rejected
✅ Recommended for crypto, small caps
❌ Optional for calm markets (gold, bonds)

2️⃣ ADX Filter (Trend Confirmation)
Ensures a real trend exists before the pattern.
→ If ADX < 14 (70% of default 20) → pattern rejected
✅ Strongly recommended (keep ON)

3️⃣ Volume Filter (Behavior Validation)
Not used to reject patterns, but strongly affects quality score.
✅ Best for liquid markets (Forex majors, large stocks)
❌ Optional for illiquid assets

⚙️ Key Settings Explained

🔘 General Settings
• Language: Arabic / English
• Show Previous Patterns: Yes / No
 → “No” keeps chart clean; “Yes” for historical review

🔘 Pattern Selection
• Enable Double Bottom: ✅ / ❌
• Enable Double Top: ✅ / ❌
→ Use combinations:
 ✅✅ → Full reversal scanning
 ✅❌ → Long setups only
 ❌✅ → Short setups only
 ❌❌ → Indicator OFF

🔘 Detection Parameters
• Pivots Left (1–20): Higher = more reliable, fewer patterns
• Pivots Right (1–20): Lower = faster signals
• Min Width (5–100): Min candles between Bottom/Top 1 & 2
• Tolerance % (0.1%–5%): Max allowed price difference
• Min Arm (5–50): Min candles between pivot & neckline
• Min Trend (5–50): Min candles in prior trend
• Trend Lookback (50–500): How far back to detect trend start
• Extension Multiplier (1.0–5.0): How long to wait for breakout

🔘 Quality Settings
• Min Quality Score (0–100):
 → Conservative: 75–85
 → Balanced: 60–70
 → Flexible: 50–55
• Custom Weights: Adjust based on market (e.g., increase Volume weight in Forex)

🔘 Target Settings
• Bottom Bullish Target: Conservative / Balanced / Aggressive
• Bottom Bearish Target: (used on failure)
• Top Bearish Target: Conservative / Balanced / Aggressive
• Top Bullish Target: (used on failure)

🔘 Visual Settings
• Label Size: Small / Normal / Large / Huge
• Pattern Colors: Fully customizable
• Table: Show/Hide + Size (Small/Normal/Large) + Position (Top-Right / Top-Left / Bottom-Right / Bottom-Left)
• Fill Transparency: 70%–95% (default: 85%)

🔔 Alert System (8 Independent Alerts)

📌 Double Bottom Alerts

Bullish Breakout → “Double Bottom Breakout – Bullish!”
Bullish Target Hit → “Bullish Target Achieved!”
Failure (Bearish) → “Double Bottom Failed – Bearish!”
Bearish Target Hit → “Bearish Target Achieved (Failure)!”
📌 Double Top Alerts

Bearish Breakdown → “Double Top Breakdown – Bearish!”
Bearish Target Hit → “Bearish Target Achieved!”
Failure (Bullish) → “Double Top Failed – Bullish!”
Bullish Target Hit → “Bullish Target Achieved (Failure)!”
Each alert can be enabled/disabled independently and supports pop-ups, emails, or webhooks.


⚠️ Disclaimer:
This indicator is for educational and analytical purposes only. It does not constitute financial, investment, or trading advice. Use it in conjunction with your own strategy and risk management. Neither TradingView nor the developer is liable for any financial decisions or losses.
Notas de prensa
Change the goal calculation method

Change the goal display method

تغير طريقة حساب الهدف

تغير طريقة عرض الهدف
Notas de prensa
Smart Adaptive Double Patterns
مقارنة النسخ | Version Comparison

ملخص التحسينات | Optimization Summary
| المعيار / Metric | الأصلي / Original | المحسّن / Optimized | التحسن / Improvement |
|------------------|-------------------|---------------------|----------------------|
| عدد الأسطر / Lines of Code | 900+ | 580 | -35% |
| المتغيرات العامة / Global Variables | 60+ | 8 | -87% |
| نسبة التكرار / Code Duplication | ~40% | ~5% | -87% |
| أسطر الحذف / Deletion Lines | 60 | 22 | -63% |


التحسينات التقنية | Technical Improvements

1. الأنواع المخصصة | User Defined Types (UDT)
الأصلي | Original: 60+ متغير منفصل | 60+ separate variables
pinescript
var float bot_p1_price = na
var int bot_p1_idx = na
var float bot_p2_price = na
30 متغير للقاع | 30 variables for bottom
30 متغير للقمة | 30 variables for top

المحسّن | Optimized: نوعان فقط | Only 2 types
pinescript
type PatternPoint
int idx
float price

type PatternData
PatternPoint p1
PatternPoint p2
PatternPoint p3
PatternPoint p4
float quality_score


2. نظام الترجمة | Translation System

الأصلي | Original: switch يُنفذ كل شمعة | switch executes every bar
pinescript
get_text(key) =>
switch key
"smart_double_bottom" => is_arabic ? "قاع مزدوج" : "Double Bottom"
25 حالة | 25 cases

المحسّن | Optimized: Map يُملأ مرة واحدة | Map filled once
pinescript
var map<string, string> TXT_AR = map.new<string, string>()

if barstate.isfirst
TXT_AR.put("smart_double_bottom", "قاع مزدوج ذكي")

txt(key) => TXT_AR.get(key)


3. حذف الكائنات | Object Deletion

الأصلي | Original: 30 سطر مكرر | 30 repeated lines
pinescript
if not na(bot_neckline_left)
line.delete(bot_neckline_left)
if not na(bot_neckline_right)
line.delete(bot_neckline_right)
27 سطر إضافي | 27 more lines

المحسّن | Optimized: Method واحد | Single method
pinescript
method clear(PatternVisuals v) =>
line.delete(v.neckline_left)
line.delete(v.neckline_right)
line.delete(v.l12)
مكان واحد | one place

4. دوال الجودة | Quality Functions
الأصلي | Original: دالتان متطابقتان | 2 identical functions
pinescript
calculate_bottom_quality(...) => // 40 سطر | 40 lines
calculate_top_quality(...) => // 40 سطر | 40 lines

المحسّن | Optimized: دالة واحدة | Single function
pinescript
calc_quality(..., bool isBottom) => // 30 سطر | 30 lines


5. دوال الأهداف | Target Functions

الأصلي | Original: 4 دوال | 4 functions
pinescript
calculate_bottom_bullish_targets(...)
calculate_bottom_bearish_targets(...)
calculate_top_bearish_targets(...)
calculate_top_bullish_targets(...)

المحسّن | Optimized: دالتان | 2 functions
pinescript
calc_targets(..., bool isBullish)
calc_reverse_targets(..., bool isBottom)


6. دالة الرسم | Drawing Function

**الأصلي | Original:** كود مكرر | Duplicated code
- 80 سطر للقاع | 80 lines for bottom
- 80 سطر للقمة | 80 lines for top

المحسّن | Optimized: دالة واحدة | Single function
pinescript
draw_pattern(PatternData d, PatternVisuals v, bool isBottom)
// 35 سطر تغطي الحالتين | 35 lines cover both cases


ما لم يتغير | Unchanged Features

| الميزة / Feature | الحالة / Status |
|------------------|-----------------|
| منطق الكشف / Detection Logic | ✅ متطابق / Identical |
| معايير الجودة / Quality Criteria | ✅ متطابق / Identical |
| الفلاتر / Filters | ✅ متطابق / Identical |
| حسابات الأهداف / Target Calculations | ✅ متطابق / Identical |
| الإعدادات / Settings | ✅ متطابق / Identical |
| الألوان / Colors | ✅ متطابق / Identical |
| التنبيهات / Alerts | ✅ متطابق / Identical |
| النتيجة على الشارت / Chart Output | ✅ متطابق 100% / 100% Identical |


فوائد التحسين | Optimization Benefits

| الفائدة / Benefit | الوصف / Description |
|-------------------|---------------------|
| سهولة الصيانة / Easy Maintenance | تعديل واحد بدلاً من اثنين / One edit instead of two |
| أداء أفضل / Better Performance | Map أسرع من switch / Map faster than switch |
| كود أنظف / Cleaner Code | UDT بدلاً من متغيرات متفرقة / UDT instead of scattered variables |
| قابلية التوسع / Scalability | إضافة نماذج جديدة أسهل / Adding new patterns easier |
| تصحيح الأخطاء / Debugging | مكان واحد للبحث / Single place to search |


ميزات Pine Script v6 المستخدمة | Pine Script v6 Features Used

| الميزة / Feature | الاستخدام / Usage |
|------------------|-------------------|
| User Defined Types (UDT) | PatternData, PatternVisuals, PatternPoint |
| Methods | clear(), init(), reset() |
| Maps | TXT_AR, TXT_EN للترجمة / for translation |
| Type Arrays | array<line>, array<float> |


الخلاصة | Conclusion

النسخة المحسّنة تقدم نفس النتائج بكود أقل وأنظف وأسرع.
The optimized version delivers identical results with less, cleaner, and faster code.
Notas de prensa
✨ Improvements:

Settings Titles: English | Arabic
Group Names: ═══════ 🎯 Targets | Objectives ═══════
Tooltips: Explanation of each setting in both languages
Code Section Names: Section 1: UDT | First Section: Types
Chart Labels: Bottom 1 / Based on selected language
Alerts: Bilingual


✨ التحسينات:

عناوين الإعدادات: English | عربي
أسماء المجموعات: ═══════ 🎯 Targets | الأهداف ═══════
Tooltips: شرح لكل إعداد باللغتين
أسماء الأقسام في الكود: Section 1: UDT | القسم الأول: الأنواع
تسميات الشارت: قاع 1 / Bottom 1 حسب اللغة المختارة
التنبيهات: ثنائية اللغة

Exención de responsabilidad

La información y las publicaciones no constituyen, ni deben considerarse como asesoramiento o recomendaciones financieras, de inversión, de trading o de otro tipo proporcionadas o respaldadas por TradingView. Más información en Condiciones de uso.