File size: 36,581 Bytes
57a0292
 
 
 
7abdb5a
94c6592
 
57a0292
 
 
 
 
 
 
 
 
 
 
 
 
7abdb5a
 
 
 
57a0292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6bf0d8
 
 
 
 
7abdb5a
20ce5d1
94c6592
 
3d227b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94c6592
3d227b7
 
 
 
 
 
 
 
 
 
 
 
94c6592
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d227b7
7abdb5a
 
 
 
3d227b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7abdb5a
 
b0cd8be
 
7abdb5a
 
 
 
 
 
 
 
 
f6bf0d8
 
7abdb5a
 
 
 
94c6592
3d227b7
7abdb5a
 
f6bf0d8
 
7abdb5a
 
94c6592
3d227b7
7abdb5a
 
f6bf0d8
 
7abdb5a
 
94c6592
 
7abdb5a
 
 
 
 
f6bf0d8
7abdb5a
f6bf0d8
 
94c6592
3d227b7
94c6592
f6bf0d8
94c6592
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d227b7
94c6592
 
 
 
 
 
 
 
 
b0cd8be
 
7abdb5a
3d227b7
7abdb5a
 
94c6592
7abdb5a
 
 
 
 
 
 
 
 
94c6592
 
 
7abdb5a
 
 
94c6592
7abdb5a
 
 
 
 
 
 
94c6592
7abdb5a
 
 
 
 
3d227b7
7abdb5a
 
57a0292
 
 
 
 
 
 
 
7abdb5a
 
57a0292
 
 
 
 
 
 
 
7abdb5a
 
 
 
b0cd8be
7abdb5a
 
 
f6bf0d8
7abdb5a
f6bf0d8
57a0292
7abdb5a
3d227b7
7abdb5a
57a0292
 
94c6592
 
 
 
57a0292
 
f6bf0d8
 
 
 
57a0292
 
 
 
 
 
 
 
7abdb5a
 
57a0292
 
 
 
 
 
f6bf0d8
 
57a0292
 
 
f6bf0d8
 
57a0292
 
26dbf50
 
 
 
 
 
 
 
94c6592
26dbf50
94c6592
26dbf50
 
 
 
 
 
 
 
 
 
 
 
94c6592
 
 
26dbf50
94c6592
26dbf50
94c6592
26dbf50
94c6592
26dbf50
 
94c6592
 
26dbf50
 
 
 
94c6592
26dbf50
 
 
 
 
 
 
 
 
 
 
 
 
7abdb5a
 
 
 
57a0292
 
 
 
 
 
 
 
 
 
94c6592
57a0292
 
 
 
94c6592
57a0292
94c6592
57a0292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26dbf50
 
 
 
 
 
 
 
57a0292
20ce5d1
94c6592
 
 
 
 
 
 
 
 
 
 
 
57a0292
7abdb5a
57a0292
94c6592
 
7abdb5a
57a0292
 
 
f6bf0d8
 
 
 
 
57a0292
 
 
 
3d227b7
67f0f71
 
 
 
 
7abdb5a
67f0f71
 
94c6592
 
 
 
 
 
 
 
20ce5d1
 
94c6592
20ce5d1
94c6592
 
 
 
 
 
 
 
 
57a0292
94c6592
 
 
 
 
 
 
 
 
 
67f0f71
94c6592
 
 
 
 
57a0292
 
7abdb5a
 
3d227b7
7abdb5a
 
f6bf0d8
7abdb5a
 
 
 
 
 
 
 
 
3d227b7
57a0292
 
 
 
 
 
 
 
 
94c6592
 
20ce5d1
 
57a0292
 
 
 
 
 
 
 
 
 
f6bf0d8
57a0292
 
 
 
7abdb5a
 
 
 
 
 
 
 
 
 
 
 
 
 
94c6592
 
 
7abdb5a
57a0292
7abdb5a
 
57a0292
7abdb5a
94c6592
7abdb5a
 
 
f6bf0d8
 
 
57a0292
 
f6bf0d8
57a0292
f6bf0d8
57a0292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26dbf50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94c6592
 
 
57a0292
94c6592
57a0292
 
 
 
 
 
 
7abdb5a
b0cd8be
7abdb5a
f6bf0d8
 
26dbf50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94c6592
 
 
 
 
 
 
 
 
 
 
 
 
 
20ce5d1
57a0292
 
 
 
 
7abdb5a
 
57a0292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6bf0d8
57a0292
 
 
 
 
 
 
 
 
 
f6bf0d8
57a0292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94c6592
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
import math
import logging
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from typing import Any, Dict, List, Set
from collections import defaultdict
from datetime import datetime

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("s8-confidence")

app = FastAPI(title="Confidence Engine s8")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# ═══════════════════════════════════════════════════════════════
# LAYER 0 β€” MATH HELPERS
# ═══════════════════════════════════════════════════════════════

if not hasattr(math, "erf"):
    def erf(x):
        s = -1 if x < 0 else 1
        ax = abs(x)
        t = 1 / (1 + 0.3275911 * ax)
        y = 1 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t
                  - 0.284496736) * t + 0.254829592) * t * math.exp(-ax * ax)
        return s * y
    math.erf = erf


def clamp(v, lo=0.05, hi=0.95):
    return max(lo, min(hi, v))


def logit(p):
    return math.log(p / (1 - p))


def sigmoid(x):
    return 1 / (1 + math.exp(-x))


def entropy(p):
    p = clamp(p, 0.001, 0.999)
    return -(p * math.log(p) + (1 - p) * math.log(1 - p))


# ═══════════════════════════════════════════════════════════════
# LAYER 1 β€” SIGNAL DIVERGENCE INDEX
# ═══════════════════════════════════════════════════════════════

def signal_divergence_index(signals: List[Dict], tf_agree: float) -> float:
    families = {}
    for i, sig in enumerate(signals):
        for fam in indicator_families(i):
            if fam not in families:
                families[fam] = []
            families[fam].append(sig["score"])

    if len(families) < 2:
        return 0.0

    family_means = {}
    for fam, scores in families.items():
        family_means[fam] = sum(scores) / len(scores)

    means = list(family_means.values())
    mean_of_means = sum(means) / len(means)
    variance = sum((m - mean_of_means) ** 2 for m in means) / len(means)

    range_means = max(means) - min(means) if len(means) > 1 else 0.25
    max_variance = (range_means ** 2) * 0.5
    if max_variance < 1e-8:
        max_variance = 0.25

    normalized_variance = min(1.0, variance / max_variance)
    tf_disagreement = 1.0 - tf_agree
    divergence = (normalized_variance * 0.6) + (tf_disagreement * 0.4)
    return round(divergence, 3)


# ═══════════════════════════════════════════════════════════════
# LAYER 1B β€” DYNAMIC INDICATOR WEIGHTS
# ═══════════════════════════════════════════════════════════════

_signal_performance = defaultdict(lambda: {"correct": 0, "total": 0, "weight_multiplier": 1.0})
_recent_predictions = []

def update_indicator_performance(family: str, was_correct: bool):
    perf = _signal_performance[family]
    perf["total"] += 1
    if was_correct:
        perf["correct"] += 1
    
    if perf["total"] > 100:
        perf["correct"] = perf["correct"] * 0.9
        perf["total"] = int(perf["total"] * 0.9)
    
    accuracy = perf["correct"] / max(perf["total"], 1)
    perf["weight_multiplier"] = 0.5 + accuracy


def get_dynamic_weight(base_weight: float, family: str) -> float:
    perf = _signal_performance[family]
    adjusted = base_weight * perf["weight_multiplier"]
    return max(base_weight * 0.5, min(base_weight * 1.5, adjusted))


def record_prediction_outcome(symbol: str, predicted_direction: str, confidence: float, actual_price_change: float):
    was_correct = (predicted_direction == "bullish" and actual_price_change > 0) or \
                  (predicted_direction == "bearish" and actual_price_change < 0) or \
                  (predicted_direction == "neutral" and abs(actual_price_change) < 0.005)
    
    families = ["trend", "momentum", "volatility", "sentiment", "volume_flow", "order_flow"]
    for family in families:
        update_indicator_performance(family, was_correct)
    
    _recent_predictions.append({
        "timestamp": datetime.now().isoformat(),
        "confidence": confidence,
        "was_correct": was_correct,
        "symbol": symbol
    })
    
    while len(_recent_predictions) > 100:
        _recent_predictions.pop(0)


# ═══════════════════════════════════════════════════════════════
# LAYER 1C β€” SIGNAL CLASSIFICATION
# ═══════════════════════════════════════════════════════════════

def indicator_families(idx: int) -> Set[str]:
    mapping = {
        0:  {"volatility"},
        1:  {"volatility"},
        2:  {"momentum"},
        3:  {"volatility"},
        4:  {"trend"},
        5:  {"trend"},
        6:  {"trend"},
        7:  {"momentum"},
        8:  {"momentum", "volume_flow"},
        9:  {"momentum"},
        10: {"sentiment"},
        11: {"sentiment"},
        12: {"sentiment"},
        13: {"order_flow", "sentiment"},
        14: {"order_flow"},
        15: {"order_flow"},
    }
    return mapping.get(idx, {"other"})


def signal_strength(score: float) -> float:
    e = entropy(score)
    max_e = entropy(0.5)
    raw = 1.0 - (e / max_e)
    return 0.15 + raw * 0.85


def regime_gate(regime: str, families: Set[str]) -> float:
    gate = 1.0

    if regime in ("trend", "strong_trend"):
        if "trend" in families:
            gate = max(gate, 1.3)
        if "momentum" in families:
            gate = max(gate, 1.2)
        if "order_flow" in families:
            gate = max(gate, 1.15)
        if "volatility" in families and "trend" not in families:
            gate = min(gate, 0.9)

    elif regime == "mean_revert":
        if "momentum" in families or "volatility" in families:
            gate = max(gate, 1.2)
        if "order_flow" in families:
            gate = min(gate, 0.7)
        if "trend" in families:
            gate = min(gate, 0.5)

    elif regime == "random_walk":
        if "trend" in families or "momentum" in families:
            gate = min(gate, 0.4)
        if "order_flow" in families:
            gate = min(gate, 0.6)
        elif "volatility" in families:
            gate = min(gate, 0.6)

    if families.issubset({"volume_flow", "sentiment"}):
        return 1.0

    return gate


# ═══════════════════════════════════════════════════════════════
# LAYER 1D β€” CROSS-ASSET CORRELATIONS
# ═══════════════════════════════════════════════════════════════

def calculate_cross_asset_impact(symbol: str, btc_iv: float, eth_iv: float) -> dict:
    is_btc = "BTC" in symbol.upper()
    is_eth = "ETH" in symbol.upper()
    
    result = {
        "btc_correlation_impact": 1.0,
        "eth_correlation_impact": 1.0,
        "volatility_spillover": 1.0,
        "btc_dominance_signal": "neutral"
    }
    
    if is_btc:
        return result
    
    if btc_iv:
        if btc_iv > 70:
            result["volatility_spillover"] = 1.15
            result["btc_dominance_signal"] = "btc_volatile"
        elif btc_iv > 50:
            result["volatility_spillover"] = 1.05
    
    if is_eth:
        if eth_iv and eth_iv > 80:
            result["volatility_spillover"] = max(result["volatility_spillover"], 1.1)
    
    return result


# ═══════════════════════════════════════════════════════════════
# LAYER 2 β€” INFERENCE
# ═══════════════════════════════════════════════════════════════

TEMPERATURE = 1.5


def aggregate_log_odds(signals: List[Dict], regime: str):
    s_lo, w_total = 0.0, 0.0

    for i, sig in enumerate(signals):
        score = clamp(sig["score"])
        base_weight = sig["weight"]
        families = indicator_families(i)
        
        primary_family = next(iter(families)) if families else "other"
        dynamic_weight = get_dynamic_weight(base_weight, primary_family)

        strength = signal_strength(score)
        gate = regime_gate(regime, families)
        final_weight = dynamic_weight * strength * gate

        s_lo += (logit(score) / TEMPERATURE) * final_weight
        w_total += final_weight

    if w_total == 0:
        return 50, 0.0

    directional_raw = s_lo / w_total
    confidence = round(sigmoid(directional_raw * TEMPERATURE) * 100)
    return confidence, directional_raw


# ═══════════════════════════════════════════════════════════════
# LAYER 3 β€” CALIBRATION
# ═══════════════════════════════════════════════════════════════

def cornish_fisher_calibrate(prob, skew, kurt):
    if abs(skew) < 1e-4 and abs(kurt - 3) < 1e-2:
        return prob
    clamped_p = clamp(prob, 0.001, 0.999)

    def inv_norm(p):
        sgn = -1 if p < 0.5 else 1
        t_val = math.sqrt(-2 * math.log(p if p < 0.5 else 1 - p))
        return sgn * (t_val - (2.30753 + t_val * 0.27061) /
                      (1 + t_val * (0.99229 + t_val * 0.04481)))

    z = inv_norm(clamped_p)
    cf = z + (z**2 - 1) * skew / 6 \
           + (z**3 - 3*z) * (kurt - 3) / 24 \
           - (2*z**3 - 5*z) * (skew**2) / 36
    return max(0.0, min(1.0, 0.5 * (1 + math.erf(cf / math.sqrt(2)))))


def apply_penalties_log_space(penalties: List[float], floor: float = 0.15) -> float:
    valid = [p for p in penalties if p > 0]
    if not valid:
        return floor

    log_sum = sum(math.log(p) for p in valid)
    avg_log = log_sum / len(valid)
    result = math.exp(avg_log)

    return max(floor, min(1.0, result))


# ═══════════════════════════════════════════════════════════════
# LAYER 4 β€” INTERPRETATION
# ═══════════════════════════════════════════════════════════════

def fear_index(garch_vol, adx_val, streak_obj, dd_obj, vol_spike, r_vol3, a_vol20, c3, c4):
    vF = min(1.0, garch_vol * 100 / 3)
    dF = min(1.0, dd_obj.get("drawdownPct", 0) / 12)
    sF = min(1.0, streak_obj.get("streak", 0) / 8) if streak_obj.get("direction") == "bear" else 0.0
    aF = min(1.0, (adx_val - 30) / 40) if adx_val > 30 else 0.0
    vfF = 0.8 if (vol_spike and r_vol3 > a_vol20 * 2.5 and c3 < c4) else 0.0
    score = round((vF*0.30 + dF*0.25 + sF*0.20 + aF*0.15 + vfF*0.10) * 100)
    if score < 25: level = "low"
    elif score < 50: level = "moderate"
    elif score < 75: level = "high"
    else: level = "extreme"
    return {"fearScore": score, "fearLevel": level}


def atr_sanity_check(current_price, bull, bear, atr_val):
    range_pred = bull - bear
    too_tight = range_pred < (atr_val * 2)
    return {
        "tooTight": too_tight,
        "suggestion": "Predicted range < 1 ATR β€” widen expectations"
        if too_tight else "Consistent with volatility"
    }


def linear_regression_slope(closes, max_periods=200):
    data = closes[-max_periods:]
    n = len(data)
    if n < 2: return 0.0
    sX, sY = sum(range(n)), sum(data)
    sXY = sum(i * data[i] for i in range(n))
    sX2 = sum(i * i for i in range(n))
    denom = n * sX2 - sX * sX
    if denom == 0: return 0.0
    return (n * sXY - sX * sY) / denom / (data[0] or 1)


def calculate_trend_continuation_probability(adx_val, hurst, primary_trend, regime):
    if primary_trend == "neutral":
        return 0.5
    
    adx_prob = min(0.85, max(0.5, adx_val / 50))
    
    hurst_adjust = 0.0
    if hurst > 0.55:
        hurst_adjust = 0.15
    elif hurst < 0.45:
        hurst_adjust = -0.15
    
    regime_adjust = 0.0
    if regime == "strong_trend":
        regime_adjust = 0.10
    elif regime == "mean_revert":
        regime_adjust = -0.20
    
    prob = adx_prob + hurst_adjust + regime_adjust
    return max(0.15, min(0.95, prob))


def calculate_volatility_adjusted_sizing(garch_vol, fear_score, confidence_score):
    if garch_vol < 0.005:
        base_size = 0.25
    elif garch_vol < 0.01:
        base_size = 0.20
    elif garch_vol < 0.02:
        base_size = 0.15
    elif garch_vol < 0.035:
        base_size = 0.10
    else:
        base_size = 0.05
    
    fear_multiplier = 1.0 - (fear_score / 200)
    confidence_multiplier = 0.5 + (confidence_score / 200)
    
    final_size = base_size * fear_multiplier * confidence_multiplier
    final_size = max(0.02, min(0.25, final_size))
    
    stop_multiplier = 1.0 + (garch_vol * 50)
    stop_multiplier = max(1.0, min(3.0, stop_multiplier))
    
    tp_multiplier = 1.5 if fear_score < 50 else 1.2
    
    return {
        "recommended_position_size_pct": round(final_size * 100, 1),
        "max_position_size_pct": round(final_size * 1.5 * 100, 1),
        "stop_loss_multiplier": round(stop_multiplier, 2),
        "take_profit_multiplier": round(tp_multiplier, 2),
        "volatility_regime": "extreme" if garch_vol > 0.035 else "high" if garch_vol > 0.02 else "normal" if garch_vol > 0.01 else "low"
    }


# ═══════════════════════════════════════════════════════════════
# MAIN ENDPOINT
# ═══════════════════════════════════════════════════════════════

@app.post("/compute")
async def compute_confidence(payload: Dict[str, Any]):
    try:
        primary     = payload.get("primary", {})
        indicators  = payload.get("indicators", {})
        vol_model   = payload.get("volModel", {})
        mc          = payload.get("mc", {})
        sentiment   = payload.get("sentiment", {})
        iv_data     = payload.get("ivData", {})

        closes = primary.get("closes", [])
        if len(closes) < 50:
            raise HTTPException(400, "Need β‰₯50 primary candles")

        last_close = closes[-1]
        symbol = payload.get("symbol", "BTC/USDT")

        # ── Unpack existing fields ──
        rsi_val       = indicators.get("rsi", 50)
        bb_upper      = indicators.get("bollingerUpper", last_close)
        bb_lower      = indicators.get("bollingerLower", last_close)
        garch_vol     = vol_model.get("currentVol", 0.01)
        egarch_vol    = indicators.get("egarchVol", 0.01)
        yz_vol        = indicators.get("yangZhangVol", 0.01)
        mc_spread     = mc.get("spread", 0.02)

        adx_obj       = indicators.get("adx", {})
        adx_val       = adx_obj.get("adx", 20)
        adx_trending  = adx_obj.get("trending", False)
        adx_ranging   = adx_obj.get("ranging", False)

        macd_obj      = indicators.get("macd", {})
        streak_obj    = {"streak": indicators.get("streak", 0),
                         "direction": indicators.get("streakDirection", "neutral"),
                         "strongStreak": indicators.get("strongStreak", False)}
        dd_obj        = {"drawdownPct": indicators.get("drawdownPct", 0),
                         "severeDrawdown": indicators.get("severeDrawdown", False),
                         "extremeDrawdown": indicators.get("extremeDrawdown", False)}

        primary_trend = indicators.get("primaryTrend", "neutral")
        medium_trend  = indicators.get("mediumTrend", "neutral")
        macro_trend   = indicators.get("macroTrend", "neutral")
        ema_stack     = indicators.get("emaStackScore", 0)
        hurst         = indicators.get("hurst", 0.5)
        regime        = indicators.get("regime", "random_walk")

        vol_sig       = indicators.get("volumeSignal", 0.5)
        wick_bias     = indicators.get("wickBias", "neutral")
        vol_spike     = vol_model.get("volSpikeActive", False)

        prob_above    = mc.get("probabilityAbove", 0.5)
        prob_below    = mc.get("probabilityBelow", 0.5)
        bull_case     = mc.get("bullCase", last_close)
        bear_case     = mc.get("bearCase", last_close)
        median_case   = mc.get("medianCase", last_close)
        pred_mean     = mc.get("predMean", last_close)
        atr_val       = indicators.get("atr", last_close * 0.01)
        
        quantile_95   = mc.get("quantile_95", bull_case)
        quantile_05   = mc.get("quantile_05", bear_case)
        prob_up_2pct  = mc.get("prob_up_2pct", 0.5)
        prob_down_2pct = mc.get("prob_down_2pct", 0.5)
        skewness      = mc.get("skewness", 0.0)
        confidence_interval_80 = mc.get("confidence_interval_80", [last_close * 0.95, last_close * 1.05])
        confidence_interval_90 = mc.get("confidence_interval_90", [last_close * 0.92, last_close * 1.08])

        # ── Extract order flow fields from S3 (now real data) ──
        cumulative_delta = sentiment.get("cumulativeDelta", 0)
        delta_trend = sentiment.get("deltaTrend", "neutral")
        delta_strength = sentiment.get("deltaStrength", 0)
        cvd_bullish = sentiment.get("cvdBullish", False)
        cvd_bearish = sentiment.get("cvdBearish", False)
        whale_activity = sentiment.get("whaleActivity", False)
        aggressive_buying = sentiment.get("aggressiveBuying", False)
        aggressive_selling = sentiment.get("aggressiveSelling", False)
        bid_wall = sentiment.get("bidWall", False)
        ask_wall = sentiment.get("askWall", False)
        ob_imbalance_20 = sentiment.get("obImbalance20", 0)

        normalized_slope = linear_regression_slope(closes, 200)
        primary_is_bull = primary_trend == "bull"

        cross_asset = calculate_cross_asset_impact(symbol, iv_data.get("btcIV"), iv_data.get("ethIV"))

        # Timeframe agreement
        trends = [primary_trend, medium_trend, macro_trend]
        non_neutral = [t for t in trends if t != "neutral"]
        if len(non_neutral) >= 2:
            bulls, bears = non_neutral.count("bull"), non_neutral.count("bear")
            if bulls == len(non_neutral) or bears == len(non_neutral): tf_agree = 1.0
            elif max(bulls, bears) >= 2: tf_agree = 0.6
            else: tf_agree = 0.3
        else: tf_agree = 0.3
        if (primary_trend == "bull" and normalized_slope > 0.0001) or \
           (primary_trend == "bear" and normalized_slope < -0.0001):
            tf_agree = min(1.0, tf_agree + 0.1)

        # ── LAYER 1: Build evidence ──
        cmf_val = indicators.get("chaikinMoneyFlow", 0)
        cmf_signal = clamp(0.5 + cmf_val * 0.5)

        kc_upper = indicators.get("keltnerUpper", last_close)
        kc_lower = indicators.get("keltnerLower", last_close)
        kc_position = (last_close - kc_lower) / (kc_upper - kc_lower) if (kc_upper and kc_lower and kc_upper != kc_lower) else 0.5
        kc_signal = clamp(kc_position)

        if cvd_bullish:
            cvd_signal = 0.7 + delta_strength * 0.3
        elif cvd_bearish:
            cvd_signal = 0.3 - delta_strength * 0.3
        else:
            cvd_signal = 0.5 + (cumulative_delta / max(abs(cumulative_delta), 1)) * 0.1 if cumulative_delta != 0 else 0.5
        cvd_signal = clamp(cvd_signal)

        # FIXED: map S3's "rising"/"falling" to signal score
        if delta_trend == "rising":
            delta_trend_signal = 0.65
        elif delta_trend == "falling":
            delta_trend_signal = 0.35
        else:
            delta_trend_signal = 0.5

        whale_signal = 0.6 if whale_activity and cvd_bullish else (0.4 if whale_activity and cvd_bearish else 0.5)
        whale_signal = clamp(whale_signal)

        ob_signal = clamp(0.5 + ob_imbalance_20 * 0.8)

        signals = [
            {"score": clamp(max(0, 1 - garch_vol * 100 / 4)),          "weight": 0.10},
            {"score": clamp(max(0, 1 - mc_spread / 0.15)),             "weight": 0.08},
            {"score": clamp(1 - abs(rsi_val - 50) / 50),               "weight": 0.07},
            {"score": clamp(max(0, 1 - ((bb_upper-bb_lower)/last_close)/0.08)), "weight": 0.05},
            {"score": clamp(tf_agree),                                  "weight": 0.09},
            {"score": clamp(adx_val/50 if adx_trending else 0.3),      "weight": 0.07},
            {"score": clamp(ema_stack / 5),                             "weight": 0.07},
            {"score": clamp(hurst if hurst > 0.55 else 1 - hurst),     "weight": 0.06},
            {"score": cmf_signal,                                       "weight": 0.05},
            {"score": kc_signal,                                        "weight": 0.04},
            {"score": clamp(sentiment.get("sentimentScore", 50)/100),   "weight": 0.06},
            {"score": clamp(sentiment.get("takerBuyRatio", 0.5)),       "weight": 0.04},
            {"score": ob_signal,                                        "weight": 0.04},
            {"score": cvd_signal,                                       "weight": 0.08},
            {"score": delta_trend_signal,                               "weight": 0.06},
            {"score": whale_signal,                                     "weight": 0.04},
        ]

        divergence_index = signal_divergence_index(signals, tf_agree)

        # ── LAYER 2: Inference ──
        raw_conf, directional_raw = aggregate_log_odds(signals, regime)
        raw_conf = raw_conf / 100

        # ── LAYER 3: Calibration ──
        log_ret = [math.log(closes[i]/closes[i-1]) for i in range(1, len(closes))]
        if len(log_ret) > 10:
            skew = sum(r**3 for r in log_ret) / len(log_ret)
            kurt = sum(r**4 for r in log_ret) / len(log_ret)
        else: skew, kurt = 0, 3

        calibrated = cornish_fisher_calibrate(raw_conf, skew, kurt)

        # Build penalty list
        contra_checks = [
            medium_trend == primary_trend,
            macro_trend == primary_trend,
            (normalized_slope > 0.0001) == primary_is_bull if abs(normalized_slope) > 0.0001 else None,
            sentiment.get("fundingBullish", False) == primary_is_bull if sentiment.get("fundingBullish") or sentiment.get("fundingBearish") else None,
            wick_bias == ("bullish" if primary_is_bull else "bearish"),
            streak_obj["direction"] == primary_trend,
            (rsi_val > 50) == primary_is_bull,
            sentiment.get("takerBullish", False) == primary_is_bull,
            (ob_imbalance_20 > 0) == primary_is_bull,
            cvd_bullish == primary_is_bull if cvd_bullish or cvd_bearish else None,
            # FIXED: use real delta_trend values ("rising"/"falling")
            (delta_trend == "rising") == primary_is_bull if delta_trend != "neutral" else None,
        ]
        contra_checks = [c for c in contra_checks if c is not None]
        agree_count = sum(contra_checks)
        total_sig = len(contra_checks)
        contra_ratio = (1 - agree_count/total_sig) if total_sig > 0 else 0

        vol_contra = (primary_is_bull and vol_sig < 0.40) or (not primary_is_bull and vol_sig > 0.60)
        macro_opp = (primary_is_bull and normalized_slope < -0.0001) or (not primary_is_bull and normalized_slope > 0.0001)
        sanity = atr_sanity_check(last_close, bull_case, bear_case, atr_val)

        r_vol3, a_vol20 = 0, 0.01
        fear = fear_index(garch_vol, adx_val, streak_obj, dd_obj, vol_spike, r_vol3, a_vol20,
                          closes[-3] if len(closes)>=3 else last_close,
                          closes[-4] if len(closes)>=4 else last_close)

        penalties = [
            1 - contra_ratio * 0.55,
            0.75 + (1 - abs(vol_sig - 0.5)*2)*0.25 if vol_contra else 1.0,
            0.78 if macro_opp else 1.0,
            0.80 if adx_ranging else 1.0,
            0.85 if (streak_obj.get("strongStreak") and indicators.get("streakMeanReversionLikely")) else 1.0,
            0.88 if sanity["tooTight"] else 1.0,
            0.65 if dd_obj.get("extremeDrawdown") else (0.82 if dd_obj.get("severeDrawdown") else 1.0),
            max(0.40, 1 - fear["fearScore"]/100),
            0.85 if vol_spike else 1.0,
            0.90 if (sentiment.get("oiTrend") == "falling" and primary_is_bull) or
                    (sentiment.get("oiTrend") == "rising" and not primary_is_bull) else 1.0,
            0.88 if iv_data.get("ivElevated", False) else 1.0,
            1.0 - (divergence_index * 0.35),
            cross_asset["volatility_spillover"] if cross_asset["volatility_spillover"] > 1.05 else 1.0,
            0.92 if (whale_activity and not primary_is_bull) or (whale_activity and cvd_bearish) else 1.0,
            0.95 if bid_wall or ask_wall else 1.0,
        ]

        penalty_multiplier = apply_penalties_log_space(penalties)
        confidence_score = round(max(0, min(100, calibrated * 100 * penalty_multiplier)))

        # ── LAYER 4: Interpretation ──
        directional_bias_raw = directional_raw
        directional_display = round(max(-1.0, min(1.0, sigmoid(directional_raw) * 2 - 1)), 3)
        if directional_display > 0.15: directional_signal = "bullish"
        elif directional_display < -0.15: directional_signal = "bearish"
        else: directional_signal = "neutral"

        bear_mult, bull_mult = 1.25, 0.80
        level = fear["fearLevel"]
        if level == "moderate": bear_mult, bull_mult = 1.35, 0.75
        elif level == "high": bear_mult, bull_mult = 1.50, 0.70
        elif level == "extreme": bear_mult, bull_mult = 1.70, 0.65
        if dd_obj.get("severeDrawdown"): bear_mult += 0.10
        if dd_obj.get("extremeDrawdown"): bear_mult += 0.20
        if streak_obj["direction"] == "bear" and streak_obj.get("strongStreak"): bear_mult += 0.10

        max_move = last_close * 0.40
        adj_bear = max(last_close - max_move, pred_mean - (pred_mean - bear_case) * bear_mult)
        adj_bull = min(last_close + max_move, pred_mean + (bull_case - pred_mean) * bull_mult)

        oi_diverges = False
        if len(closes) >= 25:
            price_change_24h = (last_close - closes[-25]) / closes[-25]
            oi_trend = sentiment.get("oiTrend", "neutral")
            if (price_change_24h > 0.01 and oi_trend == "falling") or \
               (price_change_24h < -0.01 and oi_trend == "rising"):
                oi_diverges = True

        trend_continuation_prob = calculate_trend_continuation_probability(
            adx_val, hurst, primary_trend, regime
        )
        
        position_sizing = calculate_volatility_adjusted_sizing(
            garch_vol, fear["fearScore"], confidence_score
        )
        
        mean_reversion_likelihood = 0.0
        if regime == "mean_revert":
            mean_reversion_likelihood = 0.75
        elif hurst < 0.45:
            mean_reversion_likelihood = 0.60
        elif adx_ranging:
            mean_reversion_likelihood = 0.55
        else:
            mean_reversion_likelihood = 0.30
        
        if streak_obj.get("strongStreak"):
            mean_reversion_likelihood = min(0.85, mean_reversion_likelihood + 0.15)

        dynamic_weights = {family: round(get_dynamic_weight(1.0, family), 2) for family in 
                          ["trend", "momentum", "volatility", "sentiment", "volume_flow", "order_flow"]}

        return {
            "symbol": symbol,
            "timeframe": payload.get("timeframe", "1h"),
            "currentPrice": last_close,
            "predictedMean": pred_mean,
            "medianCase": median_case,
            "bullCase": round(adj_bull, 2),
            "bearCase": round(adj_bear, 2),
            "confidenceScore": confidence_score,
            "directionalBias": directional_display,
            "directionalSignal": directional_signal,
            "directionalRaw": round(directional_bias_raw, 4),
            "signalDivergence": divergence_index,
            "regimeInstability": divergence_index > 0.35,
            
            "confidenceInterval80": [round(confidence_interval_80[0], 2), round(confidence_interval_80[1], 2)],
            "confidenceInterval90": [round(confidence_interval_90[0], 2), round(confidence_interval_90[1], 2)],
            
            "probUp2pct": prob_up_2pct,
            "probDown2pct": prob_down_2pct,
            "probUp5pct": mc.get("prob_up_5pct", 0.25),
            "probDown5pct": mc.get("prob_down_5pct", 0.25),
            
            "quantile95": round(quantile_95, 2),
            "quantile05": round(quantile_05, 2),
            "skewness": skewness,
            "upsidePotentialRatio": mc.get("upside_potential_ratio", 1.0),
            
            "trendContinuationProbability": round(trend_continuation_prob, 3),
            "meanReversionLikelihood": round(mean_reversion_likelihood, 3),
            
            "positionSizing": position_sizing,
            
            "cumulativeDelta": cumulative_delta,
            "deltaTrend": delta_trend,
            "deltaStrength": delta_strength,
            "cvdBullish": cvd_bullish,
            "cvdBearish": cvd_bearish,
            "whaleActivity": whale_activity,
            "aggressiveBuying": aggressive_buying,
            "aggressiveSelling": aggressive_selling,
            "bidWall": bid_wall,
            "askWall": ask_wall,
            
            "crossAssetImpact": cross_asset,
            "dynamicWeights": dynamic_weights,
            
            # All original fields (backward compatible)
            "garchVolatility": round(garch_vol * 100, 2),
            "egarchVolatility": round(egarch_vol * 100, 2),
            "yangZhangVol": round(yz_vol * 100, 2),
            "monteCarloSpread": round(mc_spread * 100, 2),
            "rsi": round(rsi_val, 2),
            "ema20": round(indicators.get("ema20", last_close), 2),
            "ema50": round(indicators.get("ema50", last_close), 2),
            "bollingerUpper": round(bb_upper, 2),
            "bollingerLower": round(bb_lower, 2),
            "emaStackScore": ema_stack,
            "emaCompressed": indicators.get("emaCompressed", False),
            "emaCompression": round(indicators.get("emaCompression", 0), 6),
            "emaStackBull": indicators.get("emaStackBull", False),
            "acf1": round(indicators.get("acf1", 0), 4),
            "acf5": round(indicators.get("acf5", 0), 4),
            "hurst": round(hurst, 4),
            "regime": regime,
            "volState": indicators.get("volState", "normal"),
            "meanReversionLikely": indicators.get("meanReversionLikely", False),
            "volumePOC": round(indicators.get("volumePOC", 0), 2),
            "volumeVAH": round(indicators.get("volumeVAH", 0), 2),
            "volumeVAL": round(indicators.get("volumeVAL", 0), 2),
            "obvNormalized": round(indicators.get("obvNormalized", 0), 4),
            "vwapDistance": round(indicators.get("vwapDistance", 0), 6),
            "primaryTrend": primary_trend,
            "mediumTrend": medium_trend,
            "macroTrend": macro_trend,
            "timeframeAgreement": round(tf_agree, 2),
            "normalizedSlope": round(normalized_slope, 6),
            "volSpike": vol_spike,
            "volumeSignal": round(vol_sig, 3),
            "atr": round(atr_val, 4),
            "adx": round(adx_val, 1),
            "adxTrending": adx_trending,
            "adxRanging": adx_ranging,
            "macdHistogram": round(macd_obj.get("histogram", 0), 4),
            "macdBullish": macd_obj.get("bullish", False),
            "macdMomentumFading": macd_obj.get("momentumFading", False),
            "macdCrossoverBull": macd_obj.get("crossoverBull", False),
            "macdCrossoverBear": macd_obj.get("crossoverBear", False),
            "drawdownPct": round(dd_obj["drawdownPct"], 2),
            "inDrawdown": indicators.get("inDrawdown", False),
            "severeDrawdown": dd_obj["severeDrawdown"],
            "extremeDrawdown": dd_obj["extremeDrawdown"],
            "streak": streak_obj["streak"],
            "streakDirection": streak_obj["direction"],
            "strongStreak": streak_obj["strongStreak"],
            "extremeStreak": indicators.get("extremeStreak", False),
            "wickBias": wick_bias,
            "sellingAtHighs": indicators.get("sellingAtHighs", False),
            "buyingAtLows": indicators.get("buyingAtLows", False),
            "volDivergence": indicators.get("volDivergence", False),
            "fearScore": fear["fearScore"],
            "fearLevel": fear["fearLevel"],
            "fundingRate": sentiment.get("fundingRate"),
            "longShortRatio": sentiment.get("longShortRatio"),
            "fundingBullish": sentiment.get("fundingBullish", False),
            "fundingBearish": sentiment.get("fundingBearish", False),
            "crowdedLong": sentiment.get("crowdedLong", False),
            "crowdedShort": sentiment.get("crowdedShort", False),
            "sentimentScore": sentiment.get("sentimentScore", 50),
            "takerBuyRatio": sentiment.get("takerBuyRatio", 0.5),
            "takerSellRatio": sentiment.get("takerSellRatio", 0.5),
            "takerBullish": sentiment.get("takerBullish", False),
            "takerBearish": sentiment.get("takerBearish", False),
            "obImbalance": sentiment.get("obImbalance", 0),
            "obBullish": sentiment.get("obBullish", False),
            "obBearish": sentiment.get("obBearish", False),
            "longLiqUSD": 0, "shortLiqUSD": 0,
            "liqRatio": sentiment.get("liqRatio", 0.5),
            "dominantLiq": sentiment.get("dominantLiq", "neutral"),
            "liqIntense": sentiment.get("liqIntense", False),
            "oiChange": sentiment.get("oiChange", 0),
            "oiTrend": sentiment.get("oiTrend", "neutral"),
            "oiDiverges": oi_diverges,
            "btcIV": iv_data.get("btcIV"),
            "ethIV": iv_data.get("ethIV"),
            "ivElevated": iv_data.get("ivElevated", False),
            "ivSpread": iv_data.get("ivSpread"),
            "beta": 1.0, "betaR2": 0.0,
            "atrSanityOk": not sanity["tooTight"],
            "atrSuggestion": sanity["suggestion"],
            "probabilityAbove": prob_above,
            "probabilityBelow": prob_below,
            "contradictionRatio": round(contra_ratio, 2),
            "agreementCount": agree_count,
            "totalSignals": total_sig,
            "macroOpposesPrimary": macro_opp,
            "volumeContradictsPrimary": vol_contra,
        }

    except HTTPException:
        raise
    except Exception as e:
        logger.exception("Confidence engine failed")
        raise HTTPException(500, f"Confidence error: {str(e)}")


@app.get("/health")
async def health():
    return {"status": "ok", "service": "s8-confidence"}


@app.post("/record_outcome")
async def record_outcome(symbol: str, predicted_direction: str, confidence: float, actual_price_change: float):
    record_prediction_outcome(symbol, predicted_direction, confidence, actual_price_change)
    return {"status": "recorded"}


@app.get("/weight_status")
async def get_weight_status():
    weights = {}
    for family, perf in _signal_performance.items():
        accuracy = perf["correct"] / max(perf["total"], 1)
        weights[family] = {
            "weight_multiplier": round(perf["weight_multiplier"], 2),
            "accuracy": round(accuracy, 3),
            "samples": perf["total"]
        }
    return {"weights": weights}