Spaces:
Sleeping
Sleeping
Naufal Arhab commited on
Commit ·
3cb5902
1
Parent(s): b445d0e
feat(ai): expand Damian quantitative telemetry with lead-lag, funding countdown, 24h extremes, and whale block trades
Browse files- backend/engine/signal_engine.py +363 -7
- backend/routers/ai.py +86 -19
- frontend/src/components/signals/AIAnalysisPanel.tsx +32 -0
- frontend/src/pages/AITerminal.tsx +32 -0
- frontend/src/types/index.ts +13 -0
- tests/test_calculations.py +82 -0
backend/engine/signal_engine.py
CHANGED
|
@@ -11,6 +11,7 @@ Flow:
|
|
| 11 |
"""
|
| 12 |
|
| 13 |
import logging
|
|
|
|
| 14 |
from datetime import datetime, timezone
|
| 15 |
from typing import Any
|
| 16 |
|
|
@@ -677,6 +678,342 @@ def _compute_trade_plan(
|
|
| 677 |
}
|
| 678 |
|
| 679 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 680 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 681 |
# Main engine
|
| 682 |
# ─────────────────────────────────────────────────────────────────────────────
|
|
@@ -718,14 +1055,21 @@ class SignalEngine:
|
|
| 718 |
# Institutional Alpha #2: Hyperliquid On-Chain DEX Whale Flow
|
| 719 |
hl_signal = _compute_hyperliquid_signal(hyperliquid)
|
| 720 |
|
| 721 |
-
# CVD
|
| 722 |
-
|
| 723 |
if binance and binance.get("trades"):
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 729 |
cvd_signal = _compute_cvd(trades)
|
| 730 |
|
| 731 |
# Institutional Alpha #3: Triangulation Consensus across Binance + Bybit + OKX
|
|
@@ -832,6 +1176,7 @@ class SignalEngine:
|
|
| 832 |
ls = exch.get("ls_ratio_data") or {}
|
| 833 |
return {
|
| 834 |
"funding_rate": fr.get("funding_rate"),
|
|
|
|
| 835 |
"oi": oi.get("open_interest"),
|
| 836 |
"mark_price": mp.get("mark_price"),
|
| 837 |
"index_price": mp.get("index_price"),
|
|
@@ -850,6 +1195,7 @@ class SignalEngine:
|
|
| 850 |
if hyperliquid:
|
| 851 |
exchange_data["hyperliquid"] = {
|
| 852 |
"funding_rate": hyperliquid.get("funding_rate"),
|
|
|
|
| 853 |
"oi": hyperliquid.get("open_interest"),
|
| 854 |
"mark_price": hyperliquid.get("mark_price"),
|
| 855 |
"index_price": hyperliquid.get("oracle_price"),
|
|
@@ -898,6 +1244,12 @@ class SignalEngine:
|
|
| 898 |
plan["trade_levels"]["is_perp_only"] = not has_spot
|
| 899 |
plan["trade_levels"]["safety_label"] = "AMAN (Ada Spot)" if has_spot else "RAWAN (Perp Only)"
|
| 900 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 901 |
# ── 8. Assemble final output ───────────────────────────────────────
|
| 902 |
now = datetime.now(timezone.utc).isoformat()
|
| 903 |
|
|
@@ -915,6 +1267,10 @@ class SignalEngine:
|
|
| 915 |
"trade_levels": plan["trade_levels"],
|
| 916 |
"anticipation": predictive_data["anticipation"],
|
| 917 |
"predictive": predictive_data,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 918 |
"active_timeframe": mtf_result["active_timeframe"],
|
| 919 |
"market_condition": mtf_result["market_condition"],
|
| 920 |
"signals": {
|
|
|
|
| 11 |
"""
|
| 12 |
|
| 13 |
import logging
|
| 14 |
+
import time
|
| 15 |
from datetime import datetime, timezone
|
| 16 |
from typing import Any
|
| 17 |
|
|
|
|
| 678 |
}
|
| 679 |
|
| 680 |
|
| 681 |
+
def _compute_lead_lag(exchange_data: dict, mark_price: float) -> dict[str, Any]:
|
| 682 |
+
"""
|
| 683 |
+
Lead-Lag Price Disparity across Binance, Bybit, OKX, and Hyperliquid.
|
| 684 |
+
Identifies which exchange is leading price discovery and the cross-venue spread in basis points.
|
| 685 |
+
"""
|
| 686 |
+
venue_prices: dict[str, float] = {}
|
| 687 |
+
for exch_name, data in exchange_data.items():
|
| 688 |
+
if not data:
|
| 689 |
+
continue
|
| 690 |
+
px = data.get("mark_price")
|
| 691 |
+
if px and isinstance(px, (int, float)) and px > 0:
|
| 692 |
+
venue_prices[exch_name] = float(px)
|
| 693 |
+
|
| 694 |
+
if not venue_prices and mark_price > 0:
|
| 695 |
+
venue_prices["benchmark"] = mark_price
|
| 696 |
+
|
| 697 |
+
if len(venue_prices) < 2:
|
| 698 |
+
return {
|
| 699 |
+
"venue_prices": venue_prices,
|
| 700 |
+
"max_spread_usd": 0.0,
|
| 701 |
+
"max_spread_bps": 0.0,
|
| 702 |
+
"max_spread_pct": 0.0,
|
| 703 |
+
"leading_exchange": None,
|
| 704 |
+
"lagging_exchange": None,
|
| 705 |
+
"lead_lag_summary": "Single venue / data tidak cukup untuk perbandingan lead-lag",
|
| 706 |
+
"spread_table": [],
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
highest_exch = max(venue_prices, key=venue_prices.get)
|
| 710 |
+
lowest_exch = min(venue_prices, key=venue_prices.get)
|
| 711 |
+
highest_px = venue_prices[highest_exch]
|
| 712 |
+
lowest_px = venue_prices[lowest_exch]
|
| 713 |
+
|
| 714 |
+
spread_usd = highest_px - lowest_px
|
| 715 |
+
spread_pct = (spread_usd / lowest_px * 100.0) if lowest_px > 0 else 0.0
|
| 716 |
+
spread_bps = spread_pct * 100.0 # 1% = 100 bps
|
| 717 |
+
|
| 718 |
+
avg_px = sum(venue_prices.values()) / len(venue_prices)
|
| 719 |
+
spread_table = []
|
| 720 |
+
for exch, px in venue_prices.items():
|
| 721 |
+
diff_bps = ((px - avg_px) / avg_px * 10000.0) if avg_px > 0 else 0.0
|
| 722 |
+
spread_table.append({
|
| 723 |
+
"exchange": exch,
|
| 724 |
+
"price": px,
|
| 725 |
+
"diff_from_avg_bps": round(diff_bps, 2),
|
| 726 |
+
"is_lead_bullish": exch == highest_exch,
|
| 727 |
+
"is_lead_bearish": exch == lowest_exch,
|
| 728 |
+
})
|
| 729 |
+
|
| 730 |
+
if spread_bps >= 15.0:
|
| 731 |
+
summary = f"Disparitas Tinggi: {highest_exch.upper()} memimpin di atas ({spread_bps:+.1f} bps vs {lowest_exch.upper()}). Potensi momentum agresif / arbitrase lag!"
|
| 732 |
+
elif spread_bps >= 5.0:
|
| 733 |
+
summary = f"Disparitas Moderat: {highest_exch.upper()} premium {spread_bps:+.1f} bps di atas {lowest_exch.upper()}."
|
| 734 |
+
else:
|
| 735 |
+
summary = f"Sangat Ketat: Spread antar bursa hanya {spread_bps:.1f} bps (konsensus harga seragam & likuiditas stabil)."
|
| 736 |
+
|
| 737 |
+
return {
|
| 738 |
+
"venue_prices": venue_prices,
|
| 739 |
+
"max_spread_usd": round(spread_usd, 8),
|
| 740 |
+
"max_spread_bps": round(spread_bps, 2),
|
| 741 |
+
"max_spread_pct": round(spread_pct, 4),
|
| 742 |
+
"leading_exchange": highest_exch,
|
| 743 |
+
"lagging_exchange": lowest_exch,
|
| 744 |
+
"lead_lag_summary": summary,
|
| 745 |
+
"spread_table": spread_table,
|
| 746 |
+
}
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def _compute_funding_settlement(exchange_data: dict) -> dict[str, Any]:
|
| 750 |
+
"""
|
| 751 |
+
Funding Settlement Countdown and dynamic fee risk estimation.
|
| 752 |
+
Calculates time remaining to next settlement across CEXes (8h) and Hyperliquid (1h).
|
| 753 |
+
"""
|
| 754 |
+
now_ts = time.time()
|
| 755 |
+
now_ms = now_ts * 1000.0
|
| 756 |
+
|
| 757 |
+
next_settlements = {}
|
| 758 |
+
nearest_diff_seconds = None
|
| 759 |
+
nearest_venue = None
|
| 760 |
+
|
| 761 |
+
for exch_name, data in exchange_data.items():
|
| 762 |
+
if not data:
|
| 763 |
+
continue
|
| 764 |
+
nft = data.get("next_funding_time")
|
| 765 |
+
|
| 766 |
+
if exch_name == "hyperliquid" or not nft:
|
| 767 |
+
if exch_name == "hyperliquid":
|
| 768 |
+
next_hour_s = (int(now_ts // 3600) + 1) * 3600
|
| 769 |
+
diff_s = next_hour_s - now_ts
|
| 770 |
+
m = int(diff_s // 60)
|
| 771 |
+
next_settlements[exch_name] = {
|
| 772 |
+
"countdown_seconds": int(diff_s),
|
| 773 |
+
"countdown_str": f"{m}m",
|
| 774 |
+
"cycle": "1H",
|
| 775 |
+
}
|
| 776 |
+
if nearest_diff_seconds is None or diff_s < nearest_diff_seconds:
|
| 777 |
+
nearest_diff_seconds = diff_s
|
| 778 |
+
nearest_venue = exch_name
|
| 779 |
+
continue
|
| 780 |
+
|
| 781 |
+
if nft:
|
| 782 |
+
try:
|
| 783 |
+
if isinstance(nft, (int, float)):
|
| 784 |
+
nft_ms = float(nft)
|
| 785 |
+
elif isinstance(nft, str):
|
| 786 |
+
if nft.isdigit():
|
| 787 |
+
nft_ms = float(nft)
|
| 788 |
+
else:
|
| 789 |
+
from datetime import datetime as dt_cls
|
| 790 |
+
dt = dt_cls.fromisoformat(nft.replace("Z", "+00:00"))
|
| 791 |
+
nft_ms = dt.timestamp() * 1000.0
|
| 792 |
+
else:
|
| 793 |
+
nft_ms = 0.0
|
| 794 |
+
|
| 795 |
+
if 0 < nft_ms < 10_000_000_000:
|
| 796 |
+
nft_ms *= 1000.0
|
| 797 |
+
|
| 798 |
+
diff_s = (nft_ms - now_ms) / 1000.0
|
| 799 |
+
if diff_s > 0:
|
| 800 |
+
h = int(diff_s // 3600)
|
| 801 |
+
m = int((diff_s % 3600) // 60)
|
| 802 |
+
cd_str = f"{h}h {m}m" if h > 0 else f"{m}m"
|
| 803 |
+
next_settlements[exch_name] = {
|
| 804 |
+
"countdown_seconds": int(diff_s),
|
| 805 |
+
"countdown_str": cd_str,
|
| 806 |
+
"cycle": "8H",
|
| 807 |
+
}
|
| 808 |
+
if nearest_diff_seconds is None or diff_s < nearest_diff_seconds:
|
| 809 |
+
nearest_diff_seconds = diff_s
|
| 810 |
+
nearest_venue = exch_name
|
| 811 |
+
except Exception:
|
| 812 |
+
pass
|
| 813 |
+
|
| 814 |
+
if nearest_diff_seconds is not None and nearest_diff_seconds > 0:
|
| 815 |
+
h = int(nearest_diff_seconds // 3600)
|
| 816 |
+
m = int((nearest_diff_seconds % 3600) // 60)
|
| 817 |
+
overall_countdown = f"{h}h {m}m" if h > 0 else f"{m}m"
|
| 818 |
+
is_imminent = nearest_diff_seconds <= 2700 # within 45 minutes
|
| 819 |
+
if is_imminent:
|
| 820 |
+
risk_label = f"⚠️ SETTLEMENT DALAM {overall_countdown} ({nearest_venue.upper()}): Waspada volatilitas rebalancing funding fee & wick squeeze!"
|
| 821 |
+
else:
|
| 822 |
+
risk_label = f"Settlement berikutnya dalam {overall_countdown} ({nearest_venue.upper()}). Risiko volatilitas sesaat rendah."
|
| 823 |
+
else:
|
| 824 |
+
overall_countdown = "N/A"
|
| 825 |
+
is_imminent = False
|
| 826 |
+
risk_label = "Jadwal settlement standar (siklus 8 jam / 1 jam Hyperliquid)."
|
| 827 |
+
|
| 828 |
+
return {
|
| 829 |
+
"countdown_str": overall_countdown,
|
| 830 |
+
"is_settlement_imminent": is_imminent,
|
| 831 |
+
"risk_label": risk_label,
|
| 832 |
+
"venues": next_settlements,
|
| 833 |
+
}
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
def _compute_price_extremes_24h(merged_ohlcv: dict, mark_price: float) -> dict[str, Any]:
|
| 837 |
+
"""
|
| 838 |
+
Computes rolling 24-hour extremes (High, Low, Range, and % distance).
|
| 839 |
+
Uses the last 24 candles of 1h (or 1d candle if 1h insufficient).
|
| 840 |
+
"""
|
| 841 |
+
candles_1h = merged_ohlcv.get("1h", []) if merged_ohlcv else []
|
| 842 |
+
highs = []
|
| 843 |
+
lows = []
|
| 844 |
+
|
| 845 |
+
if candles_1h and len(candles_1h) >= 1:
|
| 846 |
+
recent_bars = candles_1h[-24:]
|
| 847 |
+
for b in recent_bars:
|
| 848 |
+
h = b.get("high")
|
| 849 |
+
l = b.get("low")
|
| 850 |
+
if h is not None and float(h) > 0:
|
| 851 |
+
highs.append(float(h))
|
| 852 |
+
if l is not None and float(l) > 0:
|
| 853 |
+
lows.append(float(l))
|
| 854 |
+
|
| 855 |
+
if (not highs or not lows) and merged_ohlcv and merged_ohlcv.get("1d"):
|
| 856 |
+
c1d = merged_ohlcv["1d"][-1]
|
| 857 |
+
if c1d.get("high"): highs.append(float(c1d["high"]))
|
| 858 |
+
if c1d.get("low"): lows.append(float(c1d["low"]))
|
| 859 |
+
|
| 860 |
+
if not highs or not lows or mark_price <= 0:
|
| 861 |
+
return {
|
| 862 |
+
"high_24h": mark_price,
|
| 863 |
+
"low_24h": mark_price,
|
| 864 |
+
"range_usd": 0.0,
|
| 865 |
+
"range_pct": 0.0,
|
| 866 |
+
"dist_to_high_pct": 0.0,
|
| 867 |
+
"dist_to_low_pct": 0.0,
|
| 868 |
+
"range_position_pct": 50.0,
|
| 869 |
+
"zone_label": "Equilibrium",
|
| 870 |
+
}
|
| 871 |
+
|
| 872 |
+
high_24h = max(highs)
|
| 873 |
+
low_24h = min(lows)
|
| 874 |
+
range_usd = high_24h - low_24h
|
| 875 |
+
range_pct = (range_usd / low_24h * 100.0) if low_24h > 0 else 0.0
|
| 876 |
+
|
| 877 |
+
dist_to_high_pct = ((high_24h - mark_price) / mark_price * 100.0) if mark_price > 0 else 0.0
|
| 878 |
+
dist_to_low_pct = ((mark_price - low_24h) / mark_price * 100.0) if mark_price > 0 else 0.0
|
| 879 |
+
|
| 880 |
+
if range_usd > 0:
|
| 881 |
+
pos_pct = max(0.0, min(100.0, (mark_price - low_24h) / range_usd * 100.0))
|
| 882 |
+
else:
|
| 883 |
+
pos_pct = 50.0
|
| 884 |
+
|
| 885 |
+
if pos_pct >= 80.0:
|
| 886 |
+
zone = f"DEKAT 24H RESISTANCE/HIGH ({pos_pct:.1f}% rentang) — Waspada rejection atau fakeout wick hunt"
|
| 887 |
+
elif pos_pct <= 20.0:
|
| 888 |
+
zone = f"DEKAT 24H SUPPORT/LOW ({pos_pct:.1f}% rentang) — Area diskon / potensi sweep likuidasi buyer"
|
| 889 |
+
elif 40.0 <= pos_pct <= 60.0:
|
| 890 |
+
zone = f"MID-RANGE EQUILIBRIUM ({pos_pct:.1f}% rentang) — Menunggu dorongan momentum"
|
| 891 |
+
elif pos_pct > 60.0:
|
| 892 |
+
zone = f"UPPER RANGE EXPANSION ({pos_pct:.1f}% rentang) — Bullish momentum"
|
| 893 |
+
else:
|
| 894 |
+
zone = f"LOWER RANGE EXPANSION ({pos_pct:.1f}% rentang) — Bearish pressure"
|
| 895 |
+
|
| 896 |
+
return {
|
| 897 |
+
"high_24h": round(high_24h, 8),
|
| 898 |
+
"low_24h": round(low_24h, 8),
|
| 899 |
+
"range_usd": round(range_usd, 8),
|
| 900 |
+
"range_pct": round(range_pct, 2),
|
| 901 |
+
"dist_to_high_pct": round(dist_to_high_pct, 2),
|
| 902 |
+
"dist_to_low_pct": round(dist_to_low_pct, 2),
|
| 903 |
+
"range_position_pct": round(pos_pct, 1),
|
| 904 |
+
"zone_label": zone,
|
| 905 |
+
}
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
def _compute_whale_order_flow(trades: list[dict], mark_price: float) -> dict[str, Any]:
|
| 909 |
+
"""
|
| 910 |
+
Institutional Order Flow & Whale Block Trades Analysis.
|
| 911 |
+
Analyzes aggressive market taker buy/sell volume and large block orders.
|
| 912 |
+
"""
|
| 913 |
+
if not trades or mark_price <= 0:
|
| 914 |
+
return {
|
| 915 |
+
"taker_buy_vol_usd": 0.0,
|
| 916 |
+
"taker_sell_vol_usd": 0.0,
|
| 917 |
+
"total_vol_usd": 0.0,
|
| 918 |
+
"taker_buy_pct": 50.0,
|
| 919 |
+
"taker_ratio": 1.0,
|
| 920 |
+
"whale_buy_count": 0,
|
| 921 |
+
"whale_sell_count": 0,
|
| 922 |
+
"whale_buy_vol_usd": 0.0,
|
| 923 |
+
"whale_sell_vol_usd": 0.0,
|
| 924 |
+
"largest_trade_usd": 0.0,
|
| 925 |
+
"largest_trade_side": "NONE",
|
| 926 |
+
"flow_verdict": "Order Flow Agregat Seimbang (Belum Ada Data Trades)",
|
| 927 |
+
}
|
| 928 |
+
|
| 929 |
+
taker_buy_vol = 0.0
|
| 930 |
+
taker_sell_vol = 0.0
|
| 931 |
+
parsed_trades = []
|
| 932 |
+
|
| 933 |
+
for t in trades:
|
| 934 |
+
try:
|
| 935 |
+
px = float(t.get("price", 0.0))
|
| 936 |
+
qty = float(t.get("qty", 0.0))
|
| 937 |
+
if px <= 0 or qty <= 0:
|
| 938 |
+
continue
|
| 939 |
+
usd_val = px * qty
|
| 940 |
+
is_sell_taker = bool(t.get("is_buyer_maker", False))
|
| 941 |
+
parsed_trades.append((usd_val, is_sell_taker))
|
| 942 |
+
if is_sell_taker:
|
| 943 |
+
taker_sell_vol += usd_val
|
| 944 |
+
else:
|
| 945 |
+
taker_buy_vol += usd_val
|
| 946 |
+
except Exception:
|
| 947 |
+
continue
|
| 948 |
+
|
| 949 |
+
if not parsed_trades:
|
| 950 |
+
return {
|
| 951 |
+
"taker_buy_vol_usd": 0.0,
|
| 952 |
+
"taker_sell_vol_usd": 0.0,
|
| 953 |
+
"total_vol_usd": 0.0,
|
| 954 |
+
"taker_buy_pct": 50.0,
|
| 955 |
+
"taker_ratio": 1.0,
|
| 956 |
+
"whale_buy_count": 0,
|
| 957 |
+
"whale_sell_count": 0,
|
| 958 |
+
"whale_buy_vol_usd": 0.0,
|
| 959 |
+
"whale_sell_vol_usd": 0.0,
|
| 960 |
+
"largest_trade_usd": 0.0,
|
| 961 |
+
"largest_trade_side": "NONE",
|
| 962 |
+
"flow_verdict": "Order Flow Agregat Seimbang",
|
| 963 |
+
}
|
| 964 |
+
|
| 965 |
+
total_vol = taker_buy_vol + taker_sell_vol
|
| 966 |
+
buy_pct = (taker_buy_vol / total_vol * 100.0) if total_vol > 0 else 50.0
|
| 967 |
+
taker_ratio = (taker_buy_vol / taker_sell_vol) if taker_sell_vol > 0 else 1.0
|
| 968 |
+
|
| 969 |
+
# Dynamic Whale Threshold: $25,000 for majors/mid-caps, or top tier for alts
|
| 970 |
+
threshold = 25000.0
|
| 971 |
+
whale_buys = [v for v, is_sell in parsed_trades if (not is_sell) and v >= threshold]
|
| 972 |
+
whale_sells = [v for v, is_sell in parsed_trades if is_sell and v >= threshold]
|
| 973 |
+
|
| 974 |
+
# Fallback to $10k if coin is a smaller cap alt
|
| 975 |
+
if not whale_buys and not whale_sells:
|
| 976 |
+
threshold = 10000.0
|
| 977 |
+
whale_buys = [v for v, is_sell in parsed_trades if (not is_sell) and v >= threshold]
|
| 978 |
+
whale_sells = [v for v, is_sell in parsed_trades if is_sell and v >= threshold]
|
| 979 |
+
|
| 980 |
+
whale_buy_vol = sum(whale_buys)
|
| 981 |
+
whale_sell_vol = sum(whale_sells)
|
| 982 |
+
|
| 983 |
+
largest_val, largest_is_sell = max(parsed_trades, key=lambda x: x[0])
|
| 984 |
+
largest_side = "SELL" if largest_is_sell else "BUY"
|
| 985 |
+
|
| 986 |
+
if len(whale_buys) > 0 and len(whale_sells) == 0:
|
| 987 |
+
verdict = f"Paus Agresif Sisi Beli: {len(whale_buys)} block buy (${whale_buy_vol:,.0f}) tanpa block sell tandingan!"
|
| 988 |
+
elif len(whale_sells) > 0 and len(whale_buys) == 0:
|
| 989 |
+
verdict = f"Paus Agresif Sisi Jual: {len(whale_sells)} block sell (${whale_sell_vol:,.0f}) tanpa block buy tandingan!"
|
| 990 |
+
elif whale_buy_vol > whale_sell_vol * 1.5:
|
| 991 |
+
verdict = f"Dominasi Block Buy: Whale buy ${whale_buy_vol:,.0f} ({len(whale_buys)} orders) vs sell ${whale_sell_vol:,.0f} ({len(whale_sells)} orders)."
|
| 992 |
+
elif whale_sell_vol > whale_buy_vol * 1.5:
|
| 993 |
+
verdict = f"Dominasi Block Sell: Whale sell ${whale_sell_vol:,.0f} ({len(whale_sells)} orders) vs buy ${whale_buy_vol:,.0f} ({len(whale_buys)} orders)."
|
| 994 |
+
elif buy_pct >= 58.0:
|
| 995 |
+
verdict = f"Taker Buy Dominan: {buy_pct:.1f}% volume taker agresif beli (Rasio {taker_ratio:.2f}x)."
|
| 996 |
+
elif buy_pct <= 42.0:
|
| 997 |
+
verdict = f"Taker Sell Dominan: {100.0 - buy_pct:.1f}% volume taker agresif jual (Rasio {taker_ratio:.2f}x)."
|
| 998 |
+
else:
|
| 999 |
+
verdict = f"Order Flow Seimbang: Taker buy {buy_pct:.1f}% vs sell {100.0 - buy_pct:.1f}%."
|
| 1000 |
+
|
| 1001 |
+
return {
|
| 1002 |
+
"taker_buy_vol_usd": round(taker_buy_vol, 2),
|
| 1003 |
+
"taker_sell_vol_usd": round(taker_sell_vol, 2),
|
| 1004 |
+
"total_vol_usd": round(total_vol, 2),
|
| 1005 |
+
"taker_buy_pct": round(buy_pct, 1),
|
| 1006 |
+
"taker_ratio": round(taker_ratio, 2),
|
| 1007 |
+
"whale_buy_count": len(whale_buys),
|
| 1008 |
+
"whale_sell_count": len(whale_sells),
|
| 1009 |
+
"whale_buy_vol_usd": round(whale_buy_vol, 2),
|
| 1010 |
+
"whale_sell_vol_usd": round(whale_sell_vol, 2),
|
| 1011 |
+
"largest_trade_usd": round(largest_val, 2),
|
| 1012 |
+
"largest_trade_side": largest_side,
|
| 1013 |
+
"flow_verdict": verdict,
|
| 1014 |
+
}
|
| 1015 |
+
|
| 1016 |
+
|
| 1017 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 1018 |
# Main engine
|
| 1019 |
# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
| 1055 |
# Institutional Alpha #2: Hyperliquid On-Chain DEX Whale Flow
|
| 1056 |
hl_signal = _compute_hyperliquid_signal(hyperliquid)
|
| 1057 |
|
| 1058 |
+
# CVD & Whale Order Flow: aggregate trades across Binance, Bybit, and OKX
|
| 1059 |
+
all_trades = []
|
| 1060 |
if binance and binance.get("trades"):
|
| 1061 |
+
all_trades.extend(binance["trades"])
|
| 1062 |
+
if bybit and bybit.get("trades"):
|
| 1063 |
+
all_trades.extend(bybit["trades"])
|
| 1064 |
+
if okx and okx.get("trades"):
|
| 1065 |
+
all_trades.extend(okx["trades"])
|
| 1066 |
+
|
| 1067 |
+
trades = all_trades if all_trades else (
|
| 1068 |
+
(binance.get("trades") if binance else None)
|
| 1069 |
+
or (bybit.get("trades") if bybit else None)
|
| 1070 |
+
or (okx.get("trades") if okx else None)
|
| 1071 |
+
or []
|
| 1072 |
+
)
|
| 1073 |
cvd_signal = _compute_cvd(trades)
|
| 1074 |
|
| 1075 |
# Institutional Alpha #3: Triangulation Consensus across Binance + Bybit + OKX
|
|
|
|
| 1176 |
ls = exch.get("ls_ratio_data") or {}
|
| 1177 |
return {
|
| 1178 |
"funding_rate": fr.get("funding_rate"),
|
| 1179 |
+
"next_funding_time": fr.get("next_funding_time"),
|
| 1180 |
"oi": oi.get("open_interest"),
|
| 1181 |
"mark_price": mp.get("mark_price"),
|
| 1182 |
"index_price": mp.get("index_price"),
|
|
|
|
| 1195 |
if hyperliquid:
|
| 1196 |
exchange_data["hyperliquid"] = {
|
| 1197 |
"funding_rate": hyperliquid.get("funding_rate"),
|
| 1198 |
+
"next_funding_time": int(((time.time() // 3600) + 1) * 3600 * 1000),
|
| 1199 |
"oi": hyperliquid.get("open_interest"),
|
| 1200 |
"mark_price": hyperliquid.get("mark_price"),
|
| 1201 |
"index_price": hyperliquid.get("oracle_price"),
|
|
|
|
| 1244 |
plan["trade_levels"]["is_perp_only"] = not has_spot
|
| 1245 |
plan["trade_levels"]["safety_label"] = "AMAN (Ada Spot)" if has_spot else "RAWAN (Perp Only)"
|
| 1246 |
|
| 1247 |
+
# ── 7.5 Institutional Microstructure, Lead-Lag & Order Flow ───────
|
| 1248 |
+
lead_lag_data = _compute_lead_lag(exchange_data, mark_price)
|
| 1249 |
+
settlement_data = _compute_funding_settlement(exchange_data)
|
| 1250 |
+
extremes_data = _compute_price_extremes_24h(merged_ohlcv, mark_price)
|
| 1251 |
+
whale_flow_data = _compute_whale_order_flow(trades, mark_price)
|
| 1252 |
+
|
| 1253 |
# ── 8. Assemble final output ───────────────────────────────────────
|
| 1254 |
now = datetime.now(timezone.utc).isoformat()
|
| 1255 |
|
|
|
|
| 1267 |
"trade_levels": plan["trade_levels"],
|
| 1268 |
"anticipation": predictive_data["anticipation"],
|
| 1269 |
"predictive": predictive_data,
|
| 1270 |
+
"lead_lag": lead_lag_data,
|
| 1271 |
+
"funding_settlement": settlement_data,
|
| 1272 |
+
"price_extremes": extremes_data,
|
| 1273 |
+
"whale_flow": whale_flow_data,
|
| 1274 |
"active_timeframe": mtf_result["active_timeframe"],
|
| 1275 |
"market_condition": mtf_result["market_condition"],
|
| 1276 |
"signals": {
|
backend/routers/ai.py
CHANGED
|
@@ -17,6 +17,12 @@ from pydantic import BaseModel
|
|
| 17 |
|
| 18 |
from database.db import async_get_latest_signal, async_get_latest_snapshot
|
| 19 |
from engine.doh_resolver import enable_doh_bypass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
enable_doh_bypass()
|
| 22 |
|
|
@@ -166,6 +172,42 @@ def _build_ai_prompt(
|
|
| 166 |
if v is None: return "N/A"
|
| 167 |
return f"{v * 100:+.4f}%"
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
# 1. Total Aggregated Open Interest across all venues
|
| 170 |
total_oi_usd = 0.0
|
| 171 |
venue_oi_str_list = []
|
|
@@ -349,41 +391,52 @@ Berikut adalah Aturan Pengaman Emas (Golden Safeguards) yang WAJIB kamu terapkan
|
|
| 349 |
prompt = f"""Role: Damian — Senior Institutional Crypto Derivatives Quantitative Strategist.
|
| 350 |
Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presisi kuantitatif, dan tanpa basa-basi pembuka/penutup.
|
| 351 |
|
| 352 |
-
=== 📊 DATA LIVE
|
| 353 |
-
1. KONSENSUS ARAH &
|
| 354 |
• Sinyal Sistem: {direction} | Conviction Score: {conviction}/10 | Konsistensi Streak: {streak_count} Siklus Berturut-turut ({streak_dir})
|
| 355 |
• Confluence Consensus: {len(bullish_signals)} Bullish vs {len(bearish_signals)} Bearish vs {len(neutral_signals)} Netral ({confluence_pct}% Kesepakatan)
|
| 356 |
• Sinyal Pendukung: {', '.join(bullish_signals) if bullish_signals else 'Tidak ada'}
|
| 357 |
• Sinyal Menentang: {', '.join(bearish_signals) if bearish_signals else 'Tidak ada'}
|
| 358 |
|
| 359 |
-
2. HARGA,
|
| 360 |
-
• Mark Price: {_fmt_px(mark_price)} | Index Price: {_fmt_px(index_price)} | Basis Spread: {div_pct:+.3f}%
|
| 361 |
-
•
|
|
|
|
| 362 |
• Total Open Interest Agregat (4 Bursa): {total_oi_str} ({venue_oi_breakdown})
|
| 363 |
• Status Pasar: {spot_status_str}
|
| 364 |
|
| 365 |
-
3.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
• Rata-rata Funding Rate 8H: {avg_fr_8h_pct:+.4f}% | Annualized APR: {annualized_apr_pct:+.2f}% APR
|
|
|
|
| 367 |
• Carry Arbitrage Impact: {carry_impact}
|
| 368 |
• Breakdown Bursa: Binance: {binance_fr} ({binance_ls}) | Bybit: {bybit_fr} ({bybit_ls}) | OKX: {okx_fr} ({okx_ls}) | Hyperliquid DEX: {hl_fr}
|
| 369 |
|
| 370 |
-
|
| 371 |
• Spot CVD: {spot_cvd} | Futures CVD: {fut_cvd} -> Status Aliran: {cvd_label}
|
|
|
|
|
|
|
|
|
|
| 372 |
• Hyperliquid DEX Whale Flow: {hl_label} (Basis Mark-Oracle: {hl_basis:+.3f}%)
|
| 373 |
• Open Interest Divergence: {oi_div_str}
|
| 374 |
|
| 375 |
-
|
| 376 |
• Struktur MTF: 1D: {struct_map.get('1d', 'unknown').upper()} | 4H: {struct_map.get('4h', 'unknown').upper()} | 1H: {struct_map.get('1h', 'unknown').upper()} | 15M: {struct_map.get('15m', 'unknown').upper()} (Active TF: {active_tf.upper()})
|
| 377 |
• Volatility Squeeze: {squeeze_intensity} (Compression Ratio: {compression_ratio:.2f})
|
| 378 |
• Kedalaman Orderbook (Top 20 Depth): ${bid_depth:,.0f} Bids vs ${ask_depth:,.0f} Asks (Rasio: {depth_ratio:.2f}x) -> {resting_pressure}
|
| 379 |
|
| 380 |
-
|
| 381 |
• Upper Short Liquidation Magnet: {upper_mag} ({dist_up:+.2f}%)
|
| 382 |
• Lower Long Liquidation Magnet: {lower_mag} ({dist_down:+.2f}%)
|
| 383 |
• Target Prediktif Sistem: {pred_target_str} ({target_type}) | Jarak: {target_dist_pct:+.2f}%
|
| 384 |
• Antisipasi Pergerakan: {anticipation_text}
|
| 385 |
|
| 386 |
-
|
| 387 |
• Rezim Pasar Global: {regime_text}
|
| 388 |
• Keselarasan Tren: {alignment_text}
|
| 389 |
• Status Manipulasi Harga: {fake_status_str}
|
|
@@ -397,31 +450,32 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi
|
|
| 397 |
2. DILARANG MEMBERIKAN ANALISA MENGAMBANG ("bisa naik atau turun"). Tetapkan 1 BIAS terkuat yang paling didukung data kuantitatif bursa.
|
| 398 |
3. HUKUM CVD & LEVERAGE TRAP: Jika Futures CVD naik tapi Spot CVD turun/negatif, ini adalah LEVERAGE TRAP (Retail beli futures, Spot buang barang). DILARANG menyarankan Long mengejar pucuk!
|
| 399 |
4. ATURAN INVALIDASI KRITIS: Syarat pembatalan setup WAJIB berbasis penutupan candle (misal: "Batal jika candle 1H ditutup di bawah $X"), BUKAN sekadar sengatan jarum wick touch.
|
| 400 |
-
5.
|
|
|
|
| 401 |
|
| 402 |
=== 📝 FORMAT OUTPUT WAJIB (Bahasa Indonesia) ===
|
| 403 |
### 🏛️ 1. EXECUTIVE VERDICT & KONSENSUS BURSA
|
| 404 |
- **Directional Bias**: [STRONG LONG / BUY ON PULLBACK / STRONG SHORT / SELL ON RALLY / WAIT-AND-SEE]
|
| 405 |
- **Confluence Consensus**: [Sebutkan skor konviksi, kesepakatan indikator (misal X Bullish vs Y Bearish), dan kestabilan streak]
|
| 406 |
-
- **
|
| 407 |
- **Ringkasan Eksekutif (1-2 Kalimat)**: [Sintesis padat alasan utama arah pasar berdasarkan data di atas]
|
| 408 |
|
| 409 |
### 🌊 2. BEDAH ANATOMI MODAL, CARRY & ON-CHAIN ALPHA
|
| 410 |
-
- **Spot CVD vs Futures CVD**: [Evaluasi akumulasi spot
|
| 411 |
-
- **Funding Rate
|
| 412 |
-
- **Hyperliquid DEX & Open Interest**: [Konfirmasi posisi whale on-chain dan apakah volume baru agresif masuk atau terjadi covering/likuidasi]
|
| 413 |
|
| 414 |
### 🧲 3. MIKROSTRUKTUR ORDERBOOK, VOLATILITAS & MAGNET LIKUIDASI
|
| 415 |
- **Orderbook Imbalance**: [Analisa dinding Bids vs Asks dan letak penahan harga]
|
| 416 |
-
- **Energi Volatilitas &
|
| 417 |
- **Target Sapuan Likuidasi (Whale Hunting Zone)**: [Level magnet short/long liquidation yang paling berpeluang disikat oleh Market Maker]
|
| 418 |
|
| 419 |
### 🎯 4. ACTIONABLE TRADE SETUP (STANDAR INSTITUSIONAL)
|
| 420 |
-
- **Zona Entry**: [Rentang harga aman berbasis pullback S/R]
|
| 421 |
- **Dynamic Stop Loss (SL)**: [Level ketat di luar area manipulasi wick hunt]
|
| 422 |
-
- **Take Profit (TP1 & TP2)**: [TP1 realistis, TP2 runner di area magnet likuidasi]
|
| 423 |
- **Risk/Reward**: [Minimal 1 : 1.5+]
|
| 424 |
-
- **Rekomendasi Leverage & Sizing**: [Batas leverage aman sesuai profil volatilitas aset]
|
| 425 |
- **Kondisi Invalidasi Kritis**: [Syarat pasti kapan rencana ini gugur total berdasarkan penutupan candle 1H/4H]
|
| 426 |
"""
|
| 427 |
|
|
@@ -449,6 +503,19 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi
|
|
| 449 |
"direction": direction,
|
| 450 |
"streak": streak_count,
|
| 451 |
"confluence_pct": confluence_pct,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 452 |
}
|
| 453 |
|
| 454 |
return prompt, data_summary
|
|
|
|
| 17 |
|
| 18 |
from database.db import async_get_latest_signal, async_get_latest_snapshot
|
| 19 |
from engine.doh_resolver import enable_doh_bypass
|
| 20 |
+
from engine.signal_engine import (
|
| 21 |
+
_compute_lead_lag,
|
| 22 |
+
_compute_funding_settlement,
|
| 23 |
+
_compute_price_extremes_24h,
|
| 24 |
+
_compute_whale_order_flow,
|
| 25 |
+
)
|
| 26 |
|
| 27 |
enable_doh_bypass()
|
| 28 |
|
|
|
|
| 172 |
if v is None: return "N/A"
|
| 173 |
return f"{v * 100:+.4f}%"
|
| 174 |
|
| 175 |
+
def _px_venue(px: Any) -> str:
|
| 176 |
+
if px is None or px == 0:
|
| 177 |
+
return "N/A"
|
| 178 |
+
return _fmt_px(px)
|
| 179 |
+
|
| 180 |
+
binance_px = binance.get("mark_price")
|
| 181 |
+
bybit_px = bybit.get("mark_price")
|
| 182 |
+
okx_px = okx.get("mark_price")
|
| 183 |
+
hl_px = hl.get("mark_price")
|
| 184 |
+
|
| 185 |
+
# Extended Institutional Microstructure: Lead-Lag, Settlement, Extremes & Whale Flow
|
| 186 |
+
lead_lag = signals_data.get("lead_lag")
|
| 187 |
+
if not lead_lag:
|
| 188 |
+
lead_lag = _compute_lead_lag(exch_data, mark_price)
|
| 189 |
+
|
| 190 |
+
settlement = signals_data.get("funding_settlement")
|
| 191 |
+
if not settlement:
|
| 192 |
+
settlement = _compute_funding_settlement(exch_data)
|
| 193 |
+
|
| 194 |
+
extremes = signals_data.get("price_extremes")
|
| 195 |
+
if not extremes:
|
| 196 |
+
extremes = {
|
| 197 |
+
"high_24h": mark_price, "low_24h": mark_price, "range_usd": 0.0,
|
| 198 |
+
"range_pct": 0.0, "dist_to_high_pct": 0.0, "dist_to_low_pct": 0.0,
|
| 199 |
+
"range_position_pct": 50.0, "zone_label": "Equilibrium",
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
whale_flow = signals_data.get("whale_flow")
|
| 203 |
+
if not whale_flow:
|
| 204 |
+
whale_flow = {
|
| 205 |
+
"taker_buy_pct": 50.0, "taker_ratio": 1.0, "whale_buy_count": 0,
|
| 206 |
+
"whale_sell_count": 0, "whale_buy_vol_usd": 0.0, "whale_sell_vol_usd": 0.0,
|
| 207 |
+
"largest_trade_usd": 0.0, "largest_trade_side": "NONE",
|
| 208 |
+
"flow_verdict": "Order Flow Agregat Seimbang",
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
# 1. Total Aggregated Open Interest across all venues
|
| 212 |
total_oi_usd = 0.0
|
| 213 |
venue_oi_str_list = []
|
|
|
|
| 391 |
prompt = f"""Role: Damian — Senior Institutional Crypto Derivatives Quantitative Strategist.
|
| 392 |
Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presisi kuantitatif, dan tanpa basa-basi pembuka/penutup.
|
| 393 |
|
| 394 |
+
=== 📊 DATA LIVE BURSA & KUANTITATIF REAL-TIME ({symbol}) ===
|
| 395 |
+
1. KONSENSUS ARAH, KONVIKSI & STREAK SISTEM
|
| 396 |
• Sinyal Sistem: {direction} | Conviction Score: {conviction}/10 | Konsistensi Streak: {streak_count} Siklus Berturut-turut ({streak_dir})
|
| 397 |
• Confluence Consensus: {len(bullish_signals)} Bullish vs {len(bearish_signals)} Bearish vs {len(neutral_signals)} Netral ({confluence_pct}% Kesepakatan)
|
| 398 |
• Sinyal Pendukung: {', '.join(bullish_signals) if bullish_signals else 'Tidak ada'}
|
| 399 |
• Sinyal Menentang: {', '.join(bearish_signals) if bearish_signals else 'Tidak ada'}
|
| 400 |
|
| 401 |
+
2. HARGA MULTI-BURSA, DISPARITAS LEAD-LAG & LIKUIDITAS
|
| 402 |
+
• Mark Price Utama: {_fmt_px(mark_price)} | Index Price: {_fmt_px(index_price)} | Basis Spread: {div_pct:+.3f}%
|
| 403 |
+
• Matrix Harga Bursa: Binance: {_px_venue(binance_px)} | Bybit: {_px_venue(bybit_px)} | OKX: {_px_venue(okx_px)} | Hyperliquid DEX: {_px_venue(hl_px)}
|
| 404 |
+
• Lead-Lag Disparity: Spread Maksimal {lead_lag.get('max_spread_bps', 0.0):.1f} bps (${_fmt_px(lead_lag.get('max_spread_usd', 0.0))}) | Status: {lead_lag.get('lead_lag_summary', 'Ketat / Seimbang')}
|
| 405 |
• Total Open Interest Agregat (4 Bursa): {total_oi_str} ({venue_oi_breakdown})
|
| 406 |
• Status Pasar: {spot_status_str}
|
| 407 |
|
| 408 |
+
3. EXTREMES 24 JAM & PROFIL RENTANG HARGA
|
| 409 |
+
• 24H High: {_fmt_px(extremes.get('high_24h', mark_price))} ({extremes.get('dist_to_high_pct', 0.0):+.2f}% dari harga saat ini)
|
| 410 |
+
• 24H Low: {_fmt_px(extremes.get('low_24h', mark_price))} ({extremes.get('dist_to_low_pct', 0.0):+.2f}% dari harga saat ini)
|
| 411 |
+
• Rentang 24H: {_fmt_px(extremes.get('range_usd', 0.0))} ({extremes.get('range_pct', 0.0):.2f}% rentang volatilitas)
|
| 412 |
+
• Posisi Rentang: {extremes.get('range_position_pct', 50.0):.1f}% -> {extremes.get('zone_label', 'Equilibrium')}
|
| 413 |
+
|
| 414 |
+
4. FUNDING RATES, COUNTDOWN SETTLEMENT & ANNUALIZED CARRY (APR %)
|
| 415 |
• Rata-rata Funding Rate 8H: {avg_fr_8h_pct:+.4f}% | Annualized APR: {annualized_apr_pct:+.2f}% APR
|
| 416 |
+
• Jadwal Settlement Terdekat: Hitung mundur {settlement.get('countdown_str', 'N/A')} ({settlement.get('risk_label', '')})
|
| 417 |
• Carry Arbitrage Impact: {carry_impact}
|
| 418 |
• Breakdown Bursa: Binance: {binance_fr} ({binance_ls}) | Bybit: {bybit_fr} ({bybit_ls}) | OKX: {okx_fr} ({okx_ls}) | Hyperliquid DEX: {hl_fr}
|
| 419 |
|
| 420 |
+
5. ORDER FLOW INSTITUSIONAL, WHALE BLOCK TRADES & CVD
|
| 421 |
• Spot CVD: {spot_cvd} | Futures CVD: {fut_cvd} -> Status Aliran: {cvd_label}
|
| 422 |
+
• Agresivitas Taker: Buy {whale_flow.get('taker_buy_pct', 50.0):.1f}% vs Sell {100.0 - whale_flow.get('taker_buy_pct', 50.0):.1f}% (Rasio Taker: {whale_flow.get('taker_ratio', 1.0):.2f}x)
|
| 423 |
+
• Whale Block Trades (> $25K): {whale_flow.get('whale_buy_count', 0)} Buy Blocks (${whale_flow.get('whale_buy_vol_usd', 0.0):,.0f}) vs {whale_flow.get('whale_sell_count', 0)} Sell Blocks (${whale_flow.get('whale_sell_vol_usd', 0.0):,.0f})
|
| 424 |
+
• Trade Terbesar: {_fmt_usd(whale_flow.get('largest_trade_usd', 0.0))} ({whale_flow.get('largest_trade_side', 'NONE')}) -> {whale_flow.get('flow_verdict', '')}
|
| 425 |
• Hyperliquid DEX Whale Flow: {hl_label} (Basis Mark-Oracle: {hl_basis:+.3f}%)
|
| 426 |
• Open Interest Divergence: {oi_div_str}
|
| 427 |
|
| 428 |
+
6. STRUKTUR MULTI-TIMEFRAME (MTF), VOLATILITAS & ORDERBOOK
|
| 429 |
• Struktur MTF: 1D: {struct_map.get('1d', 'unknown').upper()} | 4H: {struct_map.get('4h', 'unknown').upper()} | 1H: {struct_map.get('1h', 'unknown').upper()} | 15M: {struct_map.get('15m', 'unknown').upper()} (Active TF: {active_tf.upper()})
|
| 430 |
• Volatility Squeeze: {squeeze_intensity} (Compression Ratio: {compression_ratio:.2f})
|
| 431 |
• Kedalaman Orderbook (Top 20 Depth): ${bid_depth:,.0f} Bids vs ${ask_depth:,.0f} Asks (Rasio: {depth_ratio:.2f}x) -> {resting_pressure}
|
| 432 |
|
| 433 |
+
7. MAGNET LIKUIDASI WHALE & TARGET PREDIKTIF
|
| 434 |
• Upper Short Liquidation Magnet: {upper_mag} ({dist_up:+.2f}%)
|
| 435 |
• Lower Long Liquidation Magnet: {lower_mag} ({dist_down:+.2f}%)
|
| 436 |
• Target Prediktif Sistem: {pred_target_str} ({target_type}) | Jarak: {target_dist_pct:+.2f}%
|
| 437 |
• Antisipasi Pergerakan: {anticipation_text}
|
| 438 |
|
| 439 |
+
8. KONTEKS PASAR GLOBAL & DETEKSI ANOMALI
|
| 440 |
• Rezim Pasar Global: {regime_text}
|
| 441 |
• Keselarasan Tren: {alignment_text}
|
| 442 |
• Status Manipulasi Harga: {fake_status_str}
|
|
|
|
| 450 |
2. DILARANG MEMBERIKAN ANALISA MENGAMBANG ("bisa naik atau turun"). Tetapkan 1 BIAS terkuat yang paling didukung data kuantitatif bursa.
|
| 451 |
3. HUKUM CVD & LEVERAGE TRAP: Jika Futures CVD naik tapi Spot CVD turun/negatif, ini adalah LEVERAGE TRAP (Retail beli futures, Spot buang barang). DILARANG menyarankan Long mengejar pucuk!
|
| 452 |
4. ATURAN INVALIDASI KRITIS: Syarat pembatalan setup WAJIB berbasis penutupan candle (misal: "Batal jika candle 1H ditutup di bawah $X"), BUKAN sekadar sengatan jarum wick touch.
|
| 453 |
+
5. SINTESIS LEAD-LAG & EXTREMES 24 JAM: Sebutkan bursa mana yang memimpin pergerakan harga dan perhatikan posisi harga terhadap 24H High/Low sebagai zona take profit/invalidation alami.
|
| 454 |
+
6. Gaya Penulisan: Padat, poin per poin tajam, bernada Quantitative Research Desk Telegram. Panjang 350-500 kata.
|
| 455 |
|
| 456 |
=== 📝 FORMAT OUTPUT WAJIB (Bahasa Indonesia) ===
|
| 457 |
### 🏛️ 1. EXECUTIVE VERDICT & KONSENSUS BURSA
|
| 458 |
- **Directional Bias**: [STRONG LONG / BUY ON PULLBACK / STRONG SHORT / SELL ON RALLY / WAIT-AND-SEE]
|
| 459 |
- **Confluence Consensus**: [Sebutkan skor konviksi, kesepakatan indikator (misal X Bullish vs Y Bearish), dan kestabilan streak]
|
| 460 |
+
- **Disparitas Harga & Bursa Pendorong (Lead-Lag)**: [Spread antar bursa dalam bps, bursa mana yang memimpin harga, dan posisi relatif terhadap rentang 24H High/Low]
|
| 461 |
- **Ringkasan Eksekutif (1-2 Kalimat)**: [Sintesis padat alasan utama arah pasar berdasarkan data di atas]
|
| 462 |
|
| 463 |
### 🌊 2. BEDAH ANATOMI MODAL, CARRY & ON-CHAIN ALPHA
|
| 464 |
+
- **Spot CVD vs Futures CVD & Whale Block Trades**: [Evaluasi akumulasi spot vs leverage futures retail, dominasi taker buy/sell, dan aktivitas whale block trade]
|
| 465 |
+
- **Funding Rate, Countdown Settlement & Carry (APR)**: [Dampak carry cost tahunan, hitung mundur settlement terdekat, dan ada/tidaknya risiko volatilitas fee rebalancing]
|
| 466 |
+
- **Hyperliquid DEX & Open Interest**: [Konfirmasi posisi whale on-chain DEX dan apakah volume baru agresif masuk atau terjadi covering/likuidasi]
|
| 467 |
|
| 468 |
### 🧲 3. MIKROSTRUKTUR ORDERBOOK, VOLATILITAS & MAGNET LIKUIDASI
|
| 469 |
- **Orderbook Imbalance**: [Analisa dinding Bids vs Asks dan letak penahan harga]
|
| 470 |
+
- **Energi Volatilitas & Profil 24 Jam**: [Tingkat kompresi harga, ruang gerak terhadap 24H High/Low, dan antisipasi arah ledakan]
|
| 471 |
- **Target Sapuan Likuidasi (Whale Hunting Zone)**: [Level magnet short/long liquidation yang paling berpeluang disikat oleh Market Maker]
|
| 472 |
|
| 473 |
### 🎯 4. ACTIONABLE TRADE SETUP (STANDAR INSTITUSIONAL)
|
| 474 |
+
- **Zona Entry**: [Rentang harga aman berbasis pullback S/R dan jarak aman dari 24H extremes]
|
| 475 |
- **Dynamic Stop Loss (SL)**: [Level ketat di luar area manipulasi wick hunt]
|
| 476 |
+
- **Take Profit (TP1 & TP2)**: [TP1 realistis, TP2 runner di area magnet likuidasi / 24H High/Low]
|
| 477 |
- **Risk/Reward**: [Minimal 1 : 1.5+]
|
| 478 |
+
- **Rekomendasi Leverage & Sizing**: [Batas leverage aman sesuai profil volatilitas aset dan countdown settlement funding]
|
| 479 |
- **Kondisi Invalidasi Kritis**: [Syarat pasti kapan rencana ini gugur total berdasarkan penutupan candle 1H/4H]
|
| 480 |
"""
|
| 481 |
|
|
|
|
| 503 |
"direction": direction,
|
| 504 |
"streak": streak_count,
|
| 505 |
"confluence_pct": confluence_pct,
|
| 506 |
+
"high_24h": extremes.get("high_24h"),
|
| 507 |
+
"low_24h": extremes.get("low_24h"),
|
| 508 |
+
"range_24h_pct": extremes.get("range_pct"),
|
| 509 |
+
"dist_to_high_pct": extremes.get("dist_to_high_pct"),
|
| 510 |
+
"dist_to_low_pct": extremes.get("dist_to_low_pct"),
|
| 511 |
+
"range_position_pct": extremes.get("range_position_pct"),
|
| 512 |
+
"lead_lag_spread_bps": lead_lag.get("max_spread_bps"),
|
| 513 |
+
"leading_exchange": lead_lag.get("leading_exchange"),
|
| 514 |
+
"funding_countdown": settlement.get("countdown_str"),
|
| 515 |
+
"is_settlement_imminent": settlement.get("is_settlement_imminent"),
|
| 516 |
+
"taker_buy_pct": whale_flow.get("taker_buy_pct"),
|
| 517 |
+
"whale_buy_count": whale_flow.get("whale_buy_count"),
|
| 518 |
+
"whale_sell_count": whale_flow.get("whale_sell_count"),
|
| 519 |
}
|
| 520 |
|
| 521 |
return prompt, data_summary
|
frontend/src/components/signals/AIAnalysisPanel.tsx
CHANGED
|
@@ -397,6 +397,38 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) {
|
|
| 397 |
<span className="text-text-muted block text-[9px]">LIQ MAGNET BAWAH</span>
|
| 398 |
<span className="text-signal-short">{result.data_snapshot.lower_magnet}</span>
|
| 399 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 400 |
</div>
|
| 401 |
)}
|
| 402 |
|
|
|
|
| 397 |
<span className="text-text-muted block text-[9px]">LIQ MAGNET BAWAH</span>
|
| 398 |
<span className="text-signal-short">{result.data_snapshot.lower_magnet}</span>
|
| 399 |
</div>
|
| 400 |
+
{result.data_snapshot.lead_lag_spread_bps !== undefined && (
|
| 401 |
+
<div>
|
| 402 |
+
<span className="text-text-muted block text-[9px]">LEAD-LAG SPREAD</span>
|
| 403 |
+
<span className="text-cyan-300">
|
| 404 |
+
{result.data_snapshot.lead_lag_spread_bps.toFixed(1)} bps ({result.data_snapshot.leading_exchange?.toUpperCase() || 'BALANCED'})
|
| 405 |
+
</span>
|
| 406 |
+
</div>
|
| 407 |
+
)}
|
| 408 |
+
{result.data_snapshot.funding_countdown && (
|
| 409 |
+
<div>
|
| 410 |
+
<span className="text-text-muted block text-[9px]">SETTLEMENT COUNTDOWN</span>
|
| 411 |
+
<span className={result.data_snapshot.is_settlement_imminent ? "text-amber-400 font-bold" : "text-text-primary"}>
|
| 412 |
+
{result.data_snapshot.funding_countdown}
|
| 413 |
+
</span>
|
| 414 |
+
</div>
|
| 415 |
+
)}
|
| 416 |
+
{result.data_snapshot.range_24h_pct !== undefined && (
|
| 417 |
+
<div>
|
| 418 |
+
<span className="text-text-muted block text-[9px]">RENTANG 24 JAM</span>
|
| 419 |
+
<span className="text-text-primary">
|
| 420 |
+
{result.data_snapshot.range_24h_pct.toFixed(2)}% ({result.data_snapshot.range_position_pct?.toFixed(0)}% pos)
|
| 421 |
+
</span>
|
| 422 |
+
</div>
|
| 423 |
+
)}
|
| 424 |
+
{result.data_snapshot.whale_buy_count !== undefined && (
|
| 425 |
+
<div>
|
| 426 |
+
<span className="text-text-muted block text-[9px]">WHALE BLOCK TRADES</span>
|
| 427 |
+
<span className="text-emerald-400">
|
| 428 |
+
{result.data_snapshot.whale_buy_count} Buys / {result.data_snapshot.whale_sell_count} Sells
|
| 429 |
+
</span>
|
| 430 |
+
</div>
|
| 431 |
+
)}
|
| 432 |
</div>
|
| 433 |
)}
|
| 434 |
|
frontend/src/pages/AITerminal.tsx
CHANGED
|
@@ -819,6 +819,38 @@ export function AITerminal({ initialSymbol = 'BTCUSDT', onSelectSymbol }: AITerm
|
|
| 819 |
<span className="text-text-muted block text-[9px]">ORDERBOOK PRESSURE</span>
|
| 820 |
<span className="text-text-primary">{msg.dataSnapshot.resting_pressure}</span>
|
| 821 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 822 |
</div>
|
| 823 |
)}
|
| 824 |
</div>
|
|
|
|
| 819 |
<span className="text-text-muted block text-[9px]">ORDERBOOK PRESSURE</span>
|
| 820 |
<span className="text-text-primary">{msg.dataSnapshot.resting_pressure}</span>
|
| 821 |
</div>
|
| 822 |
+
{msg.dataSnapshot.lead_lag_spread_bps !== undefined && (
|
| 823 |
+
<div>
|
| 824 |
+
<span className="text-text-muted block text-[9px]">LEAD-LAG SPREAD</span>
|
| 825 |
+
<span className="text-cyan-300">
|
| 826 |
+
{msg.dataSnapshot.lead_lag_spread_bps.toFixed(1)} bps ({msg.dataSnapshot.leading_exchange?.toUpperCase() || 'BALANCED'})
|
| 827 |
+
</span>
|
| 828 |
+
</div>
|
| 829 |
+
)}
|
| 830 |
+
{msg.dataSnapshot.funding_countdown && (
|
| 831 |
+
<div>
|
| 832 |
+
<span className="text-text-muted block text-[9px]">SETTLEMENT</span>
|
| 833 |
+
<span className={msg.dataSnapshot.is_settlement_imminent ? "text-amber-400 font-bold" : "text-text-primary"}>
|
| 834 |
+
{msg.dataSnapshot.funding_countdown}
|
| 835 |
+
</span>
|
| 836 |
+
</div>
|
| 837 |
+
)}
|
| 838 |
+
{msg.dataSnapshot.range_24h_pct !== undefined && (
|
| 839 |
+
<div>
|
| 840 |
+
<span className="text-text-muted block text-[9px]">24H RANGE</span>
|
| 841 |
+
<span className="text-text-primary">
|
| 842 |
+
{msg.dataSnapshot.range_24h_pct.toFixed(2)}% ({msg.dataSnapshot.range_position_pct?.toFixed(0)}% pos)
|
| 843 |
+
</span>
|
| 844 |
+
</div>
|
| 845 |
+
)}
|
| 846 |
+
{msg.dataSnapshot.whale_buy_count !== undefined && (
|
| 847 |
+
<div>
|
| 848 |
+
<span className="text-text-muted block text-[9px]">WHALE BLOCKS</span>
|
| 849 |
+
<span className="text-emerald-400">
|
| 850 |
+
{msg.dataSnapshot.whale_buy_count}B / {msg.dataSnapshot.whale_sell_count}S
|
| 851 |
+
</span>
|
| 852 |
+
</div>
|
| 853 |
+
)}
|
| 854 |
</div>
|
| 855 |
)}
|
| 856 |
</div>
|
frontend/src/types/index.ts
CHANGED
|
@@ -212,6 +212,19 @@ export interface AIAnalysisResponse {
|
|
| 212 |
lower_magnet: string;
|
| 213 |
squeeze_intensity: string;
|
| 214 |
resting_pressure: string;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
};
|
| 216 |
created_at: string;
|
| 217 |
}
|
|
|
|
| 212 |
lower_magnet: string;
|
| 213 |
squeeze_intensity: string;
|
| 214 |
resting_pressure: string;
|
| 215 |
+
high_24h?: number;
|
| 216 |
+
low_24h?: number;
|
| 217 |
+
range_24h_pct?: number;
|
| 218 |
+
dist_to_high_pct?: number;
|
| 219 |
+
dist_to_low_pct?: number;
|
| 220 |
+
range_position_pct?: number;
|
| 221 |
+
lead_lag_spread_bps?: number;
|
| 222 |
+
leading_exchange?: string;
|
| 223 |
+
funding_countdown?: string;
|
| 224 |
+
is_settlement_imminent?: boolean;
|
| 225 |
+
taker_buy_pct?: number;
|
| 226 |
+
whale_buy_count?: number;
|
| 227 |
+
whale_sell_count?: number;
|
| 228 |
};
|
| 229 |
created_at: string;
|
| 230 |
}
|
tests/test_calculations.py
CHANGED
|
@@ -17,6 +17,10 @@ from engine.signal_engine import (
|
|
| 17 |
_compute_ls_ratio,
|
| 18 |
_compute_basis,
|
| 19 |
_compute_trade_plan,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
)
|
| 21 |
from engine.fake_detector import (
|
| 22 |
FakeDetector,
|
|
@@ -233,6 +237,84 @@ def test_warnings_do_not_deduct_score():
|
|
| 233 |
assert out_short["direction"] == "SHORT"
|
| 234 |
print(" PASSED!")
|
| 235 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
if __name__ == "__main__":
|
| 237 |
print("=" * 60)
|
| 238 |
print("STARTING TEST SUITE: ENGINE CALCULATION AUDIT")
|
|
|
|
| 17 |
_compute_ls_ratio,
|
| 18 |
_compute_basis,
|
| 19 |
_compute_trade_plan,
|
| 20 |
+
_compute_lead_lag,
|
| 21 |
+
_compute_funding_settlement,
|
| 22 |
+
_compute_price_extremes_24h,
|
| 23 |
+
_compute_whale_order_flow,
|
| 24 |
)
|
| 25 |
from engine.fake_detector import (
|
| 26 |
FakeDetector,
|
|
|
|
| 237 |
assert out_short["direction"] == "SHORT"
|
| 238 |
print(" PASSED!")
|
| 239 |
|
| 240 |
+
def test_extended_quant_telemetry():
|
| 241 |
+
print("[9] Testing Extended Quantitative Telemetry (Lead-Lag, Settlement, Extremes, Whale Flow)...")
|
| 242 |
+
# 1. Lead-Lag
|
| 243 |
+
exch_data = {
|
| 244 |
+
"binance": {"mark_price": 100.0},
|
| 245 |
+
"bybit": {"mark_price": 100.10}, # +10 bps
|
| 246 |
+
"okx": {"mark_price": 99.95},
|
| 247 |
+
"hyperliquid": {"mark_price": 99.90},
|
| 248 |
+
}
|
| 249 |
+
lead_lag = _compute_lead_lag(exch_data, mark_price=100.0)
|
| 250 |
+
assert lead_lag["leading_exchange"] == "bybit", f"Expected Bybit to lead, got {lead_lag['leading_exchange']}"
|
| 251 |
+
assert lead_lag["lagging_exchange"] == "hyperliquid"
|
| 252 |
+
assert lead_lag["max_spread_bps"] > 15.0, f"Expected spread > 15 bps, got {lead_lag['max_spread_bps']}"
|
| 253 |
+
assert len(lead_lag["spread_table"]) == 4
|
| 254 |
+
|
| 255 |
+
# 2. Funding Settlement
|
| 256 |
+
import time
|
| 257 |
+
now_ms = time.time() * 1000.0
|
| 258 |
+
exch_settle = {
|
| 259 |
+
"binance": {"next_funding_time": now_ms + (45 * 60 * 1000)}, # 45m away
|
| 260 |
+
"bybit": {"next_funding_time": now_ms + (120 * 60 * 1000)}, # 2h away
|
| 261 |
+
"hyperliquid": {"next_funding_time": now_ms + (25 * 60 * 1000)},
|
| 262 |
+
}
|
| 263 |
+
settle = _compute_funding_settlement(exch_settle)
|
| 264 |
+
assert settle["countdown_str"] is not None
|
| 265 |
+
assert settle["is_settlement_imminent"] is True
|
| 266 |
+
|
| 267 |
+
# 3. 24H Price Extremes
|
| 268 |
+
candles_1h = [
|
| 269 |
+
{"high": 105.0, "low": 95.0, "close": 100.0, "open": 98.0}
|
| 270 |
+
for _ in range(24)
|
| 271 |
+
]
|
| 272 |
+
candles_1h[-5]["high"] = 110.0 # 24h high
|
| 273 |
+
candles_1h[-10]["low"] = 90.0 # 24h low
|
| 274 |
+
extremes = _compute_price_extremes_24h({"1h": candles_1h}, mark_price=100.0)
|
| 275 |
+
assert extremes["high_24h"] == 110.0
|
| 276 |
+
assert extremes["low_24h"] == 90.0
|
| 277 |
+
assert extremes["range_usd"] == 20.0
|
| 278 |
+
assert extremes["dist_to_high_pct"] == 10.0 # (110-100)/100 = 10%
|
| 279 |
+
assert extremes["dist_to_low_pct"] == 10.0 # (100-90)/100 = 10%
|
| 280 |
+
assert extremes["range_position_pct"] == 50.0 # mid range
|
| 281 |
+
|
| 282 |
+
# 4. Whale Order Flow
|
| 283 |
+
trades = [
|
| 284 |
+
{"price": 100.0, "qty": 500.0, "is_buyer_maker": False}, # $50,000 Taker BUY (Whale)
|
| 285 |
+
{"price": 100.0, "qty": 300.0, "is_buyer_maker": False}, # $30,000 Taker BUY (Whale)
|
| 286 |
+
{"price": 100.0, "qty": 10.0, "is_buyer_maker": True}, # $1,000 Taker SELL (Retail)
|
| 287 |
+
]
|
| 288 |
+
flow = _compute_whale_order_flow(trades, mark_price=100.0)
|
| 289 |
+
assert flow["whale_buy_count"] == 2
|
| 290 |
+
assert flow["whale_sell_count"] == 0
|
| 291 |
+
assert flow["whale_buy_vol_usd"] == 80000.0
|
| 292 |
+
assert flow["largest_trade_usd"] == 50000.0
|
| 293 |
+
assert flow["largest_trade_side"] == "BUY"
|
| 294 |
+
assert flow["taker_buy_pct"] > 95.0
|
| 295 |
+
|
| 296 |
+
# 5. AI Prompt Integration
|
| 297 |
+
from routers.ai import _build_ai_prompt
|
| 298 |
+
signal_mock = {
|
| 299 |
+
"direction": "LONG",
|
| 300 |
+
"conviction": 8,
|
| 301 |
+
"lead_lag": lead_lag,
|
| 302 |
+
"funding_settlement": settle,
|
| 303 |
+
"price_extremes": extremes,
|
| 304 |
+
"whale_flow": flow,
|
| 305 |
+
"exchange_data": exch_data,
|
| 306 |
+
"signals": {},
|
| 307 |
+
"predictive": {},
|
| 308 |
+
}
|
| 309 |
+
prompt_txt, data_summary = _build_ai_prompt("BTCUSDT", signal_mock, [])
|
| 310 |
+
assert "Matrix Harga Bursa" in prompt_txt
|
| 311 |
+
assert "Disparitas Harga & Bursa Pendorong (Lead-Lag)" in prompt_txt
|
| 312 |
+
assert "EXTREMES 24 JAM & PROFIL RENTANG HARGA" in prompt_txt
|
| 313 |
+
assert "ORDER FLOW INSTITUSIONAL, WHALE BLOCK TRADES & CVD" in prompt_txt
|
| 314 |
+
assert data_summary["high_24h"] == 110.0
|
| 315 |
+
assert data_summary["whale_buy_count"] == 2
|
| 316 |
+
print(" PASSED!")
|
| 317 |
+
|
| 318 |
if __name__ == "__main__":
|
| 319 |
print("=" * 60)
|
| 320 |
print("STARTING TEST SUITE: ENGINE CALCULATION AUDIT")
|