File size: 27,438 Bytes
922bf26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
"""
Market Structure, Chart Pattern, and Candlestick Pattern Detector
Provides objective, rule-based detection for the TVTA Vision Dataset.
"""

import numpy as np
import pandas as pd
from typing import List, Dict, Any, Optional, Tuple


# ─── SWING POINT DETECTION ───────────────────────────────────────────────────

def find_swing_highs(lows: pd.Series, highs: pd.Series, order: int = 5) -> List[int]:
    """Find swing high indices: highs[i] is the highest in [i-order, i+order]."""
    swing_indices = []
    for i in range(order, len(highs) - order):
        if highs.iloc[i] == highs.iloc[i - order:i + order + 1].max():
            swing_indices.append(i)
    return swing_indices


def find_swing_lows(lows: pd.Series, highs: pd.Series, order: int = 5) -> List[int]:
    """Find swing low indices: lows[i] is the lowest in [i-order, i+order]."""
    swing_indices = []
    for i in range(order, len(lows) - order):
        if lows.iloc[i] == lows.iloc[i - order:i + order + 1].min():
            swing_indices.append(i)
    return swing_indices


# ─── MARKET STRUCTURE ────────────────────────────────────────────────────────

def detect_market_structure(
    df: pd.DataFrame, swing_order: int = 5
) -> Dict[str, Any]:
    """
    Detect market structure: HH, HL, LH, LL, BOS, CHoCH.
    Uses only data up to the final candle (no future leakage).
    """
    highs = df["high"]
    lows = df["low"]
    closes = df["close"]

    swing_highs = find_swing_highs(lows, highs, swing_order)
    swing_lows = find_swing_lows(lows, highs, swing_order)

    if len(swing_highs) < 2 and len(swing_lows) < 2:
        return {
            "classification": "neutral",
            "sequence": "",
            "break_of_structure": False,
            "change_of_character": False,
            "swing_highs": len(swing_highs),
            "swing_lows": len(swing_lows),
        }

    # Build structure sequence
    structure_seq = []
    all_swings = []
    for idx in swing_highs:
        all_swings.append(("H", idx, highs.iloc[idx]))
    for idx in swing_lows:
        all_swings.append(("L", idx, lows.iloc[idx]))
    all_swings.sort(key=lambda x: x[1])

    # Determine HH/HL/LH/LL
    prev_high = None
    prev_low = None
    seq_labels = []

    for swing_type, idx, price in all_swings:
        if swing_type == "H":
            if prev_high is not None:
                if price > prev_high:
                    seq_labels.append("HH")
                else:
                    seq_labels.append("LH")
            prev_high = price
        else:
            if prev_low is not None:
                if price > prev_low:
                    seq_labels.append("HL")
                else:
                    seq_labels.append("LL")
            prev_low = price

    sequence_str = "_".join(seq_labels) if seq_labels else ""

    # Classification
    hh_count = seq_labels.count("HH")
    ll_count = seq_labels.count("LL")
    hl_count = seq_labels.count("HL")
    lh_count = seq_labels.count("LH")

    if hh_count > lh_count and hl_count >= ll_count:
        classification = "bullish"
    elif ll_count > hl_count and lh_count >= hh_count:
        classification = "bearish"
    elif hh_count == ll_count and len(seq_labels) > 0:
        classification = "mixed"
    else:
        classification = "neutral"

    # Break of Structure (BOS): price breaks the last significant swing level
    bos = False
    if len(all_swings) >= 2:
        last_swing = all_swings[-1]
        prev_swing = all_swings[-2]
        if last_swing[0] == "H" and closes.iloc[-1] > last_swing[2]:
            bos = True
        elif last_swing[0] == "L" and closes.iloc[-1] < last_swing[2]:
            bos = True

    # Change of Character (CHoCH): structure reverses after a clear trend
    choch = False
    if len(seq_labels) >= 3:
        recent = seq_labels[-3:]
        if classification == "bullish" and "LL" in recent[:2]:
            choch = True
        elif classification == "bearish" and "HH" in recent[:2]:
            choch = True

    return {
        "classification": classification,
        "sequence": sequence_str,
        "break_of_structure": bos,
        "change_of_character": choch,
        "swing_highs": len(swing_highs),
        "swing_lows": len(swing_lows),
    }


# ─── TREND CLASSIFICATION ───────────────────────────────────────────────────

def classify_trend(df: pd.DataFrame, idx: int = -1) -> Dict[str, Any]:
    """
    Classify the dominant trend using objective rules.
    """
    if idx < 0:
        idx = len(df) + idx
    if idx < 0 or idx >= len(df):
        idx = len(df) - 1

    row = df.iloc[idx]
    close = row.get("close", 0)

    score = 0
    reasons = []

    # Moving average alignment
    ema20 = row.get("ema_20", 0)
    ema50 = row.get("ema_50", 0)
    ema200 = row.get("ema_200", 0)

    if ema20 > ema50 > ema200:
        score += 2
        reasons.append("ema_bullish_alignment")
    elif ema20 < ema50 < ema200:
        score -= 2
        reasons.append("ema_bearish_alignment")

    # Price vs MAs
    if close > ema20:
        score += 1
    else:
        score -= 1
    if close > ema200:
        score += 1
    else:
        score -= 1

    # RSI
    rsi = row.get("rsi_14", 50)
    if rsi > 60:
        score += 1
    elif rsi < 40:
        score -= 1

    # MACD
    macd = row.get("macd", 0)
    macd_sig = row.get("macd_signal", 0)
    if macd > macd_sig:
        score += 1
    else:
        score -= 1

    # ADX
    adx = row.get("adx", 20)
    trending = adx > 25

    # Price structure (last 20 candles)
    if idx >= 20:
        recent_highs = df["high"].iloc[idx - 20:idx + 1]
        recent_lows = df["low"].iloc[idx - 20:idx + 1]
        if recent_highs.is_monotonic_increasing:
            score += 1
        elif recent_highs.is_monotonic_decreasing:
            score -= 1
        if recent_lows.is_monotonic_increasing:
            score += 1
        elif recent_lows.is_monotonic_decreasing:
            score -= 1

    # Classify
    if score >= 5:
        trend = "strong_bullish"
    elif score >= 3:
        trend = "bullish"
    elif score >= 1:
        trend = "weak_bullish"
    elif score == 0:
        trend = "sideways"
    elif score >= -2:
        trend = "weak_bearish"
    elif score >= -4:
        trend = "bearish"
    else:
        trend = "strong_bearish"

    return {
        "classification": trend,
        "score": score,
        "trending": trending,
        "adx": round(float(adx), 2),
        "reasons": reasons,
    }


# ─── SUPPORT AND RESISTANCE ─────────────────────────────────────────────────

def find_support_resistance(
    df: pd.DataFrame,
    swing_order: int = 5,
    tolerance_pct: float = 0.01,
    min_touches: int = 2,
) -> Dict[str, Any]:
    """
    Find significant support and resistance levels from swing points.
    """
    highs = df["high"]
    lows = df["low"]

    swing_highs = find_swing_highs(lows, highs, swing_order)
    swing_lows = find_swing_lows(lows, highs, swing_order)

    # Cluster swing highs into resistance levels
    resistance_clusters = _cluster_levels(
        [highs.iloc[i] for i in swing_highs], tolerance_pct
    )
    support_clusters = _cluster_levels(
        [lows.iloc[i] for i in swing_lows], tolerance_pct
    )

    # Filter by minimum touches
    resistance_levels = []
    for price, touches in resistance_clusters:
        if touches >= min_touches:
            resistance_levels.append({
                "price": round(float(price), 2),
                "strength": _level_strength(touches),
                "touches": touches,
            })

    support_levels = []
    for price, touches in support_clusters:
        if touches >= min_touches:
            support_levels.append({
                "price": round(float(price), 2),
                "strength": _level_strength(touches),
                "touches": touches,
            })

    # Sort by proximity to current price
    current_price = df["close"].iloc[-1]
    resistance_levels.sort(key=lambda x: x["price"])
    support_levels.sort(key=lambda x: x["price"], reverse=True)

    # Keep only levels near current price
    resistance_levels = [
        r for r in resistance_levels
        if r["price"] > current_price * 0.95 and r["price"] < current_price * 1.15
    ]
    support_levels = [
        s for s in support_levels
        if s["price"] < current_price * 1.05 and s["price"] > current_price * 0.85
    ]

    return {
        "support_levels": support_levels[:5],
        "resistance_levels": resistance_levels[:5],
    }


def _cluster_levels(prices: List[float], tolerance_pct: float) -> List[Tuple[float, int]]:
    """Cluster nearby price levels."""
    if not prices:
        return []

    prices_sorted = sorted(prices)
    clusters = []
    current_cluster = [prices_sorted[0]]

    for p in prices_sorted[1:]:
        cluster_mean = np.mean(current_cluster)
        if abs(p - cluster_mean) / cluster_mean <= tolerance_pct:
            current_cluster.append(p)
        else:
            clusters.append((np.mean(current_cluster), len(current_cluster)))
            current_cluster = [p]

    if current_cluster:
        clusters.append((np.mean(current_cluster), len(current_cluster)))

    return clusters


def _level_strength(touches: int) -> str:
    if touches >= 5:
        return "very_strong"
    elif touches >= 3:
        return "strong"
    elif touches >= 2:
        return "medium"
    else:
        return "weak"


# ─── CANDLESTICK PATTERNS ───────────────────────────────────────────────────

def detect_candlestick_patterns(df: pd.DataFrame) -> List[Dict[str, Any]]:
    """
    Detect common candlestick patterns at the most recent candles.
    """
    patterns = []
    n = len(df)
    if n < 5:
        return patterns

    o = df["open"].values
    h = df["high"].values
    l = df["low"].values
    c = df["close"].values

    # Body and shadow sizes
    body = np.abs(c - o)
    upper_shadow = h - np.maximum(o, c)
    lower_shadow = np.minimum(o, c) - l
    total_range = h - l
    total_range = np.where(total_range == 0, 1e-10, total_range)

    avg_body = np.mean(body[-20:]) if n >= 20 else np.mean(body)

    # Doji: very small body
    for i in range(max(n - 5, 0), n):
        if body[i] < 0.1 * total_range[i]:
            patterns.append({
                "pattern": "doji",
                "index": i,
                "strength": "medium",
            })

    # Hammer: small body at upper end, long lower shadow
    for i in range(max(n - 5, 0), n):
        if (body[i] < 0.3 * total_range[i] and
            lower_shadow[i] > 2 * body[i] and
            upper_shadow[i] < 0.1 * total_range[i]):
            patterns.append({
                "pattern": "hammer",
                "index": i,
                "strength": "medium",
            })

    # Inverted Hammer: small body at lower end, long upper shadow
    for i in range(max(n - 5, 0), n):
        if (body[i] < 0.3 * total_range[i] and
            upper_shadow[i] > 2 * body[i] and
            lower_shadow[i] < 0.1 * total_range[i]):
            patterns.append({
                "pattern": "inverted_hammer",
                "index": i,
                "strength": "medium",
            })

    # Shooting Star: small body at lower end, long upper shadow, uptrend
    for i in range(max(n - 5, 0), n):
        if (body[i] < 0.3 * total_range[i] and
            upper_shadow[i] > 2 * body[i] and
            lower_shadow[i] < 0.1 * total_range[i] and
            c[i - 1] > o[i - 1] if i > 0 else False):
            patterns.append({
                "pattern": "shooting_star",
                "index": i,
                "strength": "medium",
            })

    # Bullish Engulfing
    for i in range(max(n - 5, 1), n):
        if (c[i - 1] < o[i - 1] and  # Previous bearish
            c[i] > o[i] and            # Current bullish
            o[i] <= c[i - 1] and
            c[i] >= o[i - 1]):
            patterns.append({
                "pattern": "bullish_engulfing",
                "index": i,
                "strength": "strong",
            })

    # Bearish Engulfing
    for i in range(max(n - 5, 1), n):
        if (c[i - 1] > o[i - 1] and  # Previous bullish
            c[i] < o[i] and            # Current bearish
            o[i] >= c[i - 1] and
            c[i] <= o[i - 1]):
            patterns.append({
                "pattern": "bearish_engulfing",
                "index": i,
                "strength": "strong",
            })

    # Morning Star (3-candle bullish reversal)
    for i in range(max(n - 5, 2), n):
        if (c[i - 2] < o[i - 2] and                    # Bearish
            body[i - 1] < 0.3 * body[i - 2] and          # Small body
            c[i] > o[i] and                               # Bullish
            c[i] > (o[i - 2] + c[i - 2]) / 2):           # Close above midpoint
            patterns.append({
                "pattern": "morning_star",
                "index": i,
                "strength": "strong",
            })

    # Evening Star (3-candle bearish reversal)
    for i in range(max(n - 5, 2), n):
        if (c[i - 2] > o[i - 2] and                    # Bullish
            body[i - 1] < 0.3 * body[i - 2] and          # Small body
            c[i] < o[i] and                               # Bearish
            c[i] < (o[i - 2] + c[i - 2]) / 2):           # Close below midpoint
            patterns.append({
                "pattern": "evening_star",
                "index": i,
                "strength": "strong",
            })

    # Three White Soldiers (3 consecutive bullish candles)
    for i in range(max(n - 5, 2), n):
        if (c[i - 2] > o[i - 2] and c[i - 1] > o[i - 1] and c[i] > o[i] and
            c[i - 2] < c[i - 1] < c[i] and o[i - 2] < o[i - 1] < o[i]):
            patterns.append({
                "pattern": "three_white_soldiers",
                "index": i,
                "strength": "strong",
            })

    # Three Black Crows (3 consecutive bearish candles)
    for i in range(max(n - 5, 2), n):
        if (c[i - 2] < o[i - 2] and c[i - 1] < o[i - 1] and c[i] < o[i] and
            c[i - 2] > c[i - 1] > c[i] and o[i - 2] > o[i - 1] > o[i]):
            patterns.append({
                "pattern": "three_black_crows",
                "index": i,
                "strength": "strong",
            })

    # Deduplicate: keep only the most recent occurrence of each pattern type
    seen = set()
    unique_patterns = []
    for p in reversed(patterns):
        if p["pattern"] not in seen:
            seen.add(p["pattern"])
            unique_patterns.append(p)
    unique_patterns.reverse()

    return unique_patterns


# ─── CHART PATTERN DETECTION ────────────────────────────────────────────────

def detect_chart_patterns(df: pd.DataFrame) -> List[Dict[str, Any]]:
    """
    Detect chart patterns from price structure.
    Returns patterns only when structural evidence meets criteria.
    """
    patterns = []
    n = len(df)
    if n < 30:
        return patterns

    highs = df["high"].values
    lows = df["low"].values
    closes = df["close"].values
    volumes = df["volume"].values

    # Find swing points
    swing_highs = find_swing_highs(df["low"], df["high"], 5)
    swing_lows = find_swing_lows(df["low"], df["high"], 5)

    # Double Top: two similar highs with a trough in between
    if len(swing_highs) >= 2:
        for i in range(len(swing_highs) - 1):
            h1 = highs[swing_highs[i]]
            h2 = highs[swing_highs[i + 1]]
            if abs(h1 - h2) / h1 < 0.02:  # Within 2%
                trough_idx = swing_highs[i] + np.argmin(lows[swing_highs[i]:swing_highs[i + 1]])
                trough = lows[trough_idx]
                if (h1 - trough) / h1 > 0.03:  # At least 3% drop
                    patterns.append({
                        "pattern": "double_top",
                        "strength": "strong",
                        "neckline": round(float(trough), 2),
                    })
                    break

    # Double Bottom: two similar lows with a peak in between
    if len(swing_lows) >= 2:
        for i in range(len(swing_lows) - 1):
            l1 = lows[swing_lows[i]]
            l2 = lows[swing_lows[i + 1]]
            if abs(l1 - l2) / l1 < 0.02:
                peak_idx = swing_lows[i] + np.argmax(highs[swing_lows[i]:swing_lows[i + 1]])
                peak = highs[peak_idx]
                if (peak - l1) / l1 > 0.03:
                    patterns.append({
                        "pattern": "double_bottom",
                        "strength": "strong",
                        "neckline": round(float(peak), 2),
                    })
                    break

    # Head and Shoulders: three highs with the middle highest
    if len(swing_highs) >= 3:
        for i in range(len(swing_highs) - 2):
            left = highs[swing_highs[i]]
            head = highs[swing_highs[i + 1]]
            right = highs[swing_highs[i + 2]]
            if head > left * 1.02 and head > right * 1.02:
                # Find neckline (lows between shoulders)
                neck_lows = lows[swing_highs[i]:swing_highs[i + 2] + 1]
                neckline = np.min(neck_lows)
                patterns.append({
                    "pattern": "head_and_shoulders",
                    "strength": "strong",
                    "neckline": round(float(neckline), 2),
                })
                break

    # Ascending Triangle: rising flat resistance, higher lows
    if len(swing_highs) >= 2 and len(swing_lows) >= 2:
        recent_highs = [highs[i] for i in swing_highs[-3:]]
        recent_lows = [lows[i] for i in swing_lows[-3:]]
        if (abs(recent_highs[-1] - recent_highs[0]) / recent_highs[0] < 0.01 and
            recent_lows[-1] > recent_lows[0]):
            patterns.append({
                "pattern": "ascending_triangle",
                "strength": "medium",
            })

    # Descending Triangle: falling flat support, lower highs
    if len(swing_highs) >= 2 and len(swing_lows) >= 2:
        recent_highs = [highs[i] for i in swing_highs[-3:]]
        recent_lows = [lows[i] for i in swing_lows[-3:]]
        if (abs(recent_lows[-1] - recent_lows[0]) / recent_lows[0] < 0.01 and
            recent_highs[-1] < recent_highs[0]):
            patterns.append({
                "pattern": "descending_triangle",
                "strength": "medium",
            })

    # Bull Flag: strong uptrend followed by consolidation
    if n >= 20:
        first_half = closes[:n // 2]
        second_half = closes[n // 2:]
        if (first_half[-1] > first_half[0] * 1.05 and  # Strong uptrend
            np.std(second_half) < np.std(first_half) * 0.5):  # Consolidation
            patterns.append({
                "pattern": "bull_flag",
                "strength": "medium",
            })

    # Bear Flag: strong downtrend followed by consolidation
    if n >= 20:
        first_half = closes[:n // 2]
        second_half = closes[n // 2:]
        if (first_half[-1] < first_half[0] * 0.95 and
            np.std(second_half) < np.std(first_half) * 0.5):
            patterns.append({
                "pattern": "bear_flag",
                "strength": "medium",
            })

    # Rectangle/Consolidation: price in a range
    if n >= 20:
        recent_high = np.max(highs[-20:])
        recent_low = np.min(lows[-20:])
        range_pct = (recent_high - recent_low) / recent_low
        if range_pct < 0.05:  # Less than 5% range
            patterns.append({
                "pattern": "rectangle",
                "strength": "medium",
                "range_high": round(float(recent_high), 2),
                "range_low": round(float(recent_low), 2),
            })

    # Deduplicate
    seen = set()
    unique = []
    for p in patterns:
        if p["pattern"] not in seen:
            seen.add(p["pattern"])
            unique.append(p)

    return unique


# ─── DIVERGENCE DETECTION ───────────────────────────────────────────────────

def detect_divergence(df: pd.DataFrame) -> List[Dict[str, Any]]:
    """
    Detect RSI and MACD divergence from price.
    """
    divergences = []
    n = len(df)
    if n < 30:
        return divergences

    if "rsi_14" not in df.columns:
        return divergences

    closes = df["close"].values
    rsi = df["rsi_14"].values

    # Find local swing points in price and RSI
    swing_highs = find_swing_highs(df["low"], df["high"], 5)
    swing_lows = find_swing_lows(df["low"], df["high"], 5)

    # Bullish RSI divergence: price makes lower low, RSI makes higher low
    if len(swing_lows) >= 2:
        for i in range(len(swing_lows) - 1):
            if (closes[swing_lows[i + 1]] < closes[swing_lows[i]] and
                rsi[swing_lows[i + 1]] > rsi[swing_lows[i]]):
                divergences.append({
                    "type": "bullish_rsi_divergence",
                    "indicator": "rsi",
                    "strength": "medium",
                })
                break

    # Bearish RSI divergence: price makes higher high, RSI makes lower high
    if len(swing_highs) >= 2:
        for i in range(len(swing_highs) - 1):
            if (closes[swing_highs[i + 1]] > closes[swing_highs[i]] and
                rsi[swing_highs[i + 1]] < rsi[swing_highs[i]]):
                divergences.append({
                    "type": "bearish_rsi_divergence",
                    "indicator": "rsi",
                    "strength": "medium",
                })
                break

    # MACD divergence
    if "macd" in df.columns:
        macd = df["macd"].values
        if len(swing_lows) >= 2:
            for i in range(len(swing_lows) - 1):
                if (closes[swing_lows[i + 1]] < closes[swing_lows[i]] and
                    macd[swing_lows[i + 1]] > macd[swing_lows[i]]):
                    divergences.append({
                        "type": "bullish_macd_divergence",
                        "indicator": "macd",
                        "strength": "medium",
                    })
                    break

        if len(swing_highs) >= 2:
            for i in range(len(swing_highs) - 1):
                if (closes[swing_highs[i + 1]] > closes[swing_highs[i]] and
                    macd[swing_highs[i + 1]] < macd[swing_highs[i]]):
                    divergences.append({
                        "type": "bearish_macd_divergence",
                        "indicator": "macd",
                        "strength": "medium",
                    })
                    break

    return divergences


# ─── BREAKOUT DETECTION ─────────────────────────────────────────────────────

def detect_breakout(df: pd.DataFrame) -> Dict[str, Any]:
    """
    Detect breakout/breakdown conditions.
    """
    n = len(df)
    if n < 20:
        return {"status": "no_breakout"}

    closes = df["close"].values
    volumes = df["volume"].values
    highs = df["high"].values
    lows = df["low"].values

    # Recent range
    recent_high = np.max(highs[-20:-1])  # Exclude last candle
    recent_low = np.min(lows[-20:-1])
    current_close = closes[-1]
    avg_vol = np.mean(volumes[-20:-1])
    current_vol = volumes[-1]

    result = {"status": "no_breakout"}

    # Upside breakout
    if current_close > recent_high:
        vol_confirm = current_vol > avg_vol * 1.2
        if vol_confirm:
            result = {
                "status": "confirmed_breakout",
                "direction": "up",
                "level": round(float(recent_high), 2),
                "volume_confirmation": True,
            }
        else:
            result = {
                "status": "potential_breakout",
                "direction": "up",
                "level": round(float(recent_high), 2),
                "volume_confirmation": False,
            }

    # Downside breakdown
    elif current_close < recent_low:
        vol_confirm = current_vol > avg_vol * 1.2
        if vol_confirm:
            result = {
                "status": "confirmed_breakdown",
                "direction": "down",
                "level": round(float(recent_low), 2),
                "volume_confirmation": True,
            }
        else:
            result = {
                "status": "potential_breakdown",
                "direction": "down",
                "level": round(float(recent_low), 2),
                "volume_confirmation": False,
            }

    return result


# ─── MARKET REGIME ──────────────────────────────────────────────────────────

def classify_market_regime(df: pd.DataFrame) -> Dict[str, Any]:
    """
    Classify the primary market regime.
    """
    n = len(df)
    if n < 20:
        return {"primary": "unknown", "secondary": []}

    closes = df["close"].values
    volumes = df["volume"].values

    # Volatility
    returns = np.diff(np.log(closes))
    current_vol = np.std(returns[-20:]) * np.sqrt(252)
    avg_vol = np.std(returns) * np.sqrt(252) if len(returns) > 0 else current_vol

    # Trend
    trend_info = classify_trend(df)
    trend = trend_info["classification"]

    # Range detection
    recent_high = np.max(df["high"].values[-20:])
    recent_low = np.min(df["low"].values[-20:])
    range_pct = (recent_high - recent_low) / recent_low

    # Volume pattern
    vol_mean = np.mean(volumes[-30:]) if n >= 30 else np.mean(volumes)
    vol_trend = np.mean(volumes[-10:]) / vol_mean if vol_mean > 0 else 1.0

    regime = "transition"
    secondary = []

    if current_vol > avg_vol * 1.5:
        secondary.append("high_volatility")
    elif current_vol < avg_vol * 0.5:
        secondary.append("low_volatility")

    if range_pct < 0.03 and "sideways" in trend:
        regime = "sideways_range"
    elif "bullish" in trend and vol_trend > 1.2:
        regime = "bull_trend"
    elif "bearish" in trend and vol_trend > 1.2:
        regime = "bear_trend"
    elif "bullish" in trend:
        regime = "accumulation"
    elif "bearish" in trend:
        regime = "distribution"
    elif current_vol > avg_vol * 1.5:
        regime = "high_volatility"

    # Breakout regime
    breakout = detect_breakout(df)
    if "confirmed_breakout" in breakout.get("status", ""):
        secondary.append("breakout_regime")
    elif "confirmed_breakdown" in breakout.get("status", ""):
        secondary.append("breakdown_regime")

    return {
        "primary": regime,
        "secondary": secondary,
        "volatility_annualized": round(float(current_vol), 4),
    }