-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoracle_engine.py
More file actions
2220 lines (1963 loc) · 92.3 KB
/
Copy pathoracle_engine.py
File metadata and controls
2220 lines (1963 loc) · 92.3 KB
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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
"""
ORACLE ENGINE — Fused Wolf / Insider / Quant analysis pipeline.
Consumes the structured report produced by ``tool_full_coin_intelligence_report``
and deterministically executes all nine phases of the ORACLE spec:
Phase 1 — Regime detection
Phase 2 — Multi-Timeframe signal engine (MTF)
Phase 3 — Smart-Money divergence (DPI + WFI)
Phase 4 — Pattern confidence engine
Phase 5 — Macro adjustment
Phase 6 — Composite score + signal
Phase 7 — Bayesian scenarios + 24H expected value
Phase 8 — Trade execution plan (entry / SL / TP / Kelly / size)
Phase 9 — Risk audit
Returns both a structured dict and a fully formatted Markdown brief that
matches the FINAL OUTPUT FORMAT section of ``prompts/analysis_oracle.md``.
"""
from typing import Any, Dict, List, Optional, Tuple
# ----------------------------------------------------------------------
# Small helpers
# ----------------------------------------------------------------------
def _g(d: Optional[Dict], *keys, default=None):
"""Safe nested dict getter."""
cur: Any = d
for k in keys:
if not isinstance(cur, dict):
return default
cur = cur.get(k)
if cur is None:
return default
return cur if cur is not None else default
def _num(x, default=None):
try:
if x is None:
return default
return float(x)
except (TypeError, ValueError):
return default
def _clamp(x: float, lo: float, hi: float) -> float:
return max(lo, min(hi, x))
def _fmt_price(x: Optional[float]) -> str:
if x is None:
return "n/a"
try:
v = float(x)
except (TypeError, ValueError):
return "n/a"
if v >= 100:
return f"{v:,.2f}"
if v >= 1:
return f"{v:.4f}"
if v >= 0.01:
return f"{v:.6f}"
return f"{v:.8f}"
def _pct(x: Optional[float], digits: int = 2) -> str:
if x is None:
return "n/a"
try:
return f"{float(x):+.{digits}f}%"
except (TypeError, ValueError):
return "n/a"
# ----------------------------------------------------------------------
# Phase 1 — Regime detection
# ----------------------------------------------------------------------
def detect_regime(ta_4h: Dict, ta_1d: Dict) -> Dict[str, Any]:
"""Classify as TRENDING / RANGING / VOLATILE / CHAOTIC per the spec."""
adx_4h = _num(_g(ta_4h, "adx"))
adx_1d = _num(_g(ta_1d, "adx"))
atr_pct_4h = _num(_g(ta_4h, "atr_pct"))
bb_squeeze_4h = bool(_g(ta_4h, "bb_squeeze", default=False))
bb_bw = _num(_g(ta_4h, "bb_bandwidth"))
# Representative ADX: prefer 4H, fall back to 1D
adx = adx_4h if adx_4h is not None else adx_1d
# CHAOTIC proxy: ATR% > 8 (crypto scale) -> chaotic
chaotic = atr_pct_4h is not None and atr_pct_4h >= 8.0
if chaotic:
regime = "CHAOTIC"
reason = f"ATR on 4H is {atr_pct_4h:.2f}% of price — volatility well above normal, standard signals unreliable."
multiplier = 0.50
elif bb_squeeze_4h:
regime = "VOLATILE"
reason = "Bollinger squeeze active on 4H — breakout pending, direction unconfirmed until volume expansion."
multiplier = 0.70
elif adx is not None and adx > 25:
regime = "TRENDING"
reason = f"ADX {adx:.1f} on 4H/1D confirms directional trend — momentum tools are primary."
multiplier = 1.00
elif adx is not None and adx < 20:
regime = "RANGING"
reason = f"ADX {adx:.1f} indicates consolidation — oscillators dominate, trend tools downweighted."
multiplier = 0.85
else:
regime = "RANGING"
reason = "ADX in transition zone — treating as range until directional break confirmed."
multiplier = 0.85
return {
"regime": regime,
"reason": reason,
"multiplier": multiplier,
"adx_4h": adx_4h,
"adx_1d": adx_1d,
"atr_pct_4h": atr_pct_4h,
"bb_squeeze_4h": bb_squeeze_4h,
"bb_bandwidth_4h": bb_bw,
}
# ----------------------------------------------------------------------
# Phase 2 — Multi-Timeframe signal engine
# ----------------------------------------------------------------------
def score_timeframe(ta: Dict, regime: str) -> Dict[str, Any]:
"""Compute raw signal score (-100..+100) for one timeframe."""
if not isinstance(ta, dict) or ta.get("error"):
return {"score": 0, "contributions": [], "available": False}
contribs: List[Tuple[str, float]] = []
def add(label: str, pts: float):
if pts:
contribs.append((label, round(pts, 2)))
# Weights for regime-sensitive grouping
trend_w = 0.5 if regime == "RANGING" else 1.0
osc_w = 1.3 if regime == "RANGING" else 1.0
# -------- Trend --------
if _g(ta, "price_vs_ema200") == "above":
add("Price > EMA200", +20 * trend_w)
elif _g(ta, "price_vs_ema200") == "below":
add("Price < EMA200", -20 * trend_w)
if _g(ta, "golden_cross_active"):
add("Golden cross", +15 * trend_w)
if _g(ta, "death_cross_active"):
add("Death cross", -15 * trend_w)
# Ichimoku
pvc = _g(ta, "ichimoku", "price_vs_cloud")
cc = _g(ta, "ichimoku", "cloud_color")
if pvc == "above" and cc == "bullish":
add("Ichimoku price>cloud (green)", +10 * trend_w)
elif pvc == "below" and cc == "bearish":
add("Ichimoku price<cloud (red)", -10 * trend_w)
tk = _g(ta, "ichimoku", "tk_cross")
if tk == "bullish":
add("TK cross bullish", +8 * trend_w)
elif tk == "bearish":
add("TK cross bearish", -8 * trend_w)
# ADX + DI
adx = _num(_g(ta, "adx"))
dp = _num(_g(ta, "di_plus"))
dm = _num(_g(ta, "di_minus"))
if adx is not None and dp is not None and dm is not None and adx > 25:
if dp > dm:
add("ADX>25 DI+>DI-", +6 * trend_w)
elif dm > dp:
add("ADX>25 DI->DI+", -6 * trend_w)
# -------- Momentum (oscillators) --------
rsi = _num(_g(ta, "rsi"))
if rsi is not None:
# RSI 45-55 is truly neutral — don't award points for doing nothing
if 45 <= rsi <= 55:
pass # Neutral — no signal
elif 55 < rsi <= 65:
add("RSI upper momentum", +8 * osc_w)
elif 35 <= rsi < 45:
add("RSI lower momentum", -8 * osc_w)
elif rsi < 30:
add("RSI oversold reversal", +12 * osc_w)
elif rsi > 70:
add("RSI overbought", -12 * osc_w)
mc = _g(ta, "macd_crossover")
hist = _num(_g(ta, "macd_histogram"))
if mc == "bullish_cross":
add("MACD bull cross", +15)
elif mc == "bearish_cross":
add("MACD bear cross", -15)
ml = _num(_g(ta, "macd_line"))
ms = _num(_g(ta, "macd_signal"))
if ml is not None and ms is not None:
if ml > 0 and ms > 0:
add("MACD above zero", +8)
elif ml < 0 and ms < 0:
add("MACD below zero", -8)
k = _num(_g(ta, "stochrsi_k"))
d = _num(_g(ta, "stochrsi_d"))
if k is not None and d is not None:
if k > d and k < 0.2:
add("StochRSI oversold cross", +10 * osc_w)
elif k < d and k > 0.8:
add("StochRSI overbought cross", -10 * osc_w)
cmf = _num(_g(ta, "cmf"))
if cmf is not None:
if cmf > 0.1:
add("CMF strong inflow", +8)
elif cmf < -0.1:
add("CMF strong outflow", -8)
mfi = _num(_g(ta, "mfi"))
if mfi is not None:
if 40 <= mfi <= 60:
add("MFI healthy", +6)
elif mfi > 80 or mfi < 20:
add("MFI extreme", -6)
cci = _num(_g(ta, "cci"))
if cci is not None:
if -110 < cci < -80:
add("CCI recovery", +5)
elif 80 < cci < 110:
add("CCI exhaustion", -5)
# -------- Volatility / Structure --------
pb = _num(_g(ta, "bb_percent_b"))
vol_vs_avg = _num(_g(ta, "volume_vs_avg"))
if pb is not None and rsi is not None and vol_vs_avg is not None:
if pb < 0.1 and rsi < 40 and vol_vs_avg > 1:
add("Lower BB + RSI<40 + vol rising", +10 * osc_w)
elif pb > 0.9 and rsi > 60 and vol_vs_avg > 1:
add("Upper BB + RSI>60 + vol rising", -10 * osc_w)
if _g(ta, "bb_squeeze") and _g(ta, "volume_spike"):
if pb is not None and pb > 0.8:
add("BB squeeze up-break + vol spike", +8)
elif pb is not None and pb < 0.2:
add("BB squeeze down-break + vol spike", -8)
if _g(ta, "price_vs_vwap") == "above":
add("Price > VWAP", +6)
elif _g(ta, "price_vs_vwap") == "below":
add("Price < VWAP", -6)
# -------- Volume (regime-aware) --------
if _g(ta, "volume_spike"):
td = _g(ta, "trend_direction")
if regime == "RANGING":
# In range: volume spike at resistance = rejection (bearish)
# volume spike at support = bounce (bullish)
if pb is not None:
if pb > 0.8: # Near upper BB / resistance
add("Vol spike at resistance (rejection)", -10 * osc_w)
elif pb < 0.2: # Near lower BB / support
add("Vol spike at support (bounce)", +10 * osc_w)
else:
pass # Midrange volume spike is ambiguous in range
else:
# In trend: volume confirms direction
if td == "bullish":
add("Volume spike up-candle", +10)
elif td == "bearish":
add("Volume spike down-candle", -10)
obv_t = _g(ta, "obv_trend")
if obv_t == "up":
add("OBV higher highs", +8)
elif obv_t == "down":
add("OBV lower lows", -8)
# -------- CVD (Cumulative Volume Delta) --------
cvd_div = _g(ta, "cvd_divergence")
if cvd_div == "bullish_accumulation":
add("CVD bullish divergence (stealth accumulation)", +15)
elif cvd_div == "bearish_distribution":
add("CVD bearish divergence (stealth distribution)", -15)
cvd_trend = _g(ta, "cvd_trend")
if cvd_trend == "rising":
add("CVD trend rising (buy pressure)", +6)
elif cvd_trend == "falling":
add("CVD trend falling (sell pressure)", -6)
# -------- Divergences (powerful) --------
tf_name = _g(ta, "timeframe") or ""
div = _g(ta, "rsi_divergence")
if div == "bullish":
add("RSI bull divergence", +20 if tf_name in ("4h", "1d") else 12)
elif div == "bearish":
add("RSI bear divergence", -20 if tf_name in ("4h", "1d") else -12)
total = sum(pts for _, pts in contribs)
total = _clamp(total, -100, 100)
return {
"score": round(total, 2),
"contributions": contribs,
"available": True,
"rsi": rsi,
"macd_crossover": mc,
"bb_percent_b": pb,
"volume_vs_avg": vol_vs_avg,
"trend_direction": _g(ta, "trend_direction"),
"rsi_divergence": div,
"cvd_divergence": cvd_div,
}
def compute_mtf(technical_analysis: Dict, regime: str) -> Dict[str, Any]:
"""Score all 4 timeframes and weight them."""
weights = {"1d": 0.40, "4h": 0.30, "1h": 0.20, "15m": 0.10}
per_tf: Dict[str, Dict] = {}
weighted = 0.0
total_w = 0.0
for tf, w in weights.items():
ta = technical_analysis.get(tf) if isinstance(technical_analysis, dict) else None
s = score_timeframe(ta or {}, regime)
per_tf[tf] = s
if s["available"]:
weighted += s["score"] * w
total_w += w
mtf = (weighted / total_w) if total_w > 0 else 0.0
# Regime filter on composite
if regime == "VOLATILE":
mtf *= 0.6
elif regime == "CHAOTIC":
mtf *= 0.3
return {"per_tf": per_tf, "mtf_score": round(_clamp(mtf, -100, 100), 2)}
# ----------------------------------------------------------------------
# Phase 3 — Smart Money Divergence Engine (DPI + WFI)
# ----------------------------------------------------------------------
def compute_smart_money(report: Dict, current_price: Optional[float]) -> Dict[str, Any]:
derivs = report.get("derivatives") or {}
fr = derivs.get("funding_rates") or {}
oi = derivs.get("open_interest") or {}
whale = report.get("whale_and_onchain") or {}
ob = report.get("order_book") or {}
contribs: List[Tuple[str, float]] = []
def add(label: str, pts: float):
if pts:
contribs.append((label, round(pts, 2)))
# --- DPI ---
# Funding (already as percent in fetcher)
f = _num(fr.get("current_funding_rate"))
if f is not None:
if f > 0.1:
add("Funding >+0.1% (extreme long crowd)", -20)
elif f > 0.05:
add("Funding >+0.05% (long crowded)", -15)
elif f < -0.02:
add("Funding <-0.02% (short crowded)", +20)
elif abs(f) <= 0.01:
add("Funding ~0 (accumulation)", +15)
# OI vs price change — use per-TF signals as proxy for direction
oi_val = _num(oi.get("open_interest_usdt"))
# We do not have delta-OI/delta-price here directly; skip unless available.
# Long/short ratio
ls = _num(oi.get("long_short_ratio"))
if ls is not None:
if ls < 0.8:
add("L/S<0.8 squeeze fuel", +10)
elif ls > 1.5:
add("L/S>1.5 flush fuel", -10)
# Liquidation walls — approximate from order book walls relative to price
bid_wall = _num(ob.get("bid_wall_at"))
ask_wall = _num(ob.get("ask_wall_at"))
if current_price and ask_wall and ask_wall > current_price:
dist = (ask_wall - current_price) / current_price
if dist < 0.05:
add("Ask wall / short liq cluster just above", +15)
if current_price and bid_wall and bid_wall < current_price:
dist = (current_price - bid_wall) / current_price
if dist < 0.05:
add("Bid wall / long liq cluster just below", -15)
# --- WFI ---
net_flow = _num(whale.get("exchange_net_flow_24h"))
if net_flow is not None:
if net_flow < 0:
add("Exchange net outflow (accumulation)", +20)
elif net_flow > 0:
add("Exchange net inflow (distribution)", -20)
buys = _num(whale.get("whale_buy_count"))
sells = _num(whale.get("whale_sell_count"))
if buys is not None and sells is not None and (buys + sells) >= 3:
share_buy = buys / (buys + sells)
if share_buy > 0.7:
add("Whale buys >70%", +15)
elif share_buy < 0.3:
add("Whale sells >70%", -15)
total = sum(p for _, p in contribs)
total = _clamp(total, -100, 100)
return {
"score": round(total, 2),
"contributions": contribs,
"funding_rate_pct": f,
"funding_sentiment": fr.get("funding_sentiment"),
"open_interest_usdt": oi_val,
"long_short_ratio": ls,
"net_flow_24h": net_flow,
"net_flow_interpretation": whale.get("net_flow_interpretation"),
"whale_buy_count": buys,
"whale_sell_count": sells,
}
# ----------------------------------------------------------------------
# Phase 4 — Pattern confidence
# ----------------------------------------------------------------------
PATTERN_TABLE = {
"inverse_head_and_shoulders": (+25, 75, "bullish"),
"inverse_h&s": (+25, 75, "bullish"),
"head_and_shoulders": (-25, 75, "bearish"),
"double_bottom": (+20, 72, "bullish"),
"double_top": (-20, 72, "bearish"),
"triple_bottom": (+20, 70, "bullish"),
"triple_top": (-20, 70, "bearish"),
"bull_flag": (+18, 70, "bullish"),
"bear_flag": (-18, 70, "bearish"),
"ascending_triangle": (+15, 65, "bullish"),
"descending_triangle": (-15, 65, "bearish"),
"cup_and_handle": (+15, 65, "bullish"),
"symmetrical_triangle": (0, 58, "neutral"),
"falling_wedge": (+12, 62, "bullish"),
"rising_wedge": (-12, 62, "bearish"),
"bullish_engulfing": (+10, 62, "bullish"),
"bearish_engulfing": (-10, 62, "bearish"),
"morning_star": (+12, 65, "bullish"),
"evening_star": (-12, 65, "bearish"),
"hammer": (+10, 60, "bullish"),
"shooting_star": (-10, 60, "bearish"),
}
def _pattern_key(name: str) -> str:
return (name or "").strip().lower().replace(" ", "_").replace("-", "_")
def compute_pattern_score(chart_patterns: Dict, mtf_score: float) -> Dict[str, Any]:
strongest = _g(chart_patterns, "strongest_pattern") or {}
name = strongest.get("pattern") or strongest.get("name") or strongest.get("type") or ""
key = _pattern_key(name)
base = PATTERN_TABLE.get(key)
direction = "neutral"
confidence = None
raw = 0.0
conflict = False
if base is not None:
points, confidence, direction = base
# Scale by the pattern's detected confidence if provided
detected_conf = _num(strongest.get("confidence_pct")) or confidence
scale = (detected_conf or confidence) / 100.0
raw = points * scale
# Conflict check vs MTF direction
mtf_dir = "bullish" if mtf_score > 10 else ("bearish" if mtf_score < -10 else "neutral")
if direction != "neutral" and mtf_dir != "neutral" and direction != mtf_dir:
conflict = True
raw = raw * 0.5
return {
"score": round(_clamp(raw, -100, 100), 2),
"pattern_name": name or "none",
"pattern_direction": direction,
"base_confidence_pct": confidence,
"conflicts_with_mtf": conflict,
}
# ----------------------------------------------------------------------
# Phase 5 — Macro adjustment
# ----------------------------------------------------------------------
def compute_macro(report: Dict, is_btc: bool, beta: Optional[float]) -> Dict[str, Any]:
fg = _g(report, "macro_context", "fear_greed") or {}
gm = _g(report, "macro_context", "global_market") or {}
fg_val = _num(fg.get("current_value"))
fg_trend = fg.get("trend")
fg_adj = 0
if fg_val is not None:
if fg_val < 15:
fg_adj = +20
elif fg_val < 30:
fg_adj = +10
elif fg_val < 45:
fg_adj = +5
elif fg_val <= 55:
fg_adj = 0
elif fg_val <= 70:
fg_adj = -5
elif fg_val <= 85:
fg_adj = -15
else:
fg_adj = -25
btc_dom = _num(gm.get("btc_dominance_pct"))
btc_dom_adj = 0 # without a reliable 7d dominance delta we default to 0
# If the report carries a 7d change we honor it
btc_dom_7d_change = _num(gm.get("btc_dominance_change_7d"))
if btc_dom_7d_change is not None and not is_btc:
if btc_dom_7d_change > 1:
btc_dom_adj = -10
elif btc_dom_7d_change < -1:
btc_dom_adj = +10
macro_total = fg_adj + btc_dom_adj
size_haircut = 0.0
if beta is not None and beta > 2.0:
size_haircut = 0.25 # reduce recommended size by 25%
return {
"score": round(_clamp(macro_total, -100, 100), 2),
"fear_greed_value": fg_val,
"fear_greed_trend": fg_trend,
"fear_greed_adjustment": fg_adj,
"btc_dominance_pct": btc_dom,
"btc_dominance_adjustment": btc_dom_adj,
"beta_vs_btc": beta,
"size_haircut_from_beta": size_haircut,
}
# ----------------------------------------------------------------------
# Sentiment sub-score (small)
# ----------------------------------------------------------------------
def compute_sentiment_score(report: Dict) -> Dict[str, Any]:
s = report.get("sentiment") or {}
trend_rank = _num(s.get("trending_rank_coingecko"))
votes_up = _num(s.get("sentiment_votes_up_pct"))
score = 0.0
if trend_rank is not None:
if trend_rank <= 5:
score += 15
elif trend_rank <= 15:
score += 8
if votes_up is not None:
if votes_up > 75:
score += 10
elif votes_up > 60:
score += 5
elif votes_up < 40:
score -= 5
# ── News headline scoring (was previously fetched but never consumed) ──
news = report.get("news") or {}
headlines = news.get("news", []) if isinstance(news, dict) else []
if headlines:
# Simple keyword-based sentiment from headlines
bullish_keywords = {"surge", "rally", "soar", "bull", "breakout", "pump", "adoption",
"partnership", "upgrade", "launch", "moon", "ath", "record"}
bearish_keywords = {"crash", "dump", "bear", "hack", "exploit", "ban", "lawsuit",
"sec", "fraud", "collapse", "plunge", "sell-off", "selloff"}
bull_hits = 0
bear_hits = 0
for h in headlines:
title = (h.get("title") or "").lower()
for kw in bullish_keywords:
if kw in title:
bull_hits += 1
for kw in bearish_keywords:
if kw in title:
bear_hits += 1
if bull_hits > bear_hits + 1:
score += 10
elif bear_hits > bull_hits + 1:
score -= 10
return {"score": round(_clamp(score, -100, 100), 2),
"trending_rank": trend_rank,
"sentiment_votes_up_pct": votes_up,
"news_headlines_count": len(headlines)}
# ----------------------------------------------------------------------
# Phase 6 — Composite + signal label
# ----------------------------------------------------------------------
def composite(mtf: float, smart: float, pattern: float, sentiment: float,
macro: float, regime_multiplier: float) -> Dict[str, Any]:
raw = (mtf * 0.40) + (smart * 0.25) + (pattern * 0.15) + (sentiment * 0.10) + (macro * 0.10)
final = _clamp(raw * regime_multiplier, -100, 100)
if final >= 70:
sig = "STRONG_BUY"
elif final >= 45:
sig = "BUY"
elif final >= 20:
sig = "WEAK_BUY"
elif final > -20:
sig = "NEUTRAL"
elif final > -45:
sig = "WEAK_SELL"
elif final > -70:
sig = "SELL"
else:
sig = "STRONG_SELL"
return {
"raw_pre_regime": round(raw, 2),
"final_score": round(final, 2),
"signal": sig,
"contributions": {
"mtf": round(mtf * 0.40, 2),
"smart_money": round(smart * 0.25, 2),
"pattern": round(pattern * 0.15, 2),
"sentiment": round(sentiment * 0.10, 2),
"macro": round(macro * 0.10, 2),
},
}
# ----------------------------------------------------------------------
# Phase 7 — Heuristic scenarios + EV24H
# NOTE: Probabilities are score-derived heuristics, NOT Bayesian posteriors.
# They require empirical calibration via backtesting to be trustworthy.
# ----------------------------------------------------------------------
def build_scenarios(current_price: Optional[float], atr_4h: Optional[float],
sr: Dict, final_score: float) -> Dict[str, Any]:
if not current_price:
return {"error": "no current price"}
atr = atr_4h or (current_price * 0.02)
res = (sr or {}).get("strong_resistances") or []
sup = (sr or {}).get("strong_supports") or []
r1 = _num((res[0] or {}).get("level")) if res else None
r2 = _num((res[1] or {}).get("level")) if len(res) > 1 else None
s1 = _num((sup[0] or {}).get("level")) if sup else None
s2 = _num((sup[1] or {}).get("level")) if len(sup) > 1 else None
bull_24h = (r1 if r1 and r1 > current_price else current_price + 1.5 * atr)
bull_7d = (r2 if r2 and r2 > bull_24h else bull_24h + 2.5 * atr)
bear_24h = (s1 if s1 and s1 < current_price else current_price - 1.5 * atr)
bear_7d = (s2 if s2 and s2 < bear_24h else bear_24h - 2.5 * atr)
# Probabilities skewed by final_score (-100..+100 -> probability tilt)
tilt = final_score / 100.0 # -1..+1
base_prob = 0.55 - 0.10 * abs(tilt) # stronger edge reduces base weight
remaining = 1.0 - base_prob
# Split remaining between bull/bear weighted by sign of tilt
bull_share = 0.5 + 0.5 * tilt # 0..1
bull_prob = remaining * bull_share
bear_prob = remaining * (1 - bull_share)
def pct(a: float) -> float:
return (a - current_price) / current_price * 100.0
base_mid = current_price # base case midpoint = roughly current price
base_low = current_price - 0.75 * atr
base_high = current_price + 0.75 * atr
bull_pct = pct(bull_24h)
bear_pct = pct(bear_24h)
base_pct_mid = pct(base_mid)
ev_24h = (bull_prob * bull_pct) + (base_prob * base_pct_mid) + (bear_prob * bear_pct)
return {
"bull": {
"prob_pct": round(bull_prob * 100, 1),
"target_24h": bull_24h,
"target_24h_pct": round(bull_pct, 2),
"target_7d": bull_7d,
"target_7d_pct": round(pct(bull_7d), 2),
"trigger": f"Close > {_fmt_price(r1 or bull_24h)} on 4H with volume >150% of 20-period average",
},
"base": {
"prob_pct": round(base_prob * 100, 1),
"range_24h_low": base_low,
"range_24h_high": base_high,
"range_7d_low": current_price - 2 * atr,
"range_7d_high": current_price + 2 * atr,
"trigger": "Structure continuation without catalyst — oscillation between nearest S/R",
},
"bear": {
"prob_pct": round(bear_prob * 100, 1),
"target_24h": bear_24h,
"target_24h_pct": round(bear_pct, 2),
"target_7d": bear_7d,
"target_7d_pct": round(pct(bear_7d), 2),
"trigger": f"Close < {_fmt_price(s1 or bear_24h)} on 4H on expanding volume",
},
"ev_24h_pct": round(ev_24h, 2),
}
# ----------------------------------------------------------------------
# Phase 8 — Trade execution plan
# ----------------------------------------------------------------------
def build_trade_plan(signal: str, current_price: Optional[float], atr_4h: Optional[float],
vwap_4h: Optional[float], sr: Dict, final_score: float,
beta: Optional[float], size_haircut: float) -> Dict[str, Any]:
if not current_price:
return {"error": "no price"}
direction = "FLAT"
if signal in ("STRONG_BUY", "BUY", "WEAK_BUY"):
direction = "LONG"
elif signal in ("STRONG_SELL", "SELL", "WEAK_SELL"):
direction = "SHORT"
setup_quality = {
"STRONG_BUY": "A+", "BUY": "A", "WEAK_BUY": "B",
"NEUTRAL": "No Trade",
"WEAK_SELL": "B", "SELL": "A", "STRONG_SELL": "A+",
}.get(signal, "No Trade")
atr = atr_4h or (current_price * 0.02)
res = (sr or {}).get("strong_resistances") or []
sup = (sr or {}).get("strong_supports") or []
nearest_support = _num((sup[0] or {}).get("level")) if sup else (current_price - atr)
nearest_resistance = _num((res[0] or {}).get("level")) if res else (current_price + atr)
# Sanity-check VWAP: if it's more than 15% away from price (bad data / misaligned
# timeframe), fall back to current price.
ideal_entry = vwap_4h if (vwap_4h and abs(vwap_4h - current_price) / current_price < 0.15) else current_price
# When no tradable edge, emit blank tiers — do not print fake numbers.
if direction == "FLAT":
blank = {"entry_lower": None, "entry_upper": None, "entry_ideal": None,
"stop_loss": None, "sl_pct": None,
"tp1": None, "tp1_pct": None, "tp2": None, "tp2_pct": None,
"tp3": None, "tp3_pct": None,
"rr_tp1": 1.5, "rr_tp2": 2.5, "rr_tp3": 4.0,
"risk_per_unit": 0}
return {
"direction": "FLAT",
"setup_quality": setup_quality,
"conservative": dict(blank),
"moderate": dict(blank),
"aggressive": dict(blank),
"kelly": {"win_prob": "n/a", "avg_rr": "n/a",
"full_kelly_pct": "n/a", "half_kelly_pct": "n/a",
"half_kelly_adj_pct": "n/a"},
"position_size": {"capital_example_usdt": 10000.0, "risk_pct": 1.0,
"risk_usdt": 100.0, "position_usdt": 0,
"pct_of_capital": 0, "beta_haircut_applied": False},
"invalidation": {"level": None, "timeframe": "4H", "direction": "n/a"},
}
# Estimate slippage + fees for realistic R:R
vol_24h = _num(_g(sr, "total_volume_usd")) or 0
fee_pct = 0.10 # taker fee (Binance/MEXC)
slippage_pct = 0.05 if vol_24h > 50_000_000 else (0.10 if vol_24h > 10_000_000 else 0.30)
round_trip_cost_pct = (fee_pct + slippage_pct) * 2 # entry + exit
def build_tier(sl_mult: float, entry_offset_mult: float) -> Dict[str, Any]:
"""Build trade tier with differentiated entry zones per risk tolerance.
Conservative: deeper pullback entry (larger offset from market).
Aggressive: near-market entry.
"""
if direction == "LONG":
tier_entry = ideal_entry - entry_offset_mult * atr
sl = min(tier_entry - sl_mult * atr, (nearest_support or tier_entry) * 0.995)
risk = tier_entry - sl
tp1 = tier_entry + 1.5 * risk
tp2 = tier_entry + 2.5 * risk
tp3 = tier_entry + 4.0 * risk
elif direction == "SHORT":
tier_entry = ideal_entry + entry_offset_mult * atr
sl = max(tier_entry + sl_mult * atr, (nearest_resistance or tier_entry) * 1.005)
risk = sl - tier_entry
tp1 = tier_entry - 1.5 * risk
tp2 = tier_entry - 2.5 * risk
tp3 = tier_entry - 4.0 * risk
else:
tier_entry = ideal_entry
sl = ideal_entry
risk = atr
tp1 = tp2 = tp3 = ideal_entry
risk = max(risk, 1e-12)
# Effective R:R after fees and slippage
eff_risk = risk + (tier_entry * round_trip_cost_pct / 100)
eff_rr_tp1 = round(abs(tp1 - tier_entry) / eff_risk, 2) if eff_risk > 0 else 0
eff_rr_tp2 = round(abs(tp2 - tier_entry) / eff_risk, 2) if eff_risk > 0 else 0
return {
"entry_ideal": round(tier_entry, 8),
"entry_lower": round(tier_entry - 0.3 * atr, 8),
"entry_upper": round(tier_entry + 0.3 * atr, 8),
"stop_loss": round(sl, 8),
"sl_pct": round(abs(sl - tier_entry) / tier_entry * 100, 2),
"tp1": round(tp1, 8),
"tp1_pct": round((tp1 - tier_entry) / tier_entry * 100, 2),
"tp2": round(tp2, 8),
"tp2_pct": round((tp2 - tier_entry) / tier_entry * 100, 2),
"tp3": round(tp3, 8),
"tp3_pct": round((tp3 - tier_entry) / tier_entry * 100, 2),
"rr_tp1": 1.5,
"rr_tp2": 2.5,
"rr_tp3": 4.0,
"effective_rr_tp1_after_fees": eff_rr_tp1,
"effective_rr_tp2_after_fees": eff_rr_tp2,
"risk_per_unit": round(risk, 8),
"estimated_slippage_pct": slippage_pct,
"round_trip_cost_pct": round(round_trip_cost_pct, 3),
}
# Conservative: wait for deeper pullback (0.5 ATR offset), tight SL
# Moderate: near VWAP entry, standard SL
# Aggressive: market entry (0 offset), wide SL
conservative = build_tier(1.5, 0.5)
moderate = build_tier(2.0, 0.15)
aggressive = build_tier(2.5, 0.0)
# Kelly: score-to-probability mapping (UNCALIBRATED HEURISTIC)
# WARNING: This p is derived from composite score, not empirical win rate.
# Until backtested, treat as directional guidance only.
# Hard-cap at 1-2% risk regardless of Kelly output.
p = _clamp(0.5 + (final_score / 200.0), 0.10, 0.85) # narrower bounds than before
# Compute effective R:R from moderate tier (after fees)
b = moderate.get("effective_rr_tp2_after_fees") or 2.0
f_full = (p * b - (1 - p)) / b
f_full = max(0.0, f_full)
f_half = f_full * 0.5
# Apply beta haircut
f_half_adj = f_half * (1 - size_haircut)
# Hard cap: never risk more than 3% per trade regardless of Kelly
f_half_adj = min(f_half_adj, 0.03)
# Position size (example $10k capital, 1% risk)
capital = 10000.0
risk_pct = 0.01 if setup_quality in ('B', 'No Trade') else 0.02
risk_usdt = capital * risk_pct
risk_per_unit = moderate["risk_per_unit"] if moderate["risk_per_unit"] > 0 else atr
position_units = risk_usdt / risk_per_unit if risk_per_unit > 0 else 0
position_usdt = position_units * ideal_entry
# Cap to half-kelly % of capital
kelly_cap_usdt = capital * f_half_adj
if kelly_cap_usdt > 0:
position_usdt = min(position_usdt, kelly_cap_usdt)
invalidation_level = conservative["stop_loss"]
return {
"direction": direction,
"setup_quality": setup_quality,
"conservative": conservative,
"moderate": moderate,
"aggressive": aggressive,
"kelly": {
"win_prob": round(p * 100, 1),
"avg_rr": b,
"full_kelly_pct": round(f_full * 100, 2),
"half_kelly_pct": round(f_half * 100, 2),
"half_kelly_adj_pct": round(f_half_adj * 100, 2),
},
"position_size": {
"capital_example_usdt": capital,
"risk_pct": 1.0,
"risk_usdt": risk_usdt,
"position_usdt": round(position_usdt, 2),
"pct_of_capital": round(position_usdt / capital * 100, 2),
"beta_haircut_applied": size_haircut > 0,
},
"invalidation": {
"level": invalidation_level,
"timeframe": "4H",
"direction": "below" if direction == "LONG" else ("above" if direction == "SHORT" else "n/a"),
},
}
# ----------------------------------------------------------------------
# Phase 9 — Risk audit
# ----------------------------------------------------------------------
def risk_audit(report: Dict, smart: Dict, macro: Dict, mtf: Dict,
per_tf_ta: Dict, completeness_pct: float,
missing_sections: List[str]) -> Dict[str, Any]:
audit = {}
# 1. Crowding
f = smart.get("funding_rate_pct")
audit["funding_crowding"] = (
{"status": "WARNING", "detail": f"Funding {f:+.4f}% — leveraged longs overcrowded."}
if f is not None and f > 0.05 else {"status": "CLEAR"}
)
# 2. Liquidity
vol_24h = _num(_g(report, "metadata", "market_data", "total_volume", "usd"))
if vol_24h is None:
vol_24h = _num(_g(report, "metadata", "total_volume_usd"))
audit["liquidity"] = (
{"status": "WARNING", "detail": f"24h volume ${vol_24h:,.0f} < $5M — slippage risk."}
if vol_24h is not None and vol_24h < 5_000_000 else {"status": "CLEAR"}
)
# 3. Whale concentration
top10 = _num(_g(report, "top_holders", "top10_holders_pct"))
audit["whale_concentration"] = (
{"status": "WARNING", "detail": f"Top 10 wallets hold {top10:.1f}% of supply."}
if top10 is not None and top10 > 40 else {"status": "CLEAR"}
)
# 4. Token unlock
days = _num(_g(report, "upcoming_events", "days_until_next_event"))
audit["token_unlock"] = (
{"status": "WARNING", "detail": f"Major event in {int(days)}d."}
if days is not None and days <= 14 else {"status": "CLEAR"}
)
# 5. Beta
beta = macro.get("beta_vs_btc")
audit["beta"] = (
{"status": "WARNING", "detail": f"Beta {beta:.2f} — BTC exposure amplified."}
if beta is not None and beta > 2.0 else {"status": "CLEAR"}
)
# 6. MTF divergence
per_tf = mtf.get("per_tf", {})
scores = [v.get("score") for v in per_tf.values() if v.get("available")]
divergent = len(scores) >= 2 and (max(scores) > 25 and min(scores) < -25)
audit["mtf_divergence"] = (
{"status": "WARNING", "detail": "Timeframes disagree sharply."}
if divergent else {"status": "CLEAR"}
)
# 7. Volume confirmation (4H)
vol_4h = _num(_g(per_tf_ta.get("4h") or {}, "volume_vs_avg"))
audit["volume_confirmation"] = (
{"status": "UNCONFIRMED", "detail": f"4H volume {vol_4h:.2f}x avg — below average."}
if vol_4h is not None and vol_4h < 1.0 else {"status": "CONFIRMED"}
)
# 8. Data completeness
audit["data_completeness"] = (
{"status": "FULL"} if completeness_pct >= 95
else {"status": "PARTIAL", "detail": f"{completeness_pct:.0f}% — missing: {', '.join(missing_sections) or 'n/a'}"}
)
# Overall rating
warnings = sum(1 for k, v in audit.items() if v.get("status") in ("WARNING", "UNCONFIRMED", "PARTIAL"))
if warnings >= 4:
overall = "EXTREME"
elif warnings >= 3:
overall = "HIGH"
elif warnings >= 1:
overall = "MODERATE"
else:
overall = "LOW"
audit["overall_risk"] = overall
return audit
# ----------------------------------------------------------------------
# Narrative helpers — Wolf / Insider / Verdict prose
# ----------------------------------------------------------------------
def wolf_read(report: Dict, ta_4h: Dict, current_price: Optional[float]) -> str:
ob = report.get("order_book") or {}
rt = report.get("trade_flow") or {}
imb = _num(ob.get("imbalance_ratio"))
bwall = _num(ob.get("bid_wall_at"))
awall = _num(ob.get("ask_wall_at"))
buy_pct = _num(rt.get("buy_volume_pct"))
sell_pct = _num(rt.get("sell_volume_pct"))
accel = _num(rt.get("trade_acceleration_score"))
vwap = _num(ta_4h.get("vwap"))
pvw = ta_4h.get("price_vs_vwap")
parts = []
if imb is not None:
if imb > 1.3:
parts.append(f"Bid depth outweighs asks {imb:.2f}× — buyers absorbing supply, not chasing.")
elif imb < 0.77:
parts.append(f"Ask depth dominates {1/imb:.2f}× — sellers stacked, rallies likely sold.")
else:
parts.append(f"Book near balance ({imb:.2f}) — no side has clear commitment.")
if awall and current_price:
parts.append(f"Visible ask wall at {_fmt_price(awall)} acts as magnetic resistance above.")
if bwall and current_price:
parts.append(f"Bid wall at {_fmt_price(bwall)} is the line the market must hold.")
if buy_pct is not None and sell_pct is not None:
if buy_pct > 60:
parts.append(f"Tape prints {buy_pct:.0f}% aggressive buys — flow is directional up.")
elif sell_pct > 60: