Naufal Arhab commited on
Commit
80df99b
·
1 Parent(s): 6ba523a

fix(audit): resolve multi-pass backend calculations, exchange guards, AI/UI state, and chart bugs

Browse files

- Normalize exchange symbol resolution, spot/OHLCV/OI guards, and USD notional OI on multi-stream
- Harden outcome evaluator, fake detector, predictive engine, Bybit TP precision, and DoH SSRF safety
- Fix chart blanking, stale WS/query symbol guards, sub-cent price precision, and AI/server settings UI
- Rebuild frontend dist and add 39 regression tests (130 pytest passing)

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. backend/config.py +2 -2
  2. backend/database/db.py +31 -10
  3. backend/database/memory_store.py +14 -1
  4. backend/engine/backtester.py +4 -0
  5. backend/engine/data_collector.py +34 -16
  6. backend/engine/execution/bybit_executor.py +78 -27
  7. backend/engine/fake_detector.py +17 -11
  8. backend/engine/mtf_analyzer.py +38 -21
  9. backend/engine/outcome_evaluator.py +33 -16
  10. backend/engine/predictive_engine.py +2 -2
  11. backend/engine/signal_engine.py +601 -126
  12. backend/engine/symbol_resolver.py +35 -12
  13. backend/exchanges/base.py +60 -0
  14. backend/exchanges/binance.py +106 -57
  15. backend/exchanges/bitget.py +24 -10
  16. backend/exchanges/bybit.py +72 -40
  17. backend/exchanges/hyperliquid.py +55 -3
  18. backend/exchanges/okx.py +27 -11
  19. backend/main.py +25 -9
  20. backend/routers/ai.py +258 -70
  21. backend/routers/execution.py +14 -7
  22. backend/routers/journal.py +7 -7
  23. backend/routers/market.py +73 -14
  24. backend/routers/signals.py +5 -3
  25. backend/routers/ws.py +54 -7
  26. backend/scripts/run_backtest.py +2 -0
  27. frontend/dist/assets/AIAnalysisPanel-BbXTq8TV.js +0 -2
  28. frontend/dist/assets/AIAnalysisPanel-DsgKGe3C.js +2 -0
  29. frontend/dist/assets/AddPairModal-D8YkLLF_.js +0 -1
  30. frontend/dist/assets/AddPairModal-DCQtFcNW.js +1 -0
  31. frontend/dist/assets/GlobalAISettingsModal-BOzCh0qM.js +1 -0
  32. frontend/dist/assets/GlobalAISettingsModal-y_W5Q-P7.js +0 -1
  33. frontend/dist/assets/ServerSettingsModal-B2vOj2j4.js +1 -0
  34. frontend/dist/assets/ServerSettingsModal-BJC6WDDG.js +0 -1
  35. frontend/dist/assets/{index-FYyQL2Qc.js → index-CaCGPr1l.js} +0 -0
  36. frontend/dist/assets/{index--kfpEFWJ.css → index-DaWuxWbx.css} +0 -0
  37. frontend/dist/index.html +2 -2
  38. frontend/src/App.tsx +1 -0
  39. frontend/src/api/client.ts +2 -5
  40. frontend/src/components/chart/AggregatedOIChart.tsx +20 -3
  41. frontend/src/components/chart/CVDVolumeChart.tsx +13 -2
  42. frontend/src/components/chart/FundingRateHistoryChart.tsx +8 -2
  43. frontend/src/components/chart/MultiExchangeLiveBoard.tsx +2 -1
  44. frontend/src/components/chart/TradingViewChart.tsx +15 -3
  45. frontend/src/components/execution/ExecutionModal.tsx +38 -9
  46. frontend/src/components/layout/Header.tsx +6 -2
  47. frontend/src/components/layout/MobileDrawer.tsx +4 -1
  48. frontend/src/components/layout/Sidebar.tsx +4 -1
  49. frontend/src/components/pairs/AddPairModal.tsx +14 -2
  50. frontend/src/components/pairs/PairItem.tsx +1 -1
backend/config.py CHANGED
@@ -39,6 +39,6 @@ raw_cors = os.getenv("CORS_ORIGINS", "*")
39
  CORS_ORIGINS: list[str] = ["*"] if raw_cors == "*" else [c.strip() for c in raw_cors.split(",") if c.strip()]
40
 
41
  # --- Signal thresholds ---
42
- SIGNAL_LONG_THRESHOLD: int = 4
43
- SIGNAL_SHORT_THRESHOLD: int = -4
44
  MAX_CONVICTION: int = 10
 
39
  CORS_ORIGINS: list[str] = ["*"] if raw_cors == "*" else [c.strip() for c in raw_cors.split(",") if c.strip()]
40
 
41
  # --- Signal thresholds ---
42
+ SIGNAL_LONG_THRESHOLD: int = 3
43
+ SIGNAL_SHORT_THRESHOLD: int = -3
44
  MAX_CONVICTION: int = 10
backend/database/db.py CHANGED
@@ -7,7 +7,9 @@ asyncio.to_thread() called from async FastAPI routes / background tasks.
7
 
8
  import json
9
  import logging
 
10
  import asyncio
 
11
  from contextlib import contextmanager
12
  from typing import Any, Generator
13
 
@@ -31,6 +33,22 @@ logger = logging.getLogger(__name__)
31
 
32
  _pool: ConnectionPool | None = None
33
  _mem = memory_store
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
 
36
  def get_pool() -> ConnectionPool:
@@ -413,7 +431,7 @@ def db_save_signal(symbol: str, timeframe: str, direction: str, conviction: int,
413
  cur.execute(
414
  """INSERT INTO signals (symbol, timeframe, direction, conviction, signal_data)
415
  VALUES (%s, %s, %s, %s, %s)""",
416
- (symbol, timeframe, direction, conviction, json.dumps(signal_data)),
417
  )
418
 
419
 
@@ -692,7 +710,7 @@ def db_create_journal_entry(data: dict) -> dict:
692
  """Insert a new trade record into trade_journal."""
693
  if not DATABASE_URL:
694
  return _mem.create_journal_entry(data)
695
- snapshot_json = json.dumps(data.get("snapshot_data") or {})
696
  query = """
697
  INSERT INTO trade_journal (
698
  symbol, bias, entry_zone, stop_loss, take_profit, risk_reward,
@@ -816,7 +834,7 @@ def db_get_journal_stats() -> dict:
816
  COUNT(*) FILTER (WHERE status = 'HIT_SL') as hit_sl,
817
  COUNT(*) FILTER (WHERE status = 'PENDING') as pending,
818
  COUNT(*) FILTER (WHERE status = 'CANCELLED') as cancelled,
819
- COUNT(*) FILTER (WHERE status = 'HIT_SL' AND audited = FALSE) as unaudited_sl
820
  FROM trade_journal;
821
  """)
822
  row = cur.fetchone() or {}
@@ -851,7 +869,7 @@ def db_get_unaudited_failed_trades(limit: int = 10) -> list[dict]:
851
  cur.execute(
852
  """
853
  SELECT * FROM trade_journal
854
- WHERE status = 'HIT_SL' AND audited = FALSE
855
  ORDER BY created_at ASC
856
  LIMIT %s;
857
  """,
@@ -966,11 +984,14 @@ def _ensure_predictions_table(cur: Any, conn: Any) -> None:
966
  global _predictions_table_ensured
967
  if _predictions_table_ensured:
968
  return
969
- cur.execute(CREATE_SIGNAL_PREDICTIONS_TABLE)
970
- cur.execute(CREATE_SIGNAL_PREDICTIONS_PENDING_INDEX)
971
- cur.execute(CREATE_SIGNAL_PREDICTIONS_EVAL_INDEX)
972
- conn.commit()
973
- _predictions_table_ensured = True
 
 
 
974
 
975
 
976
  def db_insert_signal_prediction(data: dict) -> dict:
@@ -1000,7 +1021,7 @@ def db_insert_signal_prediction(data: dict) -> dict:
1000
  float(data.get("stop_loss", 0.0)),
1001
  float(data.get("tp1", 0.0)),
1002
  float(data.get("tp2", 0.0)),
1003
- json.dumps(data.get("factor_scores") or {}),
1004
  data.get("expires_at"),
1005
  ),
1006
  )
 
7
 
8
  import json
9
  import logging
10
+ import math
11
  import asyncio
12
+ import threading
13
  from contextlib import contextmanager
14
  from typing import Any, Generator
15
 
 
33
 
34
  _pool: ConnectionPool | None = None
35
  _mem = memory_store
36
+ _predictions_table_lock = threading.Lock()
37
+
38
+
39
+ def _sanitize_json_payload(obj: Any) -> Any:
40
+ """Replace non-finite floats (NaN/Inf) with None so PostgreSQL JSONB never fails on NaN."""
41
+ if isinstance(obj, float):
42
+ return obj if math.isfinite(obj) else None
43
+ if isinstance(obj, dict):
44
+ return {k: _sanitize_json_payload(v) for k, v in obj.items()}
45
+ if isinstance(obj, (list, tuple)):
46
+ return [_sanitize_json_payload(v) for v in obj]
47
+ return obj
48
+
49
+
50
+ def _safe_json_dumps(obj: Any) -> str:
51
+ return json.dumps(_sanitize_json_payload(obj), allow_nan=False)
52
 
53
 
54
  def get_pool() -> ConnectionPool:
 
431
  cur.execute(
432
  """INSERT INTO signals (symbol, timeframe, direction, conviction, signal_data)
433
  VALUES (%s, %s, %s, %s, %s)""",
434
+ (symbol, timeframe, direction, conviction, _safe_json_dumps(signal_data)),
435
  )
436
 
437
 
 
710
  """Insert a new trade record into trade_journal."""
711
  if not DATABASE_URL:
712
  return _mem.create_journal_entry(data)
713
+ snapshot_json = _safe_json_dumps(data.get("snapshot_data") or {})
714
  query = """
715
  INSERT INTO trade_journal (
716
  symbol, bias, entry_zone, stop_loss, take_profit, risk_reward,
 
834
  COUNT(*) FILTER (WHERE status = 'HIT_SL') as hit_sl,
835
  COUNT(*) FILTER (WHERE status = 'PENDING') as pending,
836
  COUNT(*) FILTER (WHERE status = 'CANCELLED') as cancelled,
837
+ COUNT(*) FILTER (WHERE status = 'HIT_SL' AND COALESCE(audited, FALSE) = FALSE) as unaudited_sl
838
  FROM trade_journal;
839
  """)
840
  row = cur.fetchone() or {}
 
869
  cur.execute(
870
  """
871
  SELECT * FROM trade_journal
872
+ WHERE status = 'HIT_SL' AND COALESCE(audited, FALSE) = FALSE
873
  ORDER BY created_at ASC
874
  LIMIT %s;
875
  """,
 
984
  global _predictions_table_ensured
985
  if _predictions_table_ensured:
986
  return
987
+ with _predictions_table_lock:
988
+ if _predictions_table_ensured:
989
+ return
990
+ cur.execute(CREATE_SIGNAL_PREDICTIONS_TABLE)
991
+ cur.execute(CREATE_SIGNAL_PREDICTIONS_PENDING_INDEX)
992
+ cur.execute(CREATE_SIGNAL_PREDICTIONS_EVAL_INDEX)
993
+ conn.commit()
994
+ _predictions_table_ensured = True
995
 
996
 
997
  def db_insert_signal_prediction(data: dict) -> dict:
 
1021
  float(data.get("stop_loss", 0.0)),
1022
  float(data.get("tp1", 0.0)),
1023
  float(data.get("tp2", 0.0)),
1024
+ _safe_json_dumps(data.get("factor_scores") or {}),
1025
  data.get("expires_at"),
1026
  ),
1027
  )
backend/database/memory_store.py CHANGED
@@ -385,6 +385,11 @@ class InMemoryDatabaseStore:
385
  entry["status"] = st
386
  entry["outcome_note"] = note
387
  entry["outcome_at"] = None if st == "PENDING" else _utc_now_iso()
 
 
 
 
 
388
  if failure_tag is not None:
389
  entry["failure_tag"] = failure_tag
390
  if exit_price is not None:
@@ -531,6 +536,8 @@ class InMemoryDatabaseStore:
531
  if isinstance(created_str, str):
532
  try:
533
  c_dt = datetime.fromisoformat(created_str.replace("Z", "+00:00"))
 
 
534
  if (now_dt - c_dt).total_seconds() < cooldown_hours * 3600:
535
  return copy.deepcopy(r)
536
  except ValueError:
@@ -550,6 +557,8 @@ class InMemoryDatabaseStore:
550
  if isinstance(created_str, str):
551
  try:
552
  c_dt = datetime.fromisoformat(created_str.replace("Z", "+00:00"))
 
 
553
  if (now_dt - c_dt).total_seconds() > cutoff_sec:
554
  continue
555
  except ValueError:
@@ -603,7 +612,11 @@ def compute_accuracy_summary_from_rows(rows: list[dict[str, Any]], days: int = 3
603
  if not isinstance(f_scores, dict):
604
  continue
605
  for f_name, raw_val in f_scores.items():
606
- score = int(raw_val.get("score", 0)) if isinstance(raw_val, dict) else int(raw_val or 0)
 
 
 
 
607
  if score == 0:
608
  continue
609
  b = factor_buckets.setdefault(f_name, {"aligned": [], "opposing": []})
 
385
  entry["status"] = st
386
  entry["outcome_note"] = note
387
  entry["outcome_at"] = None if st == "PENDING" else _utc_now_iso()
388
+ if st == "PENDING":
389
+ entry["failure_tag"] = None
390
+ entry["exit_price"] = None
391
+ entry["holding_duration_seconds"] = None
392
+ entry["audited"] = False
393
  if failure_tag is not None:
394
  entry["failure_tag"] = failure_tag
395
  if exit_price is not None:
 
536
  if isinstance(created_str, str):
537
  try:
538
  c_dt = datetime.fromisoformat(created_str.replace("Z", "+00:00"))
539
+ if c_dt.tzinfo is None:
540
+ c_dt = c_dt.replace(tzinfo=now_dt.tzinfo)
541
  if (now_dt - c_dt).total_seconds() < cooldown_hours * 3600:
542
  return copy.deepcopy(r)
543
  except ValueError:
 
557
  if isinstance(created_str, str):
558
  try:
559
  c_dt = datetime.fromisoformat(created_str.replace("Z", "+00:00"))
560
+ if c_dt.tzinfo is None:
561
+ c_dt = c_dt.replace(tzinfo=now_dt.tzinfo)
562
  if (now_dt - c_dt).total_seconds() > cutoff_sec:
563
  continue
564
  except ValueError:
 
612
  if not isinstance(f_scores, dict):
613
  continue
614
  for f_name, raw_val in f_scores.items():
615
+ raw_score = raw_val.get("score", 0) if isinstance(raw_val, dict) else raw_val
616
+ try:
617
+ score = int(float(raw_score)) if raw_score is not None else 0
618
+ except (TypeError, ValueError):
619
+ score = 0
620
  if score == 0:
621
  continue
622
  b = factor_buckets.setdefault(f_name, {"aligned": [], "opposing": []})
backend/engine/backtester.py CHANGED
@@ -43,11 +43,15 @@ def _aggregate_higher_tf(candles_1h: list[dict], group_hours: int) -> list[dict]
43
  "close": float(c["close"]),
44
  "volume": float(c.get("volume", 0.0)),
45
  }
 
 
46
  else:
47
  cur_bar["high"] = max(cur_bar["high"], float(c["high"]))
48
  cur_bar["low"] = min(cur_bar["low"], float(c["low"]))
49
  cur_bar["close"] = float(c["close"])
50
  cur_bar["volume"] += float(c.get("volume", 0.0))
 
 
51
 
52
  if cur_bar is not None:
53
  grouped.append(cur_bar)
 
43
  "close": float(c["close"]),
44
  "volume": float(c.get("volume", 0.0)),
45
  }
46
+ if c.get("taker_buy_volume") is not None:
47
+ cur_bar["taker_buy_volume"] = float(c["taker_buy_volume"])
48
  else:
49
  cur_bar["high"] = max(cur_bar["high"], float(c["high"]))
50
  cur_bar["low"] = min(cur_bar["low"], float(c["low"]))
51
  cur_bar["close"] = float(c["close"])
52
  cur_bar["volume"] += float(c.get("volume", 0.0))
53
+ if c.get("taker_buy_volume") is not None:
54
+ cur_bar["taker_buy_volume"] = cur_bar.get("taker_buy_volume", 0.0) + float(c["taker_buy_volume"])
55
 
56
  if cur_bar is not None:
57
  grouped.append(cur_bar)
backend/engine/data_collector.py CHANGED
@@ -20,6 +20,7 @@ from typing import Any
20
  import httpx
21
 
22
  from config import BYBIT_BASE_URL, PROXY_URL
 
23
  from exchanges.binance import BinanceClient
24
  from exchanges.bybit import BybitClient
25
  from exchanges.okx import OKXClient
@@ -32,12 +33,22 @@ logger = logging.getLogger(__name__)
32
  _SPOT_VERIFICATION_CACHE: dict[str, tuple[bool, float]] = {}
33
  _spot_cache_lock = asyncio.Lock()
34
  _SPOT_HTTP_CLIENT: httpx.AsyncClient | None = None
 
35
 
36
 
37
  def _get_spot_http_client() -> httpx.AsyncClient:
38
- """Return a shared persistent AsyncClient for spot existence probes (avoids repeated TLS handshakes)."""
39
- global _SPOT_HTTP_CLIENT
40
- if _SPOT_HTTP_CLIENT is None or _SPOT_HTTP_CLIENT.is_closed:
 
 
 
 
 
 
 
 
 
41
  kwargs: dict[str, Any] = {
42
  "timeout": 2.5,
43
  "verify": True,
@@ -50,15 +61,16 @@ def _get_spot_http_client() -> httpx.AsyncClient:
50
  if PROXY_URL:
51
  kwargs["proxy"] = PROXY_URL
52
  _SPOT_HTTP_CLIENT = httpx.AsyncClient(**kwargs)
 
53
  return _SPOT_HTTP_CLIENT
54
 
55
 
56
  def _clean_spot_symbol(symbol: str) -> str:
57
  """
58
- Strip futures multiplier prefixes (1000, 10000, 1000000, k) to match spot tickers.
59
- e.g. 1000PEPEUSDT -> PEPEUSDT, 1000SHIBUSDT -> SHIBUSDT, 1000BONKUSDT -> BONKUSDT
60
  """
61
- return re.sub(r'^(1000000000|1000000|100000|10000|1000|k)', '', symbol, flags=re.IGNORECASE).upper()
62
 
63
 
64
  async def check_spot_market_exists(symbol: str) -> bool:
@@ -68,17 +80,18 @@ async def check_spot_market_exists(symbol: str) -> bool:
68
  - If verified True: cached permanently in memory.
69
  - If False: re-checks automatically every 1 hour in case a spot market is newly listed.
70
  """
 
71
  now = time.time()
72
  async with _spot_cache_lock:
73
- if symbol in _SPOT_VERIFICATION_CACHE:
74
- cached_has_spot, timestamp = _SPOT_VERIFICATION_CACHE[symbol]
75
  # Permanent True or cached False within 1 hour
76
  if cached_has_spot or (now - timestamp < 3600):
77
  return cached_has_spot
78
 
79
- clean_symbol = _clean_spot_symbol(symbol)
80
- symbols_to_try = [symbol]
81
- if clean_symbol != symbol and clean_symbol.endswith("USDT"):
82
  symbols_to_try.append(clean_symbol)
83
 
84
  client = _get_spot_http_client()
@@ -108,9 +121,12 @@ async def check_spot_market_exists(symbol: str) -> bool:
108
 
109
  async def _check_okx() -> bool:
110
  for sym in symbols_to_try:
111
- if sym.endswith("USDT"):
112
- base = sym[:-4]
113
- inst_id = f"{base}-USDT"
 
 
 
114
  try:
115
  r = await client.get(f"https://www.okx.com/api/v5/public/instruments?instType=SPOT&instId={inst_id}")
116
  if r.status_code == 200:
@@ -125,7 +141,7 @@ async def check_spot_market_exists(symbol: str) -> bool:
125
  has_spot = any(res is True for res in results if not isinstance(res, Exception))
126
 
127
  async with _spot_cache_lock:
128
- _SPOT_VERIFICATION_CACHE[symbol] = (has_spot, now)
129
  return has_spot
130
 
131
 
@@ -189,14 +205,16 @@ class DataCollector:
189
  # Hyperliquid On-Chain DEX
190
  async def _fetch_hl():
191
  try:
192
- market_data, orderbook = await asyncio.gather(
193
  self._hyperliquid.get_market_data(symbol),
194
  self._hyperliquid.get_orderbook(symbol, depth=20),
 
195
  return_exceptions=True,
196
  )
197
  if isinstance(market_data, Exception) or not market_data:
198
  return None
199
  market_data["orderbook"] = orderbook if not isinstance(orderbook, Exception) else None
 
200
  return market_data
201
  except Exception as exc:
202
  logger.debug("[%s] Hyperliquid collect error: %s", symbol, exc)
 
20
  import httpx
21
 
22
  from config import BYBIT_BASE_URL, PROXY_URL
23
+ from engine.symbol_resolver import strip_multiplier_prefix
24
  from exchanges.binance import BinanceClient
25
  from exchanges.bybit import BybitClient
26
  from exchanges.okx import OKXClient
 
33
  _SPOT_VERIFICATION_CACHE: dict[str, tuple[bool, float]] = {}
34
  _spot_cache_lock = asyncio.Lock()
35
  _SPOT_HTTP_CLIENT: httpx.AsyncClient | None = None
36
+ _SPOT_HTTP_LOOP: asyncio.AbstractEventLoop | None = None
37
 
38
 
39
  def _get_spot_http_client() -> httpx.AsyncClient:
40
+ """Return a loop-safe persistent AsyncClient for spot existence probes."""
41
+ global _SPOT_HTTP_CLIENT, _SPOT_HTTP_LOOP
42
+ try:
43
+ current_loop = asyncio.get_running_loop()
44
+ except RuntimeError:
45
+ current_loop = None
46
+
47
+ loop_changed = (
48
+ _SPOT_HTTP_LOOP is not None
49
+ and (_SPOT_HTTP_LOOP.is_closed() or (current_loop is not None and _SPOT_HTTP_LOOP is not current_loop))
50
+ )
51
+ if _SPOT_HTTP_CLIENT is None or _SPOT_HTTP_CLIENT.is_closed or loop_changed:
52
  kwargs: dict[str, Any] = {
53
  "timeout": 2.5,
54
  "verify": True,
 
61
  if PROXY_URL:
62
  kwargs["proxy"] = PROXY_URL
63
  _SPOT_HTTP_CLIENT = httpx.AsyncClient(**kwargs)
64
+ _SPOT_HTTP_LOOP = current_loop
65
  return _SPOT_HTTP_CLIENT
66
 
67
 
68
  def _clean_spot_symbol(symbol: str) -> str:
69
  """
70
+ Strip futures multiplier prefixes (1000, 10000, 1000000, known meme k-prefixes)
71
+ to match spot tickers without mangling tokens like KAVAUSDT or KASUSDT.
72
  """
73
+ return strip_multiplier_prefix(symbol)
74
 
75
 
76
  async def check_spot_market_exists(symbol: str) -> bool:
 
80
  - If verified True: cached permanently in memory.
81
  - If False: re-checks automatically every 1 hour in case a spot market is newly listed.
82
  """
83
+ sym = symbol.upper().strip().replace("/", "").replace("-", "")
84
  now = time.time()
85
  async with _spot_cache_lock:
86
+ if sym in _SPOT_VERIFICATION_CACHE:
87
+ cached_has_spot, timestamp = _SPOT_VERIFICATION_CACHE[sym]
88
  # Permanent True or cached False within 1 hour
89
  if cached_has_spot or (now - timestamp < 3600):
90
  return cached_has_spot
91
 
92
+ clean_symbol = _clean_spot_symbol(sym)
93
+ symbols_to_try = [sym]
94
+ if clean_symbol and clean_symbol != sym and clean_symbol.endswith(("USDT", "USDC", "USD", "BUSD", "EUR")):
95
  symbols_to_try.append(clean_symbol)
96
 
97
  client = _get_spot_http_client()
 
121
 
122
  async def _check_okx() -> bool:
123
  for sym in symbols_to_try:
124
+ inst_id = None
125
+ for quote in ("USDT", "USDC", "USD", "BUSD", "EUR"):
126
+ if sym.endswith(quote) and len(sym) > len(quote):
127
+ inst_id = f"{sym[:-len(quote)]}-{quote}"
128
+ break
129
+ if inst_id:
130
  try:
131
  r = await client.get(f"https://www.okx.com/api/v5/public/instruments?instType=SPOT&instId={inst_id}")
132
  if r.status_code == 200:
 
141
  has_spot = any(res is True for res in results if not isinstance(res, Exception))
142
 
143
  async with _spot_cache_lock:
144
+ _SPOT_VERIFICATION_CACHE[sym] = (has_spot, now)
145
  return has_spot
146
 
147
 
 
205
  # Hyperliquid On-Chain DEX
206
  async def _fetch_hl():
207
  try:
208
+ market_data, orderbook, hl_trades = await asyncio.gather(
209
  self._hyperliquid.get_market_data(symbol),
210
  self._hyperliquid.get_orderbook(symbol, depth=20),
211
+ self._hyperliquid.get_recent_trades(symbol),
212
  return_exceptions=True,
213
  )
214
  if isinstance(market_data, Exception) or not market_data:
215
  return None
216
  market_data["orderbook"] = orderbook if not isinstance(orderbook, Exception) else None
217
+ market_data["trades"] = hl_trades if (not isinstance(hl_trades, Exception) and isinstance(hl_trades, list)) else []
218
  return market_data
219
  except Exception as exc:
220
  logger.debug("[%s] Hyperliquid collect error: %s", symbol, exc)
backend/engine/execution/bybit_executor.py CHANGED
@@ -12,6 +12,7 @@ import hashlib
12
  import logging
13
  import math
14
  import os
 
15
  from typing import Any
16
  from urllib.parse import urlencode
17
 
@@ -57,6 +58,11 @@ class BybitExecutor:
57
  async def close(self) -> None:
58
  await self._client.aclose()
59
 
 
 
 
 
 
60
  def _generate_signature(self, timestamp: str, payload_str: str) -> str:
61
  """Bybit V5 HMAC-SHA256 signature generator."""
62
  param_str = f"{timestamp}{self.api_key}{self.recv_window}{payload_str}"
@@ -77,10 +83,12 @@ class BybitExecutor:
77
  }
78
 
79
  if method.upper() == "GET":
80
- query_str = urlencode(sorted((params or {}).items())) if params else ""
 
81
  sign = self._generate_signature(timestamp, query_str)
82
  headers["X-BAPI-SIGN"] = sign
83
- resp = await self._client.get(path, params=params, headers=headers)
 
84
  else:
85
  body_str = json.dumps(json_body, separators=(",", ":")) if json_body else ""
86
  sign = self._generate_signature(timestamp, body_str)
@@ -109,7 +117,8 @@ class BybitExecutor:
109
  async def get_wallet_balance(self) -> dict[str, Any]:
110
  """Fetch Unified/Futures USDT available balance and total equity."""
111
  data = await self._request("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED"})
112
- acct_item = data.get("result", {}).get("list", [{}])[0]
 
113
  coins = acct_item.get("coin", [])
114
  usdt_info = next((c for c in coins if c.get("coin") == "USDT"), {})
115
  acct_equity = float(acct_item.get("totalEquity") or 0.0)
@@ -126,7 +135,7 @@ class BybitExecutor:
126
 
127
  async def get_instrument_info(self, symbol: str) -> dict[str, Any]:
128
  """Fetch contract precision, tickSize, and lotSize."""
129
- sym = symbol.upper().strip()
130
  data = await self._request("GET", "/v5/market/instruments-info", {
131
  "category": "linear",
132
  "symbol": sym,
@@ -153,7 +162,7 @@ class BybitExecutor:
153
 
154
  async def set_leverage(self, symbol: str, leverage: int) -> bool:
155
  """Set cross/isolated leverage for linear contract."""
156
- sym = symbol.upper().strip()
157
  lev_str = str(max(1, min(leverage, 100)))
158
  try:
159
  await self._request("POST", "/v5/position/set-leverage", json_body={
@@ -181,21 +190,42 @@ class BybitExecutor:
181
  return len(s.split(".")[1])
182
  return 0
183
 
 
 
 
 
 
 
 
 
 
184
  @classmethod
185
  def _round_step(cls, value: float, step: float) -> float:
186
- """Round down value to the nearest step to satisfy exchange filters."""
187
  if step <= 0:
188
  return value
189
  precision = cls._get_precision(step)
190
- return round(math.floor(value / step) * step, precision)
 
 
 
 
 
 
191
 
192
  @classmethod
193
  def _round_tick(cls, value: float, tick: float) -> float:
194
- """Round price to the nearest tick."""
195
  if tick <= 0:
196
  return value
197
  precision = cls._get_precision(tick)
198
- return round(round(value / tick) * tick, precision)
 
 
 
 
 
 
199
 
200
  async def _place_reduce_only_tp(
201
  self,
@@ -205,16 +235,18 @@ class BybitExecutor:
205
  price: float,
206
  tp_level: str,
207
  percent: float,
 
 
208
  ) -> dict[str, Any] | None:
209
  """Place a reduce-only Limit TP order with transient position-settle retries."""
210
- sym = symbol.upper().strip()
211
  payload = {
212
  "category": "linear",
213
  "symbol": sym,
214
  "side": opposite_side,
215
  "orderType": "Limit",
216
- "qty": str(qty),
217
- "price": str(price),
218
  "timeInForce": "GTC",
219
  "reduceOnly": True,
220
  "positionIdx": 0,
@@ -246,12 +278,14 @@ class BybitExecutor:
246
  tp2_qty: float,
247
  tp2_price: float,
248
  percent: float,
 
 
249
  ) -> dict[str, Any]:
250
  """
251
  Check a Limit entry order's fill state once and attach reduce-only TP2 upon Filled.
252
  Returns terminal/non-terminal status so both single checks and pollers can compose it.
253
  """
254
- sym = symbol.upper().strip()
255
  params = {"category": "linear", "symbol": sym, "orderId": entry_order_id}
256
  resp = await self._request("GET", "/v5/order/realtime", params=params)
257
  items = resp.get("result", {}).get("list", [])
@@ -264,6 +298,13 @@ class BybitExecutor:
264
 
265
  order_status = str(items[0].get("orderStatus", ""))
266
  if order_status == "Filled":
 
 
 
 
 
 
 
267
  tp2_order = await self._place_reduce_only_tp(
268
  symbol=sym,
269
  opposite_side=opposite_side,
@@ -271,6 +312,8 @@ class BybitExecutor:
271
  price=tp2_price,
272
  tp_level="TP2",
273
  percent=percent,
 
 
274
  )
275
  return {
276
  "status": "PLACED" if tp2_order else "FAILED",
@@ -287,7 +330,7 @@ class BybitExecutor:
287
 
288
  async def get_open_position(self, symbol: str) -> dict[str, Any] | None:
289
  """Fetch active Bybit linear position for symbol (returns None if size == 0)."""
290
- sym = symbol.upper().strip()
291
  resp = await self._request("GET", "/v5/position/list", params={"category": "linear", "symbol": sym})
292
  items = resp.get("result", {}).get("list", [])
293
  for item in items:
@@ -307,7 +350,7 @@ class BybitExecutor:
307
  """
308
  Move position Stop Loss to avg_entry_price ± 6 bps fee-buffer rounded to tick_size.
309
  """
310
- sym = symbol.upper().strip()
311
  inst = await self.get_instrument_info(sym)
312
  tick_size = inst["tick_size"]
313
  is_buy = side.upper() in ("BUY", "LONG")
@@ -317,7 +360,7 @@ class BybitExecutor:
317
  "category": "linear",
318
  "symbol": sym,
319
  "positionIdx": 0,
320
- "stopLoss": str(rounded_be_sl),
321
  "slTriggerBy": "MarkPrice",
322
  }
323
  await self._request("POST", "/v5/position/trading-stop", json_body=payload)
@@ -350,7 +393,7 @@ class BybitExecutor:
350
  """
351
  Execute trade setup on Bybit V5 with bracket Stop Loss and custom split TP1/TP2.
352
  """
353
- sym = symbol.upper().strip()
354
  side_norm = "Buy" if side.upper() in ("BUY", "LONG") else "Sell"
355
  opposite_side = "Sell" if side_norm == "Buy" else "Buy"
356
 
@@ -369,7 +412,8 @@ class BybitExecutor:
369
  if not calc_price or calc_price <= 0:
370
  # Fallback: fetch current ticker price
371
  ticker_data = await self._request("GET", "/v5/market/tickers", {"category": "linear", "symbol": sym})
372
- calc_price = float(ticker_data.get("result", {}).get("list", [{}])[0].get("lastPrice", 0.0))
 
373
  if calc_price <= 0:
374
  raise ValueError(f"Tidak dapat menentukan harga acuan untuk {sym}.")
375
 
@@ -412,14 +456,14 @@ class BybitExecutor:
412
  "symbol": sym,
413
  "side": side_norm,
414
  "orderType": "Market" if order_type.upper() == "MARKET" else "Limit",
415
- "qty": str(total_qty),
416
  "timeInForce": "GTC",
417
  "positionIdx": 0, # One-way mode
418
- "stopLoss": str(rounded_sl),
419
  "slTriggerBy": "MarkPrice",
420
  }
421
 
422
- # Calculate TP split quantities
423
  tp1_pct = max(10.0, min(float(tp1_percent), 100.0))
424
  if tp1_pct >= 99.0 or not rounded_tp2:
425
  tp1_qty = total_qty
@@ -427,20 +471,21 @@ class BybitExecutor:
427
  else:
428
  raw_tp1_qty = total_qty * (tp1_pct / 100.0)
429
  tp1_qty = self._round_step(raw_tp1_qty, qty_step)
430
- tp2_qty = self._round_step(total_qty - tp1_qty, qty_step)
 
431
  if tp1_qty < min_qty or tp2_qty < min_qty:
432
  tp1_qty = total_qty
433
  tp2_qty = 0.0
434
 
435
  # For Limit orders, attach takeProfit directly to the order (with Partial sizing if split)
436
  if order_type.upper() == "LIMIT":
437
- order_payload["takeProfit"] = str(rounded_tp1)
438
  order_payload["tpTriggerBy"] = "MarkPrice"
439
  if tp2_qty > 0:
440
  order_payload["tpslMode"] = "Partial"
441
- order_payload["tpSize"] = str(tp1_qty)
442
- if entry_price:
443
- order_payload["price"] = str(self._round_tick(entry_price, tick_size))
444
 
445
  logger.info("[%s] Sending Bybit Entry order: %s", sym, order_payload)
446
  entry_resp = await self._request("POST", "/v5/order/create", json_body=order_payload)
@@ -495,6 +540,8 @@ class BybitExecutor:
495
  price=rounded_tp1,
496
  tp_level="TP1",
497
  percent=100.0,
 
 
498
  )
499
  if placed:
500
  tp1_orders_info.append(placed)
@@ -507,6 +554,8 @@ class BybitExecutor:
507
  price=rounded_tp1,
508
  tp_level="TP1",
509
  percent=tp1_pct,
 
 
510
  )
511
  if placed_tp1:
512
  tp1_orders_info.append(placed_tp1)
@@ -519,6 +568,8 @@ class BybitExecutor:
519
  price=rounded_tp2,
520
  tp_level="TP2",
521
  percent=round(100.0 - tp1_pct, 1),
 
 
522
  )
523
  if placed_tp2:
524
  tp1_orders_info.append(placed_tp2)
@@ -561,7 +612,7 @@ async def watch_position_tp1_breakeven(
561
  Supports both explicit reduce-only TP1 order IDs (Market entry) and bound Limit TP1 triggers (10%-99% split).
562
  """
563
  watcher = BybitExecutor(api_key=api_key, api_secret=api_secret, mode=mode, proxy_url=proxy_url)
564
- sym = symbol.upper().strip()
565
  is_bound = not tp1_order_id or str(tp1_order_id).startswith("bound-")
566
  threshold_size = max(0.0, float(total_qty) - (0.5 * float(tp1_qty)))
567
  try:
 
12
  import logging
13
  import math
14
  import os
15
+ from decimal import Decimal, InvalidOperation, ROUND_DOWN, ROUND_HALF_UP
16
  from typing import Any
17
  from urllib.parse import urlencode
18
 
 
58
  async def close(self) -> None:
59
  await self._client.aclose()
60
 
61
+ @staticmethod
62
+ def _clean_symbol(symbol: str) -> str:
63
+ """Normalize perpetual pair formatting (e.g. BTC/USDT, btc-usdt -> BTCUSDT)."""
64
+ return symbol.upper().strip().replace("/", "").replace("-", "")
65
+
66
  def _generate_signature(self, timestamp: str, payload_str: str) -> str:
67
  """Bybit V5 HMAC-SHA256 signature generator."""
68
  param_str = f"{timestamp}{self.api_key}{self.recv_window}{payload_str}"
 
83
  }
84
 
85
  if method.upper() == "GET":
86
+ sorted_items = sorted((params or {}).items()) if params else []
87
+ query_str = urlencode(sorted_items) if sorted_items else ""
88
  sign = self._generate_signature(timestamp, query_str)
89
  headers["X-BAPI-SIGN"] = sign
90
+ req_path = f"{path}?{query_str}" if query_str else path
91
+ resp = await self._client.get(req_path, headers=headers)
92
  else:
93
  body_str = json.dumps(json_body, separators=(",", ":")) if json_body else ""
94
  sign = self._generate_signature(timestamp, body_str)
 
117
  async def get_wallet_balance(self) -> dict[str, Any]:
118
  """Fetch Unified/Futures USDT available balance and total equity."""
119
  data = await self._request("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED"})
120
+ acct_list = data.get("result", {}).get("list") or []
121
+ acct_item = acct_list[0] if acct_list else {}
122
  coins = acct_item.get("coin", [])
123
  usdt_info = next((c for c in coins if c.get("coin") == "USDT"), {})
124
  acct_equity = float(acct_item.get("totalEquity") or 0.0)
 
135
 
136
  async def get_instrument_info(self, symbol: str) -> dict[str, Any]:
137
  """Fetch contract precision, tickSize, and lotSize."""
138
+ sym = self._clean_symbol(symbol)
139
  data = await self._request("GET", "/v5/market/instruments-info", {
140
  "category": "linear",
141
  "symbol": sym,
 
162
 
163
  async def set_leverage(self, symbol: str, leverage: int) -> bool:
164
  """Set cross/isolated leverage for linear contract."""
165
+ sym = self._clean_symbol(symbol)
166
  lev_str = str(max(1, min(leverage, 100)))
167
  try:
168
  await self._request("POST", "/v5/position/set-leverage", json_body={
 
190
  return len(s.split(".")[1])
191
  return 0
192
 
193
+ @classmethod
194
+ def _format_num(cls, value: float, step_or_tick: float | None = None) -> str:
195
+ """Format price/qty as a plain decimal string without scientific notation."""
196
+ num = 0.0 if value == 0 else float(value)
197
+ if step_or_tick and step_or_tick > 0:
198
+ precision = cls._get_precision(step_or_tick)
199
+ return f"{num:.{precision}f}"
200
+ return format(Decimal(str(num)), "f")
201
+
202
  @classmethod
203
  def _round_step(cls, value: float, step: float) -> float:
204
+ """Round down value to the nearest step using Decimal to avoid IEEE 754 truncation loss."""
205
  if step <= 0:
206
  return value
207
  precision = cls._get_precision(step)
208
+ try:
209
+ d_val = Decimal(str(value))
210
+ d_step = Decimal(str(step))
211
+ steps = (d_val / d_step).to_integral_value(rounding=ROUND_DOWN)
212
+ return round(float(steps * d_step), precision)
213
+ except (InvalidOperation, ZeroDivisionError):
214
+ return round(math.floor((value / step) + 1e-9) * step, precision)
215
 
216
  @classmethod
217
  def _round_tick(cls, value: float, tick: float) -> float:
218
+ """Round price to the nearest tick using Decimal precision."""
219
  if tick <= 0:
220
  return value
221
  precision = cls._get_precision(tick)
222
+ try:
223
+ d_val = Decimal(str(value))
224
+ d_tick = Decimal(str(tick))
225
+ ticks = (d_val / d_tick).to_integral_value(rounding=ROUND_HALF_UP)
226
+ return round(float(ticks * d_tick), precision)
227
+ except (InvalidOperation, ZeroDivisionError):
228
+ return round(round(value / tick) * tick, precision)
229
 
230
  async def _place_reduce_only_tp(
231
  self,
 
235
  price: float,
236
  tp_level: str,
237
  percent: float,
238
+ qty_step: float | None = None,
239
+ tick_size: float | None = None,
240
  ) -> dict[str, Any] | None:
241
  """Place a reduce-only Limit TP order with transient position-settle retries."""
242
+ sym = self._clean_symbol(symbol)
243
  payload = {
244
  "category": "linear",
245
  "symbol": sym,
246
  "side": opposite_side,
247
  "orderType": "Limit",
248
+ "qty": self._format_num(qty, qty_step),
249
+ "price": self._format_num(price, tick_size),
250
  "timeInForce": "GTC",
251
  "reduceOnly": True,
252
  "positionIdx": 0,
 
278
  tp2_qty: float,
279
  tp2_price: float,
280
  percent: float,
281
+ qty_step: float | None = None,
282
+ tick_size: float | None = None,
283
  ) -> dict[str, Any]:
284
  """
285
  Check a Limit entry order's fill state once and attach reduce-only TP2 upon Filled.
286
  Returns terminal/non-terminal status so both single checks and pollers can compose it.
287
  """
288
+ sym = self._clean_symbol(symbol)
289
  params = {"category": "linear", "symbol": sym, "orderId": entry_order_id}
290
  resp = await self._request("GET", "/v5/order/realtime", params=params)
291
  items = resp.get("result", {}).get("list", [])
 
298
 
299
  order_status = str(items[0].get("orderStatus", ""))
300
  if order_status == "Filled":
301
+ if qty_step is None or tick_size is None:
302
+ try:
303
+ inst = await self.get_instrument_info(sym)
304
+ qty_step = qty_step or inst.get("qty_step")
305
+ tick_size = tick_size or inst.get("tick_size")
306
+ except Exception:
307
+ pass
308
  tp2_order = await self._place_reduce_only_tp(
309
  symbol=sym,
310
  opposite_side=opposite_side,
 
312
  price=tp2_price,
313
  tp_level="TP2",
314
  percent=percent,
315
+ qty_step=qty_step,
316
+ tick_size=tick_size,
317
  )
318
  return {
319
  "status": "PLACED" if tp2_order else "FAILED",
 
330
 
331
  async def get_open_position(self, symbol: str) -> dict[str, Any] | None:
332
  """Fetch active Bybit linear position for symbol (returns None if size == 0)."""
333
+ sym = self._clean_symbol(symbol)
334
  resp = await self._request("GET", "/v5/position/list", params={"category": "linear", "symbol": sym})
335
  items = resp.get("result", {}).get("list", [])
336
  for item in items:
 
350
  """
351
  Move position Stop Loss to avg_entry_price ± 6 bps fee-buffer rounded to tick_size.
352
  """
353
+ sym = self._clean_symbol(symbol)
354
  inst = await self.get_instrument_info(sym)
355
  tick_size = inst["tick_size"]
356
  is_buy = side.upper() in ("BUY", "LONG")
 
360
  "category": "linear",
361
  "symbol": sym,
362
  "positionIdx": 0,
363
+ "stopLoss": self._format_num(rounded_be_sl, tick_size),
364
  "slTriggerBy": "MarkPrice",
365
  }
366
  await self._request("POST", "/v5/position/trading-stop", json_body=payload)
 
393
  """
394
  Execute trade setup on Bybit V5 with bracket Stop Loss and custom split TP1/TP2.
395
  """
396
+ sym = self._clean_symbol(symbol)
397
  side_norm = "Buy" if side.upper() in ("BUY", "LONG") else "Sell"
398
  opposite_side = "Sell" if side_norm == "Buy" else "Buy"
399
 
 
412
  if not calc_price or calc_price <= 0:
413
  # Fallback: fetch current ticker price
414
  ticker_data = await self._request("GET", "/v5/market/tickers", {"category": "linear", "symbol": sym})
415
+ ticker_list = ticker_data.get("result", {}).get("list") or []
416
+ calc_price = float((ticker_list[0] if ticker_list else {}).get("lastPrice") or 0.0)
417
  if calc_price <= 0:
418
  raise ValueError(f"Tidak dapat menentukan harga acuan untuk {sym}.")
419
 
 
456
  "symbol": sym,
457
  "side": side_norm,
458
  "orderType": "Market" if order_type.upper() == "MARKET" else "Limit",
459
+ "qty": self._format_num(total_qty, qty_step),
460
  "timeInForce": "GTC",
461
  "positionIdx": 0, # One-way mode
462
+ "stopLoss": self._format_num(rounded_sl, tick_size),
463
  "slTriggerBy": "MarkPrice",
464
  }
465
 
466
+ # Calculate TP split quantities using Decimal subtraction to prevent IEEE 754 precision loss
467
  tp1_pct = max(10.0, min(float(tp1_percent), 100.0))
468
  if tp1_pct >= 99.0 or not rounded_tp2:
469
  tp1_qty = total_qty
 
471
  else:
472
  raw_tp1_qty = total_qty * (tp1_pct / 100.0)
473
  tp1_qty = self._round_step(raw_tp1_qty, qty_step)
474
+ raw_rem_qty = float(Decimal(str(total_qty)) - Decimal(str(tp1_qty)))
475
+ tp2_qty = self._round_step(max(0.0, raw_rem_qty), qty_step)
476
  if tp1_qty < min_qty or tp2_qty < min_qty:
477
  tp1_qty = total_qty
478
  tp2_qty = 0.0
479
 
480
  # For Limit orders, attach takeProfit directly to the order (with Partial sizing if split)
481
  if order_type.upper() == "LIMIT":
482
+ order_payload["takeProfit"] = self._format_num(rounded_tp1, tick_size)
483
  order_payload["tpTriggerBy"] = "MarkPrice"
484
  if tp2_qty > 0:
485
  order_payload["tpslMode"] = "Partial"
486
+ order_payload["tpSize"] = self._format_num(tp1_qty, qty_step)
487
+ limit_px_val = entry_price if (entry_price and entry_price > 0) else calc_price
488
+ order_payload["price"] = self._format_num(self._round_tick(limit_px_val, tick_size), tick_size)
489
 
490
  logger.info("[%s] Sending Bybit Entry order: %s", sym, order_payload)
491
  entry_resp = await self._request("POST", "/v5/order/create", json_body=order_payload)
 
540
  price=rounded_tp1,
541
  tp_level="TP1",
542
  percent=100.0,
543
+ qty_step=qty_step,
544
+ tick_size=tick_size,
545
  )
546
  if placed:
547
  tp1_orders_info.append(placed)
 
554
  price=rounded_tp1,
555
  tp_level="TP1",
556
  percent=tp1_pct,
557
+ qty_step=qty_step,
558
+ tick_size=tick_size,
559
  )
560
  if placed_tp1:
561
  tp1_orders_info.append(placed_tp1)
 
568
  price=rounded_tp2,
569
  tp_level="TP2",
570
  percent=round(100.0 - tp1_pct, 1),
571
+ qty_step=qty_step,
572
+ tick_size=tick_size,
573
  )
574
  if placed_tp2:
575
  tp1_orders_info.append(placed_tp2)
 
612
  Supports both explicit reduce-only TP1 order IDs (Market entry) and bound Limit TP1 triggers (10%-99% split).
613
  """
614
  watcher = BybitExecutor(api_key=api_key, api_secret=api_secret, mode=mode, proxy_url=proxy_url)
615
+ sym = BybitExecutor._clean_symbol(symbol)
616
  is_bound = not tp1_order_id or str(tp1_order_id).startswith("bound-")
617
  threshold_size = max(0.0, float(total_qty) - (0.5 * float(tp1_qty)))
618
  try:
backend/engine/fake_detector.py CHANGED
@@ -33,15 +33,18 @@ def _wick_sweep_detected(candles: list[dict]) -> tuple[bool, str]:
33
  # Evaluate completed candles only to confirm real wick sweep and close-back
34
  recent = candles[-4:-1] if len(candles) >= 4 else candles[:-1]
35
  for c in recent:
36
- close = c.get("close", 0)
37
- if close <= 0:
 
 
 
38
  continue
39
- rng = c["high"] - c["low"]
40
  if rng <= 0 or (rng / close) < WICK_RANGE_MIN_PCT:
41
  continue
42
 
43
- upper_wick = c["high"] - max(c["close"], c["open"])
44
- lower_wick = min(c["close"], c["open"]) - c["low"]
45
 
46
  if (upper_wick / rng) > WICK_DOMINANCE_RATIO:
47
  return True, "upper_wick_sweep (Liquidity Grab at Highs)"
@@ -56,7 +59,7 @@ def _wash_trade_detected(candles: list[dict]) -> bool:
56
  if len(candles) < 20:
57
  return False
58
 
59
- volumes = [c["volume"] for c in candles[:-2]]
60
  if not volumes:
61
  return False
62
  avg_vol = sum(volumes) / len(volumes)
@@ -66,9 +69,12 @@ def _wash_trade_detected(candles: list[dict]) -> bool:
66
  # Check the last completed candles (candles[-3] and candles[-2]), excluding the incomplete forming candle candles[-1]
67
  candidates = [candles[-3], candles[-2]] if len(candles) >= 21 else [candles[-2]]
68
  for cand in candidates:
69
- if cand["volume"] > avg_vol * MIN_VOLUME_SPIKE_MULTIPLIER:
70
- if cand["open"] > 0:
71
- price_move_pct = abs(cand["close"] - cand["open"]) / cand["open"]
 
 
 
72
  if price_move_pct < MAX_PRICE_MOVE_FOR_WASHTRADING:
73
  return True
74
  return False
@@ -85,8 +91,8 @@ def _orderbook_imbalance_detected(orderbook: dict | None, cvd_matches_price: boo
85
  return False, ""
86
 
87
  try:
88
- bid_vol = sum(float(p) * float(q) for p, q in bids[:20])
89
- ask_vol = sum(float(p) * float(q) for p, q in asks[:20])
90
  except (ValueError, TypeError, IndexError):
91
  return False, ""
92
  total_vol = bid_vol + ask_vol
 
33
  # Evaluate completed candles only to confirm real wick sweep and close-back
34
  recent = candles[-4:-1] if len(candles) >= 4 else candles[:-1]
35
  for c in recent:
36
+ high = c.get("high")
37
+ low = c.get("low")
38
+ open_p = c.get("open")
39
+ close = float(c.get("close") or 0)
40
+ if high is None or low is None or open_p is None or close <= 0:
41
  continue
42
+ rng = float(high) - float(low)
43
  if rng <= 0 or (rng / close) < WICK_RANGE_MIN_PCT:
44
  continue
45
 
46
+ upper_wick = float(high) - max(close, float(open_p))
47
+ lower_wick = min(close, float(open_p)) - float(low)
48
 
49
  if (upper_wick / rng) > WICK_DOMINANCE_RATIO:
50
  return True, "upper_wick_sweep (Liquidity Grab at Highs)"
 
59
  if len(candles) < 20:
60
  return False
61
 
62
+ volumes = [float(c["volume"]) for c in candles[:-2] if c.get("volume") is not None]
63
  if not volumes:
64
  return False
65
  avg_vol = sum(volumes) / len(volumes)
 
69
  # Check the last completed candles (candles[-3] and candles[-2]), excluding the incomplete forming candle candles[-1]
70
  candidates = [candles[-3], candles[-2]] if len(candles) >= 21 else [candles[-2]]
71
  for cand in candidates:
72
+ cand_vol = float(cand.get("volume") or 0)
73
+ cand_open = float(cand.get("open") or 0)
74
+ cand_close = float(cand.get("close") or 0)
75
+ if cand_vol > avg_vol * MIN_VOLUME_SPIKE_MULTIPLIER:
76
+ if cand_open > 0:
77
+ price_move_pct = abs(cand_close - cand_open) / cand_open
78
  if price_move_pct < MAX_PRICE_MOVE_FOR_WASHTRADING:
79
  return True
80
  return False
 
91
  return False, ""
92
 
93
  try:
94
+ bid_vol = sum(float(lvl[0]) * float(lvl[1]) for lvl in (bids or [])[:20] if lvl)
95
+ ask_vol = sum(float(lvl[0]) * float(lvl[1]) for lvl in (asks or [])[:20] if lvl)
96
  except (ValueError, TypeError, IndexError):
97
  return False, ""
98
  total_vol = bid_vol + ask_vol
backend/engine/mtf_analyzer.py CHANGED
@@ -12,16 +12,30 @@ from typing import Any
12
  logger = logging.getLogger(__name__)
13
 
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  def _atr(candles: list[dict], period: int = 14) -> float:
16
  """Average True Range over the most recent `period` candles."""
17
- if len(candles) < 2:
 
18
  return 0.0
19
- recent = candles[-(period + 1):]
20
  trs = []
21
  for i in range(1, len(recent)):
22
- high = recent[i]["high"]
23
- low = recent[i]["low"]
24
- prev_close = recent[i - 1]["close"]
25
  tr = max(high - low, abs(high - prev_close), abs(low - prev_close))
26
  trs.append(tr)
27
  return sum(trs) / len(trs) if trs else 0.0
@@ -36,16 +50,17 @@ def _atr_ratio(candles: list[dict], period: int = 14, lookback: int = 100) -> fl
36
  0.45–0.8 → compressed / ranging (15M sweep)
37
  < 0.45 → ultra-low volatility / micro squeeze (5M)
38
  """
39
- if len(candles) < period + 1:
 
40
  return 1.0
41
 
42
- current_atr = _atr(candles, period)
43
 
44
  # Compute rolling ATRs across available candles
45
  rolling_atrs = []
46
- step = max(1, len(candles) // 10)
47
- for start in range(0, len(candles) - period, step):
48
- chunk = candles[start: start + period + 1]
49
  a = _atr(chunk, period)
50
  if a > 0:
51
  rolling_atrs.append(a)
@@ -63,12 +78,13 @@ def _calc_atr_stretch(candles: list[dict], ema_period: int = 9, atr_period: int
63
  (close - EMA(ema_period)) / ATR(atr_period)
64
  Positive = stretched above EMA, Negative = stretched below EMA.
65
  """
66
- if not candles or len(candles) < atr_period + 1:
 
67
  return 0.0
68
- atr_val = _atr(candles, atr_period)
69
  if atr_val <= 0:
70
  return 0.0
71
- closes = [float(c["close"]) for c in candles if "close" in c]
72
  if not closes:
73
  return 0.0
74
  ema_val = _calc_ema(closes, ema_period)
@@ -108,22 +124,23 @@ def _market_structure(candles: list[dict]) -> str:
108
  4. EMA(20) / EMA(9) trend confluence confirmation
109
  5. Mixed / conflicting = 'ranging'
110
  """
111
- if len(candles) < 5:
 
112
  return "ranging"
113
 
114
- closes = [c["close"] for c in candles]
115
- highs = [c["high"] for c in candles]
116
- lows = [c["low"] for c in candles]
117
 
118
  # Find swing highs and swing lows across the last 30 candles
119
- window = min(len(candles), 30)
120
- start_idx = len(candles) - window
121
 
122
  # Pass 1: 5-bar Bill Williams fractals (robust against micro-noise)
123
  swing_highs: list[float] = []
124
  swing_lows: list[float] = []
125
 
126
- for i in range(start_idx + 2, len(candles) - 2):
127
  if (highs[i] >= highs[i - 1] and highs[i] >= highs[i - 2] and
128
  highs[i] >= highs[i + 1] and highs[i] >= highs[i + 2]):
129
  swing_highs.append(highs[i])
@@ -135,7 +152,7 @@ def _market_structure(candles: list[dict]) -> str:
135
  if len(swing_highs) < 2 or len(swing_lows) < 2:
136
  swing_highs.clear()
137
  swing_lows.clear()
138
- for i in range(start_idx + 1, len(candles) - 1):
139
  if highs[i] >= highs[i - 1] and highs[i] >= highs[i + 1]:
140
  swing_highs.append(highs[i])
141
  if lows[i] <= lows[i - 1] and lows[i] <= lows[i + 1]:
 
12
  logger = logging.getLogger(__name__)
13
 
14
 
15
+ def _valid_ohlc_candles(candles: list[dict]) -> list[dict]:
16
+ """Filter candles to rows that contain non-null high, low, and close values."""
17
+ if not candles:
18
+ return []
19
+ return [
20
+ c for c in candles
21
+ if isinstance(c, dict)
22
+ and c.get("high") is not None
23
+ and c.get("low") is not None
24
+ and c.get("close") is not None
25
+ ]
26
+
27
+
28
  def _atr(candles: list[dict], period: int = 14) -> float:
29
  """Average True Range over the most recent `period` candles."""
30
+ valid = _valid_ohlc_candles(candles)
31
+ if len(valid) < 2:
32
  return 0.0
33
+ recent = valid[-(period + 1):]
34
  trs = []
35
  for i in range(1, len(recent)):
36
+ high = float(recent[i]["high"])
37
+ low = float(recent[i]["low"])
38
+ prev_close = float(recent[i - 1]["close"])
39
  tr = max(high - low, abs(high - prev_close), abs(low - prev_close))
40
  trs.append(tr)
41
  return sum(trs) / len(trs) if trs else 0.0
 
50
  0.45–0.8 → compressed / ranging (15M sweep)
51
  < 0.45 → ultra-low volatility / micro squeeze (5M)
52
  """
53
+ valid = _valid_ohlc_candles(candles)
54
+ if len(valid) < period + 1:
55
  return 1.0
56
 
57
+ current_atr = _atr(valid, period)
58
 
59
  # Compute rolling ATRs across available candles
60
  rolling_atrs = []
61
+ step = max(1, len(valid) // 10)
62
+ for start in range(0, len(valid) - period, step):
63
+ chunk = valid[start: start + period + 1]
64
  a = _atr(chunk, period)
65
  if a > 0:
66
  rolling_atrs.append(a)
 
78
  (close - EMA(ema_period)) / ATR(atr_period)
79
  Positive = stretched above EMA, Negative = stretched below EMA.
80
  """
81
+ valid = _valid_ohlc_candles(candles)
82
+ if len(valid) < atr_period + 1:
83
  return 0.0
84
+ atr_val = _atr(valid, atr_period)
85
  if atr_val <= 0:
86
  return 0.0
87
+ closes = [float(c["close"]) for c in valid]
88
  if not closes:
89
  return 0.0
90
  ema_val = _calc_ema(closes, ema_period)
 
124
  4. EMA(20) / EMA(9) trend confluence confirmation
125
  5. Mixed / conflicting = 'ranging'
126
  """
127
+ valid = _valid_ohlc_candles(candles)
128
+ if len(valid) < 5:
129
  return "ranging"
130
 
131
+ closes = [float(c["close"]) for c in valid]
132
+ highs = [float(c["high"]) for c in valid]
133
+ lows = [float(c["low"]) for c in valid]
134
 
135
  # Find swing highs and swing lows across the last 30 candles
136
+ window = min(len(valid), 30)
137
+ start_idx = len(valid) - window
138
 
139
  # Pass 1: 5-bar Bill Williams fractals (robust against micro-noise)
140
  swing_highs: list[float] = []
141
  swing_lows: list[float] = []
142
 
143
+ for i in range(start_idx + 2, len(valid) - 2):
144
  if (highs[i] >= highs[i - 1] and highs[i] >= highs[i - 2] and
145
  highs[i] >= highs[i + 1] and highs[i] >= highs[i + 2]):
146
  swing_highs.append(highs[i])
 
152
  if len(swing_highs) < 2 or len(swing_lows) < 2:
153
  swing_highs.clear()
154
  swing_lows.clear()
155
+ for i in range(start_idx + 1, len(valid) - 1):
156
  if highs[i] >= highs[i - 1] and highs[i] >= highs[i + 1]:
157
  swing_highs.append(highs[i])
158
  if lows[i] <= lows[i - 1] and lows[i] <= lows[i + 1]:
backend/engine/outcome_evaluator.py CHANGED
@@ -28,7 +28,8 @@ def _to_epoch_ms(val: Any) -> int:
28
  if val is None:
29
  return 0
30
  if isinstance(val, datetime):
31
- return int(val.timestamp() * 1000)
 
32
  if isinstance(val, (int, float)):
33
  v = float(val)
34
  if v >= 100_000_000_000:
@@ -37,6 +38,8 @@ def _to_epoch_ms(val: Any) -> int:
37
  if isinstance(val, str):
38
  try:
39
  dt = datetime.fromisoformat(val.replace("Z", "+00:00"))
 
 
40
  return int(dt.timestamp() * 1000)
41
  except ValueError:
42
  try:
@@ -46,6 +49,15 @@ def _to_epoch_ms(val: Any) -> int:
46
  return 0
47
 
48
 
 
 
 
 
 
 
 
 
 
49
  def evaluate_prediction_against_candles(
50
  pred: dict[str, Any],
51
  candles: list[dict[str, Any]],
@@ -60,11 +72,13 @@ def evaluate_prediction_against_candles(
60
  return None
61
 
62
  try:
63
- entry = float(pred.get("entry_price", pred.get("entry")))
64
- sl = float(pred["stop_loss"])
65
- tp1 = float(pred.get("tp1", pred.get("take_profit_1")))
66
- tp2 = float(pred.get("tp2", pred.get("take_profit_2")))
67
- except (KeyError, TypeError, ValueError):
 
 
68
  return None
69
 
70
  risk = abs(entry - sl)
@@ -90,8 +104,10 @@ def evaluate_prediction_against_candles(
90
 
91
  tp1_hit = False
92
  for _, bar in window_bars:
93
- high = float(bar.get("high", 0.0))
94
- low = float(bar.get("low", 0.0))
 
 
95
 
96
  if not tp1_hit:
97
  if direction == "LONG":
@@ -130,7 +146,8 @@ def evaluate_prediction_against_candles(
130
  if not window_bars:
131
  return None
132
 
133
- last_close = float(window_bars[-1][1].get("close", entry))
 
134
  close_r = ((last_close - entry) / risk) if direction == "LONG" else ((entry - last_close) / risk)
135
  if tp1_hit:
136
  return ("TP1_OPEN", last_close, round(0.5 * tp1_r + 0.5 * close_r, 3))
@@ -237,14 +254,14 @@ async def async_evaluate_pending_predictions(binance_client: Any, bybit_client:
237
  tf = cfg["eval_tf"]
238
  limit = int(cfg["limit"])
239
  candles: list[dict[str, Any]] = []
240
- if binance_client is not None:
241
- try:
242
- candles = await binance_client.fetch_ohlcv(symbol, tf, limit=limit) or []
243
- except Exception:
244
- candles = []
245
- if not candles and bybit_client is not None:
246
  try:
247
- candles = await bybit_client.fetch_ohlcv(symbol, tf, limit=limit) or []
248
  except Exception:
249
  candles = []
250
  if not candles:
 
28
  if val is None:
29
  return 0
30
  if isinstance(val, datetime):
31
+ dt = val if val.tzinfo is not None else val.replace(tzinfo=timezone.utc)
32
+ return int(dt.timestamp() * 1000)
33
  if isinstance(val, (int, float)):
34
  v = float(val)
35
  if v >= 100_000_000_000:
 
38
  if isinstance(val, str):
39
  try:
40
  dt = datetime.fromisoformat(val.replace("Z", "+00:00"))
41
+ if dt.tzinfo is None:
42
+ dt = dt.replace(tzinfo=timezone.utc)
43
  return int(dt.timestamp() * 1000)
44
  except ValueError:
45
  try:
 
49
  return 0
50
 
51
 
52
+ def _first_float(mapping: dict[str, Any], *keys: str) -> float | None:
53
+ """Return the first non-None numeric value across fallback keys."""
54
+ for k in keys:
55
+ val = mapping.get(k)
56
+ if val is not None:
57
+ return float(val)
58
+ return None
59
+
60
+
61
  def evaluate_prediction_against_candles(
62
  pred: dict[str, Any],
63
  candles: list[dict[str, Any]],
 
72
  return None
73
 
74
  try:
75
+ entry = _first_float(pred, "entry_price", "entry")
76
+ sl = _first_float(pred, "stop_loss")
77
+ tp1 = _first_float(pred, "tp1", "take_profit_1")
78
+ tp2 = _first_float(pred, "tp2", "take_profit_2")
79
+ if entry is None or sl is None or tp1 is None or tp2 is None:
80
+ return None
81
+ except (TypeError, ValueError):
82
  return None
83
 
84
  risk = abs(entry - sl)
 
104
 
105
  tp1_hit = False
106
  for _, bar in window_bars:
107
+ high = float(bar.get("high") or 0.0)
108
+ low = float(bar.get("low") or 0.0)
109
+ if high <= 0 or low <= 0:
110
+ continue
111
 
112
  if not tp1_hit:
113
  if direction == "LONG":
 
146
  if not window_bars:
147
  return None
148
 
149
+ valid_closes = [float(b["close"]) for _, b in window_bars if b.get("close") is not None]
150
+ last_close = valid_closes[-1] if valid_closes else entry
151
  close_r = ((last_close - entry) / risk) if direction == "LONG" else ((entry - last_close) / risk)
152
  if tp1_hit:
153
  return ("TP1_OPEN", last_close, round(0.5 * tp1_r + 0.5 * close_r, 3))
 
254
  tf = cfg["eval_tf"]
255
  limit = int(cfg["limit"])
256
  candles: list[dict[str, Any]] = []
257
+ for client in (binance_client, bybit_client):
258
+ if client is None or candles:
259
+ continue
260
+ ohlcv_fn = getattr(client, "get_ohlcv", None) or getattr(client, "fetch_ohlcv", None)
261
+ if not callable(ohlcv_fn):
262
+ continue
263
  try:
264
+ candles = await ohlcv_fn(symbol, tf, limit=limit) or []
265
  except Exception:
266
  candles = []
267
  if not candles:
backend/engine/predictive_engine.py CHANGED
@@ -77,8 +77,8 @@ def _compute_liquidation_magnets(
77
  "primary_magnet": "UPPER",
78
  }
79
 
80
- recent_highs = [c["high"] for c in candles if c.get("high", 0) > 0]
81
- recent_lows = [c["low"] for c in candles if c.get("low", 0) > 0]
82
 
83
  if not recent_highs or not recent_lows:
84
  upper = mark_price * 1.025
 
77
  "primary_magnet": "UPPER",
78
  }
79
 
80
+ recent_highs = [c["high"] for c in candles if (c.get("high") or 0) > 0]
81
+ recent_lows = [c["low"] for c in candles if (c.get("low") or 0) > 0]
82
 
83
  if not recent_highs or not recent_lows:
84
  upper = mark_price * 1.025
backend/engine/signal_engine.py CHANGED
@@ -186,10 +186,10 @@ def _is_half_rising(sorted_trades: list[dict], total_cvd: float) -> bool:
186
  first, second = _split_trades_by_midpoint(sorted_trades)
187
  if not first or not second:
188
  return total_cvd > 0
189
- h1_buy = sum(t.get("qty", 0.0) for t in first if not t.get("is_buyer_maker", False))
190
- h1_sell = sum(t.get("qty", 0.0) for t in first if t.get("is_buyer_maker", False))
191
- h2_buy = sum(t.get("qty", 0.0) for t in second if not t.get("is_buyer_maker", False))
192
- h2_sell = sum(t.get("qty", 0.0) for t in second if t.get("is_buyer_maker", False))
193
  h1_cvd, h2_cvd = h1_buy - h1_sell, h2_buy - h2_sell
194
  h1_rat = h1_cvd / (h1_buy + h1_sell) if (h1_buy + h1_sell) > 0 else 0.0
195
  h2_rat = h2_cvd / (h2_buy + h2_sell) if (h2_buy + h2_sell) > 0 else 0.0
@@ -314,8 +314,8 @@ def _compute_spot_futures_cvd(
314
  }
315
 
316
  if not spot_trades:
317
- fut_buy = sum(t.get("qty", 0.0) for t in futures_trades if not t.get("is_buyer_maker", False))
318
- fut_sell = sum(t.get("qty", 0.0) for t in futures_trades if t.get("is_buyer_maker", False))
319
  futures_cvd = fut_buy - fut_sell
320
  return {
321
  "value": f"Perp: {futures_cvd:+.1f} (No Spot)",
@@ -326,29 +326,29 @@ def _compute_spot_futures_cvd(
326
  }
327
 
328
  # Sort trades chronologically and intersect overlapping Spot/Futures time window when populated
329
- sorted_spot = sorted(spot_trades, key=lambda t: t.get("time", 0))
330
- sorted_fut = sorted(futures_trades, key=lambda t: t.get("time", 0))
331
 
332
- spot_times = [float(t.get("time", 0) or 0) for t in sorted_spot if float(t.get("time", 0) or 0) > 0]
333
- fut_times = [float(t.get("time", 0) or 0) for t in sorted_fut if float(t.get("time", 0) or 0) > 0]
334
  if spot_times and fut_times:
335
  overlap_start = max(spot_times[0], fut_times[0])
336
  overlap_end = min(spot_times[-1], fut_times[-1])
337
  if overlap_start < overlap_end:
338
- aligned_spot = [t for t in sorted_spot if overlap_start <= float(t.get("time", 0) or 0) <= overlap_end]
339
- aligned_fut = [t for t in sorted_fut if overlap_start <= float(t.get("time", 0) or 0) <= overlap_end]
340
  if len(aligned_spot) >= 5 and len(aligned_fut) >= 5:
341
  sorted_spot = aligned_spot
342
  sorted_fut = aligned_fut
343
 
344
- spot_buy = sum(t.get("qty", 0.0) for t in sorted_spot if not t.get("is_buyer_maker", False))
345
- spot_sell = sum(t.get("qty", 0.0) for t in sorted_spot if t.get("is_buyer_maker", False))
346
  spot_total = spot_buy + spot_sell
347
  spot_cvd = spot_buy - spot_sell
348
  spot_ratio = (spot_cvd / spot_total) if spot_total > 0 else 0.0
349
 
350
- fut_buy = sum(t.get("qty", 0.0) for t in sorted_fut if not t.get("is_buyer_maker", False))
351
- fut_sell = sum(t.get("qty", 0.0) for t in sorted_fut if t.get("is_buyer_maker", False))
352
  fut_total = fut_buy + fut_sell
353
  futures_cvd = fut_buy - fut_sell
354
  fut_ratio = (futures_cvd / fut_total) if fut_total > 0 else 0.0
@@ -495,40 +495,82 @@ def _compute_oi_divergence(
495
  ) -> dict[str, Any]:
496
  """
497
  Open Interest + Price divergence signal (OI-Weighted across Binance, Bybit, OKX, and Bitget).
498
-
499
- 1. Price↑ + OI↑ (>+0.05%) → Real Long Inflow (+1)
500
- 2. Price↑ + OI↓ (<-0.05%) → Short Covering Exhaustion / Weak Rally (-1)
501
- 3. Price↓ + OI↑ (>+0.05%) → Real Short Inflow (-1)
502
- 4. Price↓ + OI↓ (<-0.05%) → Long Liquidation / Squeeze Exhaustion Done (+1)
 
503
  5. Flat / Small changes → Neutral (0)
504
  """
505
  price_changes: list[float] = []
506
  price_weights: list[float] = []
 
 
507
  oi_changes: list[float] = []
508
  oi_weights: list[float] = []
 
 
 
 
509
 
510
  for exch in [binance_data, bybit_data, okx_data, bitget_data]:
511
  if not exch:
512
  continue
513
  w = _extract_venue_oi_weight(exch)
 
514
  # 15m candle price change %
515
- candles = exch.get("ohlcv", {}).get("15m", [])
516
- if len(candles) >= 2 and candles[-2]["close"] > 0:
517
- pc = (candles[-1]["close"] - candles[-2]["close"]) / candles[-2]["close"] * 100
 
 
518
  price_changes.append(pc)
519
  price_weights.append(w)
520
 
521
- # OI change %
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
522
  oi_data = exch.get("open_interest_data")
523
- if oi_data and oi_data.get("oi_change_pct") is not None:
524
- oi_changes.append(float(oi_data["oi_change_pct"]))
525
- oi_weights.append(w)
 
 
 
 
 
 
 
526
 
527
  if not price_changes:
528
- return {"value": "No Data", "score": 0, "label": "No Price Data"}
 
 
 
 
 
 
529
 
530
  avg_price_change = _oi_weighted_average(price_changes, price_weights)
531
  avg_oi_change = _oi_weighted_average(oi_changes, oi_weights) if oi_changes else 0.0
 
 
 
532
 
533
  # Robust threshold to filter sub-tick micro-noise on 15m timeframe:
534
  # Minimum 0.15% price displacement and 0.25% net Open Interest expansion/unwinding
@@ -569,11 +611,32 @@ def _compute_oi_divergence(
569
  direction_val = "Flat (Neutral)"
570
  label = "Balanced Market Flow"
571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
572
  return {
573
  "value": direction_val,
574
  "price_change_pct": round(avg_price_change, 4),
 
575
  "oi_change_pct": round(avg_oi_change, 4),
 
 
576
  "score": score,
 
 
577
  "label": label,
578
  }
579
 
@@ -588,12 +651,12 @@ def _compute_cvd(trades: list[dict]) -> dict[str, Any]:
588
  return {"value": 0, "delta_ratio": 0.0, "score": 0, "rising": False, "label": "No Trade Data"}
589
 
590
  # Sort trades chronologically (oldest to newest) to eliminate any exchange discrepancies
591
- sorted_trades = sorted(trades, key=lambda t: t.get("time", 0))
592
 
593
  buy_vol = 0.0
594
  sell_vol = 0.0
595
  for t in sorted_trades:
596
- qty = t.get("qty", 0.0)
597
  if t.get("is_buyer_maker", False):
598
  sell_vol += qty
599
  else:
@@ -640,12 +703,14 @@ def _compute_cross_exchange(
640
  Aligned exchanges confirm price consistency.
641
  """
642
  def _pct_change_5m(exch: dict) -> float | None:
643
- candles = exch.get("ohlcv", {}).get("5m", [])
644
  if len(candles) < 2:
645
  return None
646
- prev = candles[-2]["close"]
647
- curr = candles[-1]["close"]
648
- return (curr - prev) / prev * 100 if prev else None
 
 
649
 
650
  rates = {}
651
  if binance_data:
@@ -706,32 +771,89 @@ def _compute_ls_ratio(
706
  bitget_data: dict | None = None,
707
  ) -> dict[str, Any]:
708
  """
709
- Top-trader L/S ratio (OI-Weighted across Binance, Bybit, OKX, and Bitget).
 
 
710
  """
711
  long_ratios: list[float] = []
712
  weights: list[float] = []
 
 
 
 
 
713
  for exch in [binance_data, bybit_data, okx_data, bitget_data]:
714
  if exch and exch.get("ls_ratio_data"):
715
- lr = exch["ls_ratio_data"].get("long_ratio")
 
 
716
  if lr is not None:
717
  long_ratios.append(float(lr))
718
- weights.append(_extract_venue_oi_weight(exch))
 
 
 
 
 
 
 
 
719
 
720
  if not long_ratios:
721
- return {"top_trader": None, "retail": None, "score": 0, "label": "No Data"}
 
 
 
 
 
 
 
 
722
 
723
  avg_long = _oi_weighted_average(long_ratios, weights)
724
-
725
- if avg_long >= 0.62:
726
- score, label = -1, f"Crowded Retail Longs {avg_long:.1%} → Contrarian Short"
727
- elif avg_long <= 0.38:
728
- score, label = 1, f"Crowded Retail Shorts {avg_long:.1%} → Contrarian Long"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
729
  else:
730
- score, label = 0, f"Balanced L/S {avg_long:.1%}"
 
 
 
 
 
731
 
732
  return {
733
  "top_trader": round(avg_long, 4),
734
- "retail": None,
 
 
 
735
  "score": score,
736
  "label": label,
737
  }
@@ -846,7 +968,7 @@ def _compute_trade_plan(
846
  entry_high = mark_price + (0.05 * atr)
847
 
848
  # Structure-Based Invalidation Stop Loss: anchor to recent swing low if within [sl_min_pct, sl_max_pct]
849
- recent_lows = [c["low"] for c in ohlcv_1h[-20:] if c.get("low", 0) > 0] if ohlcv_1h else []
850
  if recent_lows:
851
  struct_low = min(recent_lows) - (0.2 * atr)
852
  if mark_price * long_struct_min <= struct_low <= mark_price * long_struct_max:
@@ -902,7 +1024,7 @@ def _compute_trade_plan(
902
  entry_high = mark_price + (0.35 * atr)
903
 
904
  # Structure-Based Invalidation Stop Loss: anchor to recent swing high if within [sl_min_pct, sl_max_pct]
905
- recent_highs = [c["high"] for c in ohlcv_1h[-20:] if c.get("high", 0) > 0] if ohlcv_1h else []
906
  if recent_highs:
907
  struct_high = max(recent_highs) + (0.2 * atr)
908
  if mark_price * short_struct_min <= struct_high <= mark_price * short_struct_max:
@@ -1231,56 +1353,178 @@ def _compute_price_extremes_24h(merged_ohlcv: dict, mark_price: float, symbol: s
1231
  }
1232
 
1233
 
1234
- def _compute_whale_order_flow(trades: list[dict], mark_price: float) -> dict[str, Any]:
 
 
 
 
 
 
1235
  """
1236
- Institutional Order Flow & Whale Block Trades Analysis.
1237
- Analyzes aggressive market taker buy/sell volume and large block orders.
 
 
 
 
1238
  """
1239
- if not trades or mark_price <= 0:
1240
- return {
1241
- "taker_buy_vol_usd": 0.0,
1242
- "taker_sell_vol_usd": 0.0,
1243
- "total_vol_usd": 0.0,
1244
- "taker_buy_pct": 50.0,
1245
- "taker_ratio": 1.0,
1246
- "whale_buy_count": 0,
1247
- "whale_sell_count": 0,
1248
- "whale_buy_vol_usd": 0.0,
1249
- "whale_sell_vol_usd": 0.0,
1250
- "largest_trade_usd": 0.0,
1251
- "largest_trade_side": "NONE",
1252
- "dynamic_threshold_usd": 5000.0,
1253
- "net_whale_threshold_usd": 5000.0,
1254
- "flow_verdict": "Order Flow Agregat Seimbang (Belum Ada Data Trades)",
1255
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1256
 
1257
  taker_buy_vol = 0.0
1258
  taker_sell_vol = 0.0
1259
  parsed_trades = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1260
 
1261
- for t in trades:
1262
- try:
1263
- px = float(t.get("price", 0.0))
1264
- qty = float(t.get("qty", 0.0))
1265
- if px <= 0 or qty <= 0:
 
 
 
 
 
 
 
 
 
 
 
1266
  continue
1267
- usd_val = px * qty
1268
- is_sell_taker = bool(t.get("is_buyer_maker", False))
1269
- parsed_trades.append((usd_val, is_sell_taker))
1270
- if is_sell_taker:
1271
- taker_sell_vol += usd_val
1272
- else:
1273
- taker_buy_vol += usd_val
1274
- except Exception:
1275
- continue
1276
 
1277
  if not parsed_trades:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1278
  return {
1279
- "taker_buy_vol_usd": 0.0,
1280
- "taker_sell_vol_usd": 0.0,
1281
- "total_vol_usd": 0.0,
1282
- "taker_buy_pct": 50.0,
1283
- "taker_ratio": 1.0,
1284
  "whale_buy_count": 0,
1285
  "whale_sell_count": 0,
1286
  "whale_buy_vol_usd": 0.0,
@@ -1289,7 +1533,28 @@ def _compute_whale_order_flow(trades: list[dict], mark_price: float) -> dict[str
1289
  "largest_trade_side": "NONE",
1290
  "dynamic_threshold_usd": 5000.0,
1291
  "net_whale_threshold_usd": 5000.0,
1292
- "flow_verdict": "Order Flow Agregat Seimbang",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1293
  }
1294
 
1295
  total_vol = taker_buy_vol + taker_sell_vol
@@ -1322,17 +1587,98 @@ def _compute_whale_order_flow(trades: list[dict], mark_price: float) -> dict[str
1322
  whale_buy_vol = sum(whale_buys)
1323
  whale_sell_vol = sum(whale_sells)
1324
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1325
  largest_val, largest_is_sell = max(parsed_trades, key=lambda x: x[0])
1326
  largest_side = "SELL" if largest_is_sell else "BUY"
1327
 
1328
- if len(whale_buys) > 0 and len(whale_sells) == 0:
 
 
 
 
1329
  verdict = f"Paus Agresif Sisi Beli: {len(whale_buys)} block buy (${whale_buy_vol:,.0f}) tanpa block sell tandingan!"
1330
  elif len(whale_sells) > 0 and len(whale_buys) == 0:
1331
  verdict = f"Paus Agresif Sisi Jual: {len(whale_sells)} block sell (${whale_sell_vol:,.0f}) tanpa block buy tandingan!"
1332
- elif whale_buy_vol > whale_sell_vol * 1.5:
1333
- 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)."
1334
- elif whale_sell_vol > whale_buy_vol * 1.5:
1335
- 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)."
 
 
 
 
 
 
 
 
1336
  elif buy_pct >= 58.0:
1337
  verdict = f"Taker Buy Dominan: {buy_pct:.1f}% volume taker agresif beli (Rasio {taker_ratio:.2f}x)."
1338
  elif buy_pct <= 42.0:
@@ -1354,6 +1700,27 @@ def _compute_whale_order_flow(trades: list[dict], mark_price: float) -> dict[str
1354
  "largest_trade_side": largest_side,
1355
  "dynamic_threshold_usd": round(threshold, 2),
1356
  "net_whale_threshold_usd": round(net_whale_threshold, 2),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1357
  "flow_verdict": verdict,
1358
  }
1359
 
@@ -1686,19 +2053,21 @@ class SignalEngine:
1686
  hl_mark_px = hyperliquid.get("mark_price") if hyperliquid else None
1687
  ref_mark_px = binance_mark or bybit_mark or bitget_mark or okx_mark or hl_mark_px or 0.0
1688
 
1689
- # CVD & Whale Order Flow: combine Binance, Bybit, OKX, and Bitget (normalized to canonical contract scale).
1690
  trades = []
1691
- for v_data, v_mark in [
1692
- (binance, binance_mark),
1693
- (bybit, bybit_mark),
1694
- (okx, okx_mark),
1695
- (bitget, bitget_mark),
 
1696
  ]:
1697
  if v_data and v_data.get("trades"):
1698
  v_trades = v_data["trades"]
1699
  sample_px = v_mark or (v_trades[0].get("price") if v_trades else None)
1700
  t_scale = _get_multiplier_scale(sample_px, ref_mark_px)
1701
- trades.extend(_normalize_trades_scale(v_trades, t_scale))
 
1702
 
1703
  cvd_signal = _compute_cvd(trades)
1704
 
@@ -1724,15 +2093,60 @@ class SignalEngine:
1724
  merged_ohlcv[tf] = candles
1725
 
1726
  mtf_result = mtf_analyzer.analyze(merged_ohlcv)
1727
- if horizon_thresholds is not None and not trades:
1728
  ref_cvd_bars = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or [])[-10:]
1729
- if ref_cvd_bars:
1730
- net_delta = sum(
1731
- ((float(b.get("close", 0.0)) - float(b.get("open", 0.0))) / max(float(b.get("high", 0.0)) - float(b.get("low", 0.0)), 1e-9))
1732
- * float(b.get("volume", 0.0) or 1.0)
1733
- for b in ref_cvd_bars
1734
- )
1735
- tot_vol = sum(float(b.get("volume", 0.0) or 1.0) for b in ref_cvd_bars)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1736
  if tot_vol > 0:
1737
  ratio = net_delta / tot_vol
1738
  if ratio > 0.15:
@@ -1856,25 +2270,42 @@ class SignalEngine:
1856
  )
1857
  if mark_price <= 0 and merged_ohlcv:
1858
  for tf in ["15m", "1h", "5m"]:
1859
- if tf in merged_ohlcv and merged_ohlcv[tf]:
1860
- candidate_px = merged_ohlcv[tf][-1].get("close", 0.0)
 
 
 
 
 
 
 
1861
  if candidate_px > 0:
1862
  mark_price = candidate_px
1863
  break
 
 
1864
 
1865
  # Compute Orderbook Resting Skew & Whale Block Order Flow for Confluence Scoring
1866
  ob_skew = _compute_orderbook_skew(orderbook, mark_price)
1867
- whale_flow_data = _compute_whale_order_flow(trades, mark_price)
 
 
 
 
 
 
1868
 
1869
- whale_score = 0
 
1870
  w_buy = whale_flow_data.get("whale_buy_vol_usd", 0.0)
1871
  w_sell = whale_flow_data.get("whale_sell_vol_usd", 0.0)
1872
  t_buy_pct = whale_flow_data.get("taker_buy_pct", 50.0)
1873
  dyn_whale_thresh = float(whale_flow_data.get("dynamic_threshold_usd", 25000.0) or 25000.0)
1874
- if w_buy > w_sell * 1.4 and w_buy >= dyn_whale_thresh:
1875
- whale_score = 1
1876
- elif w_sell > w_buy * 1.4 and w_sell >= dyn_whale_thresh:
1877
- whale_score = -1
 
1878
 
1879
  whale_factor = {
1880
  "score": whale_score,
@@ -1883,6 +2314,20 @@ class SignalEngine:
1883
  "taker_ratio": whale_flow_data.get("taker_ratio", 1.0),
1884
  "whale_buy_vol_usd": w_buy,
1885
  "whale_sell_vol_usd": w_sell,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1886
  }
1887
 
1888
  ob_factor = {
@@ -1913,15 +2358,37 @@ class SignalEngine:
1913
  regime_name = mtf_result.get("regime", mtf_result.get("market_condition", "trending"))
1914
  h_thresh_map = horizon_thresholds or {}
1915
 
1916
- factors_primary = dict(factors)
1917
- factors_intraday = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1918
  **factors,
 
1919
  "market_structure": {**ms_signal, "score": mtf_result.get("intraday_structure", ms_signal["score"])},
1920
- }
1921
- factors_swing = {
1922
  **factors,
 
1923
  "market_structure": {**ms_signal, "score": mtf_result.get("swing_structure", ms_signal["score"])},
1924
- }
1925
 
1926
  primary_conf = confluence_scorer.compute(
1927
  factors_primary,
@@ -2118,11 +2585,12 @@ class SignalEngine:
2118
  avg_fr_val = float(funding_signal["value"]) * 100.0
2119
  avg_fr_val = avg_fr_val or 0.0
2120
 
2121
- # Candidate direction before global circuit breakers (including any intraday chased direction)
 
2122
  candidate_dir = (
2123
  confluence["direction"]
2124
  if confluence["direction"] in ("LONG", "SHORT")
2125
- else (intra_chased_dir or primary_conf["direction"])
2126
  )
2127
 
2128
  crowded_long_veto = candidate_dir == "LONG" and avg_fr_val > 0.05
@@ -2214,11 +2682,12 @@ class SignalEngine:
2214
  sniper_grade = "WAIT"
2215
  elif intra_dir in ("LONG", "SHORT") and sw_dir == intra_dir:
2216
  sf_aligned = (intra_dir == "LONG" and sf_score > 0) or (intra_dir == "SHORT" and sf_score < 0)
 
2217
  cvd_sc = int(cvd_signal.get("score", 0) or 0)
2218
  ohlcv_cvd_aligned = bool(horizon_thresholds) and (
2219
  (intra_dir == "LONG" and cvd_sc > 0) or (intra_dir == "SHORT" and cvd_sc < 0)
2220
  )
2221
- if squeeze_active or sf_aligned or ohlcv_cvd_aligned:
2222
  sniper_grade = "SNIPER_A_PLUS"
2223
  else:
2224
  sniper_grade = "INTRADAY_ONLY"
@@ -2293,8 +2762,14 @@ class SignalEngine:
2293
  extremes_data=extremes_data,
2294
  )
2295
 
2296
- if confluence["direction"] == "NEUTRAL" and breakout_radar_data.get("is_breakout_primed"):
2297
- if plan.get("action") == "WAIT":
 
 
 
 
 
 
2298
  plan["action"] = "WATCH BREAKOUT"
2299
  if plan.get("quick_verdict"):
2300
  plan["quick_verdict"] = f"{breakout_radar_data['radar_label']}: {breakout_radar_data['catalyst_summary']}"
 
186
  first, second = _split_trades_by_midpoint(sorted_trades)
187
  if not first or not second:
188
  return total_cvd > 0
189
+ h1_buy = sum(float(t.get("qty") or 0.0) for t in first if not t.get("is_buyer_maker", False))
190
+ h1_sell = sum(float(t.get("qty") or 0.0) for t in first if t.get("is_buyer_maker", False))
191
+ h2_buy = sum(float(t.get("qty") or 0.0) for t in second if not t.get("is_buyer_maker", False))
192
+ h2_sell = sum(float(t.get("qty") or 0.0) for t in second if t.get("is_buyer_maker", False))
193
  h1_cvd, h2_cvd = h1_buy - h1_sell, h2_buy - h2_sell
194
  h1_rat = h1_cvd / (h1_buy + h1_sell) if (h1_buy + h1_sell) > 0 else 0.0
195
  h2_rat = h2_cvd / (h2_buy + h2_sell) if (h2_buy + h2_sell) > 0 else 0.0
 
314
  }
315
 
316
  if not spot_trades:
317
+ fut_buy = sum(float(t.get("qty") or 0.0) for t in futures_trades if not t.get("is_buyer_maker", False))
318
+ fut_sell = sum(float(t.get("qty") or 0.0) for t in futures_trades if t.get("is_buyer_maker", False))
319
  futures_cvd = fut_buy - fut_sell
320
  return {
321
  "value": f"Perp: {futures_cvd:+.1f} (No Spot)",
 
326
  }
327
 
328
  # Sort trades chronologically and intersect overlapping Spot/Futures time window when populated
329
+ sorted_spot = sorted(spot_trades, key=lambda t: float(t.get("time") or 0))
330
+ sorted_fut = sorted(futures_trades, key=lambda t: float(t.get("time") or 0))
331
 
332
+ spot_times = [float(t.get("time") or 0) for t in sorted_spot if float(t.get("time") or 0) > 0]
333
+ fut_times = [float(t.get("time") or 0) for t in sorted_fut if float(t.get("time") or 0) > 0]
334
  if spot_times and fut_times:
335
  overlap_start = max(spot_times[0], fut_times[0])
336
  overlap_end = min(spot_times[-1], fut_times[-1])
337
  if overlap_start < overlap_end:
338
+ aligned_spot = [t for t in sorted_spot if overlap_start <= float(t.get("time") or 0) <= overlap_end]
339
+ aligned_fut = [t for t in sorted_fut if overlap_start <= float(t.get("time") or 0) <= overlap_end]
340
  if len(aligned_spot) >= 5 and len(aligned_fut) >= 5:
341
  sorted_spot = aligned_spot
342
  sorted_fut = aligned_fut
343
 
344
+ spot_buy = sum(float(t.get("qty") or 0.0) for t in sorted_spot if not t.get("is_buyer_maker", False))
345
+ spot_sell = sum(float(t.get("qty") or 0.0) for t in sorted_spot if t.get("is_buyer_maker", False))
346
  spot_total = spot_buy + spot_sell
347
  spot_cvd = spot_buy - spot_sell
348
  spot_ratio = (spot_cvd / spot_total) if spot_total > 0 else 0.0
349
 
350
+ fut_buy = sum(float(t.get("qty") or 0.0) for t in sorted_fut if not t.get("is_buyer_maker", False))
351
+ fut_sell = sum(float(t.get("qty") or 0.0) for t in sorted_fut if t.get("is_buyer_maker", False))
352
  fut_total = fut_buy + fut_sell
353
  futures_cvd = fut_buy - fut_sell
354
  fut_ratio = (futures_cvd / fut_total) if fut_total > 0 else 0.0
 
495
  ) -> dict[str, Any]:
496
  """
497
  Open Interest + Price divergence signal (OI-Weighted across Binance, Bybit, OKX, and Bitget).
498
+ Computes both 15m/1h Intraday divergence and 4h Swing divergence.
499
+
500
+ 1. Price↑ + OI↑ (>+0.25%) → Real Long Inflow (+1 / +2)
501
+ 2. Price↑ + OI↓ (<-0.25%) → Short Covering Exhaustion / Weak Rally (-1)
502
+ 3. Price↓ + OI↑ (>+0.25%) → Real Short Inflow (-1 / -2)
503
+ 4. Price↓ + OI↓ (<-0.25%) → Long Liquidation / Squeeze Exhaustion Done (+1)
504
  5. Flat / Small changes → Neutral (0)
505
  """
506
  price_changes: list[float] = []
507
  price_weights: list[float] = []
508
+ price_4h_changes: list[float] = []
509
+ price_4h_weights: list[float] = []
510
  oi_changes: list[float] = []
511
  oi_weights: list[float] = []
512
+ oi_1h_changes: list[float] = []
513
+ oi_1h_weights: list[float] = []
514
+ oi_4h_changes: list[float] = []
515
+ oi_4h_weights: list[float] = []
516
 
517
  for exch in [binance_data, bybit_data, okx_data, bitget_data]:
518
  if not exch:
519
  continue
520
  w = _extract_venue_oi_weight(exch)
521
+ ohlcv = exch.get("ohlcv", {}) or {}
522
  # 15m candle price change %
523
+ candles = ohlcv.get("15m", [])
524
+ if len(candles) >= 2 and (candles[-2].get("close") or 0) > 0 and candles[-1].get("close") is not None:
525
+ prev_c = float(candles[-2]["close"])
526
+ curr_c = float(candles[-1]["close"])
527
+ pc = (curr_c - prev_c) / prev_c * 100
528
  price_changes.append(pc)
529
  price_weights.append(w)
530
 
531
+ # 4h candle price change % (or 4-bar 1h fallback)
532
+ c4h = ohlcv.get("4h", [])
533
+ c1h = ohlcv.get("1h", [])
534
+ if len(c4h) >= 2 and (c4h[-2].get("close") or 0) > 0 and c4h[-1].get("close") is not None:
535
+ prev4 = float(c4h[-2]["close"])
536
+ curr4 = float(c4h[-1]["close"])
537
+ pc4 = (curr4 - prev4) / prev4 * 100
538
+ price_4h_changes.append(pc4)
539
+ price_4h_weights.append(w)
540
+ elif len(c1h) >= 5 and (c1h[-5].get("close") or 0) > 0 and c1h[-1].get("close") is not None:
541
+ prev4 = float(c1h[-5]["close"])
542
+ curr4 = float(c1h[-1]["close"])
543
+ pc4 = (curr4 - prev4) / prev4 * 100
544
+ price_4h_changes.append(pc4)
545
+ price_4h_weights.append(w)
546
+
547
+ # OI change % (15m, 1h, 4h)
548
  oi_data = exch.get("open_interest_data")
549
+ if oi_data:
550
+ if oi_data.get("oi_change_pct") is not None:
551
+ oi_changes.append(float(oi_data["oi_change_pct"]))
552
+ oi_weights.append(w)
553
+ if oi_data.get("oi_change_1h_pct") is not None:
554
+ oi_1h_changes.append(float(oi_data["oi_change_1h_pct"]))
555
+ oi_1h_weights.append(w)
556
+ if oi_data.get("oi_change_4h_pct") is not None:
557
+ oi_4h_changes.append(float(oi_data["oi_change_4h_pct"]))
558
+ oi_4h_weights.append(w)
559
 
560
  if not price_changes:
561
+ return {
562
+ "value": "No Data",
563
+ "score": 0,
564
+ "intraday_score": 0,
565
+ "swing_score": 0,
566
+ "label": "No Price Data",
567
+ }
568
 
569
  avg_price_change = _oi_weighted_average(price_changes, price_weights)
570
  avg_oi_change = _oi_weighted_average(oi_changes, oi_weights) if oi_changes else 0.0
571
+ avg_oi_1h_change = _oi_weighted_average(oi_1h_changes, oi_1h_weights) if oi_1h_changes else avg_oi_change
572
+ avg_oi_4h_change = _oi_weighted_average(oi_4h_changes, oi_4h_weights) if oi_4h_changes else avg_oi_1h_change
573
+ avg_price_4h_change = _oi_weighted_average(price_4h_changes, price_4h_weights) if price_4h_changes else avg_price_change
574
 
575
  # Robust threshold to filter sub-tick micro-noise on 15m timeframe:
576
  # Minimum 0.15% price displacement and 0.25% net Open Interest expansion/unwinding
 
611
  direction_val = "Flat (Neutral)"
612
  label = "Balanced Market Flow"
613
 
614
+ # Swing 4h OI score uses 4h OI expansion (>0.50%) + 4h price displacement (>0.40%) when 4h OI history exists
615
+ swing_score = score
616
+ if oi_4h_changes:
617
+ p4_up = avg_price_4h_change > 0.40
618
+ p4_dn = avg_price_4h_change < -0.40
619
+ oi4_up = avg_oi_4h_change > 0.50
620
+ oi4_dn = avg_oi_4h_change < -0.50
621
+ if p4_up and oi4_up:
622
+ swing_score = 1
623
+ elif p4_up and oi4_dn:
624
+ swing_score = -1
625
+ elif p4_dn and oi4_up:
626
+ swing_score = -1
627
+ elif p4_dn and oi4_dn:
628
+ swing_score = 1
629
+
630
  return {
631
  "value": direction_val,
632
  "price_change_pct": round(avg_price_change, 4),
633
+ "price_change_4h_pct": round(avg_price_4h_change, 4),
634
  "oi_change_pct": round(avg_oi_change, 4),
635
+ "oi_change_1h_pct": round(avg_oi_1h_change, 4),
636
+ "oi_change_4h_pct": round(avg_oi_4h_change, 4),
637
  "score": score,
638
+ "intraday_score": score,
639
+ "swing_score": swing_score,
640
  "label": label,
641
  }
642
 
 
651
  return {"value": 0, "delta_ratio": 0.0, "score": 0, "rising": False, "label": "No Trade Data"}
652
 
653
  # Sort trades chronologically (oldest to newest) to eliminate any exchange discrepancies
654
+ sorted_trades = sorted(trades, key=lambda t: float(t.get("time") or 0))
655
 
656
  buy_vol = 0.0
657
  sell_vol = 0.0
658
  for t in sorted_trades:
659
+ qty = float(t.get("qty") or 0.0)
660
  if t.get("is_buyer_maker", False):
661
  sell_vol += qty
662
  else:
 
703
  Aligned exchanges confirm price consistency.
704
  """
705
  def _pct_change_5m(exch: dict) -> float | None:
706
+ candles = (exch.get("ohlcv") or {}).get("5m", [])
707
  if len(candles) < 2:
708
  return None
709
+ prev = candles[-2].get("close")
710
+ curr = candles[-1].get("close")
711
+ if prev is None or curr is None or float(prev) <= 0:
712
+ return None
713
+ return (float(curr) - float(prev)) / float(prev) * 100
714
 
715
  rates = {}
716
  if binance_data:
 
771
  bitget_data: dict | None = None,
772
  ) -> dict[str, Any]:
773
  """
774
+ Smart Money Whale Position vs Retail Crowd L/S Ratio
775
+ (OI-Weighted across Binance, Bybit, OKX, and Bitget).
776
+ Separates Top-Trader Position Size (Smart Money) from Global Account Ratio (Retail Crowd).
777
  """
778
  long_ratios: list[float] = []
779
  weights: list[float] = []
780
+ whale_pos_ratios: list[float] = []
781
+ whale_pos_weights: list[float] = []
782
+ retail_ratios: list[float] = []
783
+ retail_weights: list[float] = []
784
+
785
  for exch in [binance_data, bybit_data, okx_data, bitget_data]:
786
  if exch and exch.get("ls_ratio_data"):
787
+ ls_d = exch["ls_ratio_data"]
788
+ w = _extract_venue_oi_weight(exch)
789
+ lr = ls_d.get("long_ratio")
790
  if lr is not None:
791
  long_ratios.append(float(lr))
792
+ weights.append(w)
793
+ wp = ls_d.get("top_position_long_ratio")
794
+ if wp is not None:
795
+ whale_pos_ratios.append(float(wp))
796
+ whale_pos_weights.append(w)
797
+ rr = ls_d.get("retail_long_ratio")
798
+ if rr is not None:
799
+ retail_ratios.append(float(rr))
800
+ retail_weights.append(w)
801
 
802
  if not long_ratios:
803
+ return {
804
+ "top_trader": None,
805
+ "retail": None,
806
+ "whale_position_long_ratio": None,
807
+ "smart_money_delta": 0.0,
808
+ "whale_sentiment": "NEUTRAL",
809
+ "score": 0,
810
+ "label": "No Data",
811
+ }
812
 
813
  avg_long = _oi_weighted_average(long_ratios, weights)
814
+ avg_whale_pos = _oi_weighted_average(whale_pos_ratios, whale_pos_weights) if whale_pos_ratios else None
815
+ avg_retail = _oi_weighted_average(retail_ratios, retail_weights) if retail_ratios else avg_long
816
+ smart_money_delta = (avg_whale_pos - avg_retail) if (avg_whale_pos is not None and avg_retail is not None) else 0.0
817
+
818
+ whale_sentiment = "NEUTRAL"
819
+ # Smart Money Whale Position vs Retail Crowd Divergence
820
+ if avg_whale_pos is not None and abs(smart_money_delta) >= 0.07:
821
+ if smart_money_delta >= 0.12 and avg_whale_pos >= 0.56:
822
+ score = 2
823
+ whale_sentiment = "STRONG_WHALE_LONG"
824
+ label = f"Whale Position Accumulation ({avg_whale_pos:.1%} Whale Long vs {avg_retail:.1%} Retail) → Strong Smart Money Long"
825
+ elif smart_money_delta <= -0.12 and avg_whale_pos <= 0.44:
826
+ score = -2
827
+ whale_sentiment = "STRONG_WHALE_SHORT"
828
+ label = f"Whale Position Distribution ({1.0 - avg_whale_pos:.1%} Whale Short vs {avg_retail:.1%} Retail Long) → Strong Smart Money Short"
829
+ elif smart_money_delta >= 0.07 and avg_whale_pos >= 0.52:
830
+ score = 1
831
+ whale_sentiment = "WHALE_LONG_TILT"
832
+ label = f"Smart Money Whale Long Tilt ({avg_whale_pos:.1%} Whale Pos vs {avg_retail:.1%} Retail)"
833
+ elif smart_money_delta <= -0.07 and avg_whale_pos <= 0.48:
834
+ score = -1
835
+ whale_sentiment = "WHALE_SHORT_TILT"
836
+ label = f"Smart Money Whale Short Tilt ({1.0 - avg_whale_pos:.1%} Whale Short vs {avg_retail:.1%} Retail)"
837
+ elif avg_long >= 0.62:
838
+ score, label = -1, f"Crowded Retail Longs {avg_long:.1%} → Contrarian Short"
839
+ elif avg_long <= 0.38:
840
+ score, label = 1, f"Crowded Retail Shorts {avg_long:.1%} → Contrarian Long"
841
+ else:
842
+ score, label = 0, f"Balanced L/S {avg_long:.1%}"
843
  else:
844
+ if avg_long >= 0.62:
845
+ score, label = -1, f"Crowded Retail Longs {avg_long:.1%} → Contrarian Short"
846
+ elif avg_long <= 0.38:
847
+ score, label = 1, f"Crowded Retail Shorts {avg_long:.1%} → Contrarian Long"
848
+ else:
849
+ score, label = 0, f"Balanced L/S {avg_long:.1%}"
850
 
851
  return {
852
  "top_trader": round(avg_long, 4),
853
+ "retail": round(avg_retail, 4) if retail_ratios else None,
854
+ "whale_position_long_ratio": round(avg_whale_pos, 4) if avg_whale_pos is not None else None,
855
+ "smart_money_delta": round(smart_money_delta, 4),
856
+ "whale_sentiment": whale_sentiment,
857
  "score": score,
858
  "label": label,
859
  }
 
968
  entry_high = mark_price + (0.05 * atr)
969
 
970
  # Structure-Based Invalidation Stop Loss: anchor to recent swing low if within [sl_min_pct, sl_max_pct]
971
+ recent_lows = [c["low"] for c in ohlcv_1h[-20:] if (c.get("low") or 0) > 0] if ohlcv_1h else []
972
  if recent_lows:
973
  struct_low = min(recent_lows) - (0.2 * atr)
974
  if mark_price * long_struct_min <= struct_low <= mark_price * long_struct_max:
 
1024
  entry_high = mark_price + (0.35 * atr)
1025
 
1026
  # Structure-Based Invalidation Stop Loss: anchor to recent swing high if within [sl_min_pct, sl_max_pct]
1027
+ recent_highs = [c["high"] for c in ohlcv_1h[-20:] if (c.get("high") or 0) > 0] if ohlcv_1h else []
1028
  if recent_highs:
1029
  struct_high = max(recent_highs) + (0.2 * atr)
1030
  if mark_price * short_struct_min <= struct_high <= mark_price * short_struct_max:
 
1353
  }
1354
 
1355
 
1356
+ def _compute_whale_order_flow(
1357
+ trades: list[dict],
1358
+ mark_price: float,
1359
+ merged_ohlcv: dict | None = None,
1360
+ oi_signal: dict | None = None,
1361
+ ls_signal: dict | None = None,
1362
+ ) -> dict[str, Any]:
1363
  """
1364
+ Multi-Layer Institutional Order Flow & True Whale Movement Intelligence:
1365
+ 1. Dynamic Quantile Block Trade Detection (p95 / median + 1.5% vol floor $5k)
1366
+ 2. Reconstructed Market Sweep Clustering (coalesces split resting fills sharing exact tick timestamp)
1367
+ 3. Multi-Candle Whale TWAP Accumulation/Distribution via Klines `taker_buy_volume` (15m / 1h)
1368
+ 4. Hyperliquid On-Chain Single-Wallet Whale Accumulation Tracker (`taker_wallet` grouping)
1369
+ 5. Passive Whale Iceberg Limit Absorption Detector (High Taker Sell + Price Hold + OI Expansion)
1370
  """
1371
+ # Compute multi-candle TWAP & Iceberg Absorption from OHLCV even when live trade tape is empty
1372
+ twap_buy_usd = 0.0
1373
+ twap_sell_usd = 0.0
1374
+ twap_bias = "NEUTRAL"
1375
+ twap_score = 0
1376
+ absorption_type: str | None = None
1377
+ absorption_note: str | None = None
1378
+ absorption_score = 0
1379
+
1380
+ oi_val = (oi_signal or {}).get("oi_change_pct")
1381
+ oi_chg = float(oi_val) if oi_val is not None else 0.0
1382
+ oi_1h_val = (oi_signal or {}).get("oi_change_1h_pct")
1383
+ oi_1h_chg = float(oi_1h_val) if oi_1h_val is not None else oi_chg
1384
+ # Only elevate 1H OI over 15m when aligned in sign (or 15m is flat 0.0); never let stale 1H mask active 15m unwinding
1385
+ if oi_chg != 0.0 and (oi_chg * oi_1h_chg) < 0:
1386
+ eff_oi_chg = oi_chg
1387
+ else:
1388
+ eff_oi_chg = oi_1h_chg if abs(oi_1h_chg) > abs(oi_chg) else oi_chg
1389
+
1390
+ if merged_ohlcv and mark_price > 0:
1391
+ ref_bars = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or [])[-4:]
1392
+ tb_bars = [b for b in ref_bars if b.get("taker_buy_volume") is not None and float(b.get("volume", 0.0) or 0.0) > 0]
1393
+ if tb_bars:
1394
+ for b in tb_bars:
1395
+ v_tot = float(b.get("volume", 0.0) or 0.0)
1396
+ v_buy = min(v_tot, max(0.0, float(b.get("taker_buy_volume", 0.0) or 0.0)))
1397
+ v_sell = max(0.0, v_tot - v_buy)
1398
+ px_b = float(b.get("close") or mark_price)
1399
+ twap_buy_usd += v_buy * px_b
1400
+ twap_sell_usd += v_sell * px_b
1401
+
1402
+ twap_tot_usd = twap_buy_usd + twap_sell_usd
1403
+ twap_delta_usd = twap_buy_usd - twap_sell_usd
1404
+ twap_delta_ratio = (twap_delta_usd / twap_tot_usd) if twap_tot_usd > 0 else 0.0
1405
+
1406
+ # Require institutional notional size (>= $25,000) to classify TWAP accumulation
1407
+ if twap_tot_usd >= 25_000.0:
1408
+ if twap_delta_ratio >= 0.06 and eff_oi_chg >= 0.20:
1409
+ twap_bias = "WHALE_TWAP_LONG_BUILDUP"
1410
+ twap_score = 2 if (twap_delta_ratio >= 0.12 and eff_oi_chg >= 0.50) else 1
1411
+ elif twap_delta_ratio <= -0.06 and eff_oi_chg >= 0.20:
1412
+ twap_bias = "WHALE_TWAP_SHORT_BUILDUP"
1413
+ twap_score = -2 if (twap_delta_ratio <= -0.12 and eff_oi_chg >= 0.50) else -1
1414
+ elif twap_delta_ratio >= 0.08:
1415
+ twap_bias = "TWAP_BUY_ACCUMULATION"
1416
+ twap_score = 1
1417
+ elif twap_delta_ratio <= -0.08:
1418
+ twap_bias = "TWAP_SELL_DISTRIBUTION"
1419
+ twap_score = -1
1420
+
1421
+ # Iceberg Limit Absorption on latest completed/active 15m or 1h bar
1422
+ if ref_bars:
1423
+ last_b = ref_bars[-1]
1424
+ b_high = float(last_b.get("high", 0.0) or 0.0)
1425
+ b_low = float(last_b.get("low", 0.0) or 0.0)
1426
+ b_close = float(last_b.get("close", 0.0) or 0.0)
1427
+ b_rng = b_high - b_low
1428
+ min_meaningful_rng = b_close * 0.001 if b_close > 0 else 0.0
1429
+ close_pos = ((b_close - b_low) / b_rng) if (b_rng > 0 and b_rng >= min_meaningful_rng) else 0.5
1430
+ if b_rng >= min_meaningful_rng and twap_tot_usd >= 25_000.0 and eff_oi_chg >= 0.25:
1431
+ if twap_delta_ratio <= -0.05 and close_pos >= 0.60:
1432
+ absorption_type = "BULLISH_ICEBERG_ABSORPTION"
1433
+ absorption_note = f"Limit Bid Iceberg menyerap jualan agresif + OI naik {eff_oi_chg:+.2f}%"
1434
+ absorption_score = 1
1435
+ elif twap_delta_ratio >= 0.05 and close_pos <= 0.40:
1436
+ absorption_type = "BEARISH_ICEBERG_ABSORPTION"
1437
+ absorption_note = f"Limit Ask Iceberg menahan beli agresif + OI naik {eff_oi_chg:+.2f}%"
1438
+ absorption_score = -1
1439
+ else:
1440
+ twap_delta_usd = 0.0
1441
+ twap_delta_ratio = 0.0
1442
+
1443
+ sm_delta = float((ls_signal or {}).get("smart_money_delta", 0.0) or 0.0)
1444
+ whale_pos_lr = (ls_signal or {}).get("whale_position_long_ratio")
1445
+ retail_acc_lr = (ls_signal or {}).get("retail")
1446
 
1447
  taker_buy_vol = 0.0
1448
  taker_sell_vol = 0.0
1449
  parsed_trades = []
1450
+ # Sweep reconstruction: coalesce split fills sharing exact positive (venue, time, is_sell_taker)
1451
+ sweep_buckets: dict[tuple[str, int, bool], float] = {}
1452
+ unbucketed_sweeps: list[tuple[float, bool]] = []
1453
+ # Hyperliquid on-chain wallet tracker: {wallet: [buy_usd, sell_usd]}
1454
+ wallet_flows: dict[str, list[float]] = {}
1455
+
1456
+ if trades and mark_price > 0:
1457
+ for t in trades:
1458
+ try:
1459
+ px = float(t.get("price", 0.0))
1460
+ qty = float(t.get("qty", 0.0))
1461
+ if px <= 0 or qty <= 0:
1462
+ continue
1463
+ usd_val = px * qty
1464
+ is_sell_taker = bool(t.get("is_buyer_maker", False))
1465
+ parsed_trades.append((usd_val, is_sell_taker))
1466
+ if is_sell_taker:
1467
+ taker_sell_vol += usd_val
1468
+ else:
1469
+ taker_buy_vol += usd_val
1470
 
1471
+ t_ms = int(t.get("time", 0) or 0)
1472
+ venue = str(t.get("venue", "default"))
1473
+ if t_ms > 0:
1474
+ b_key = (venue, t_ms, is_sell_taker)
1475
+ sweep_buckets[b_key] = sweep_buckets.get(b_key, 0.0) + usd_val
1476
+ else:
1477
+ unbucketed_sweeps.append((usd_val, is_sell_taker))
1478
+
1479
+ w_addr = t.get("taker_wallet")
1480
+ if w_addr and isinstance(w_addr, str):
1481
+ wf = wallet_flows.setdefault(w_addr, [0.0, 0.0])
1482
+ if is_sell_taker:
1483
+ wf[1] += usd_val
1484
+ else:
1485
+ wf[0] += usd_val
1486
+ except Exception:
1487
  continue
1488
+
1489
+ # Neutralize absorbed aggressive TWAP flow when opposite Limit Iceberg absorption confirms
1490
+ eff_twap_score = 0 if (absorption_score * twap_score < 0) else twap_score
 
 
 
 
 
 
1491
 
1492
  if not parsed_trades:
1493
+ fallback_buy_pct = (
1494
+ round(twap_buy_usd / (twap_buy_usd + twap_sell_usd) * 100.0, 1)
1495
+ if (twap_buy_usd + twap_sell_usd) > 0
1496
+ else 50.0
1497
+ )
1498
+ fallback_ratio = (
1499
+ round(twap_buy_usd / twap_sell_usd, 2)
1500
+ if twap_sell_usd > 0
1501
+ else (99.0 if twap_buy_usd > 0 else 1.0)
1502
+ )
1503
+ comp_score = max(-2, min(2, eff_twap_score + absorption_score))
1504
+ if absorption_type == "BULLISH_ICEBERG_ABSORPTION" and comp_score >= 0:
1505
+ verdict = f"🛡️ Iceberg Absorption Paus (Bullish): {absorption_note}"
1506
+ elif absorption_type == "BEARISH_ICEBERG_ABSORPTION" and comp_score <= 0:
1507
+ verdict = f"🛡️ Iceberg Absorption Paus (Bearish): {absorption_note}"
1508
+ elif twap_bias == "WHALE_TWAP_LONG_BUILDUP":
1509
+ verdict = f"Akumulasi TWAP Paus (Klines): Net Taker Buy +${twap_delta_usd:,.0f} disertai ekspansi OI {eff_oi_chg:+.2f}%."
1510
+ elif twap_bias == "WHALE_TWAP_SHORT_BUILDUP":
1511
+ verdict = f"Distribusi TWAP Paus (Klines): Net Taker Sell -${abs(twap_delta_usd):,.0f} disertai ekspansi OI {eff_oi_chg:+.2f}%."
1512
+ elif twap_bias == "TWAP_BUY_ACCUMULATION":
1513
+ verdict = f"Akumulasi TWAP Beli (Klines): Net Taker Buy +${twap_delta_usd:,.0f}."
1514
+ elif twap_bias == "TWAP_SELL_DISTRIBUTION":
1515
+ verdict = f"Distribusi TWAP Jual (Klines): Net Taker Sell -${abs(twap_delta_usd):,.0f}."
1516
+ else:
1517
+ verdict = (
1518
+ "Order Flow Agregat Seimbang (Belum Ada Data Trades)"
1519
+ if not trades
1520
+ else "Order Flow Agregat Seimbang"
1521
+ )
1522
  return {
1523
+ "taker_buy_vol_usd": round(twap_buy_usd, 2),
1524
+ "taker_sell_vol_usd": round(twap_sell_usd, 2),
1525
+ "total_vol_usd": round(twap_buy_usd + twap_sell_usd, 2),
1526
+ "taker_buy_pct": fallback_buy_pct,
1527
+ "taker_ratio": fallback_ratio,
1528
  "whale_buy_count": 0,
1529
  "whale_sell_count": 0,
1530
  "whale_buy_vol_usd": 0.0,
 
1533
  "largest_trade_side": "NONE",
1534
  "dynamic_threshold_usd": 5000.0,
1535
  "net_whale_threshold_usd": 5000.0,
1536
+ "sweep_buy_count": 0,
1537
+ "sweep_sell_count": 0,
1538
+ "sweep_buy_vol_usd": 0.0,
1539
+ "sweep_sell_vol_usd": 0.0,
1540
+ "largest_sweep_usd": 0.0,
1541
+ "twap_bias": twap_bias,
1542
+ "twap_buy_pct": round(50.0 + twap_delta_ratio * 50.0, 1),
1543
+ "twap_net_delta_usd": round(twap_delta_usd, 2),
1544
+ "twap_delta_ratio": round(twap_delta_ratio, 4),
1545
+ "absorption_type": absorption_type,
1546
+ "absorption_note": absorption_note,
1547
+ "is_iceberg_absorbing": absorption_score != 0,
1548
+ "onchain_whale_wallets": 0,
1549
+ "onchain_buy_vol_usd": 0.0,
1550
+ "onchain_sell_vol_usd": 0.0,
1551
+ "top_whale_wallet_usd": 0.0,
1552
+ "top_whale_wallet_side": "NONE",
1553
+ "whale_position_long_ratio": whale_pos_lr,
1554
+ "retail_account_long_ratio": retail_acc_lr,
1555
+ "smart_money_delta": sm_delta,
1556
+ "whale_composite_score": comp_score,
1557
+ "flow_verdict": verdict,
1558
  }
1559
 
1560
  total_vol = taker_buy_vol + taker_sell_vol
 
1587
  whale_buy_vol = sum(whale_buys)
1588
  whale_sell_vol = sum(whale_sells)
1589
 
1590
+ # Reconstructed sweep orders (coalesces split fills at identical tick timestamp)
1591
+ all_sweeps = [(val, is_sell) for (_, _, is_sell), val in sweep_buckets.items()] + unbucketed_sweeps
1592
+ sweep_buys = [v for v, is_sell in all_sweeps if (not is_sell) and v >= threshold]
1593
+ sweep_sells = [v for v, is_sell in all_sweeps if is_sell and v >= threshold]
1594
+ sweep_buy_vol = sum(sweep_buys)
1595
+ sweep_sell_vol = sum(sweep_sells)
1596
+ largest_sweep_usd = max((v for v, _ in all_sweeps), default=0.0)
1597
+
1598
+ # Hyperliquid On-Chain Single-Wallet Whale Accumulation
1599
+ onchain_whale_wallets = 0
1600
+ onchain_buy_vol_usd = 0.0
1601
+ onchain_sell_vol_usd = 0.0
1602
+ top_whale_wallet_usd = 0.0
1603
+ top_whale_wallet_side = "NONE"
1604
+ for w_buy_u, w_sell_u in wallet_flows.values():
1605
+ net_w = w_buy_u - w_sell_u
1606
+ if abs(net_w) >= max(10_000.0, threshold):
1607
+ onchain_whale_wallets += 1
1608
+ if net_w > 0:
1609
+ onchain_buy_vol_usd += net_w
1610
+ else:
1611
+ onchain_sell_vol_usd += abs(net_w)
1612
+ if abs(net_w) > top_whale_wallet_usd:
1613
+ top_whale_wallet_usd = abs(net_w)
1614
+ top_whale_wallet_side = "BUY" if net_w > 0 else "SELL"
1615
+
1616
+ onchain_score = 0
1617
+ if onchain_buy_vol_usd > onchain_sell_vol_usd * 1.4 and onchain_buy_vol_usd >= threshold:
1618
+ onchain_score = 1
1619
+ elif onchain_sell_vol_usd > onchain_buy_vol_usd * 1.4 and onchain_sell_vol_usd >= threshold:
1620
+ onchain_score = -1
1621
+
1622
+ # Also check live tape Iceberg Absorption if not already triggered by klines
1623
+ if absorption_score == 0 and merged_ohlcv and total_vol >= 25_000.0 and eff_oi_chg >= 0.25:
1624
+ ref_b = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or [])
1625
+ if ref_b:
1626
+ lb = ref_b[-1]
1627
+ l_high = float(lb.get("high", 0.0) or 0.0)
1628
+ l_low = float(lb.get("low", 0.0) or 0.0)
1629
+ l_close = float(lb.get("close", 0.0) or 0.0)
1630
+ rng = l_high - l_low
1631
+ min_rng = l_close * 0.001 if l_close > 0 else 0.0
1632
+ c_pos = ((l_close - l_low) / rng) if (rng > 0 and rng >= min_rng) else 0.5
1633
+ if rng >= min_rng and buy_pct <= 40.0 and c_pos >= 0.60:
1634
+ absorption_type = "BULLISH_ICEBERG_ABSORPTION"
1635
+ absorption_note = f"Jualan agresif ({100.0 - buy_pct:.0f}% Taker Sell) diserap Limit Buy Wall + OI naik {eff_oi_chg:+.2f}%"
1636
+ absorption_score = 1
1637
+ elif buy_pct >= 60.0 and c_pos <= 0.40:
1638
+ absorption_type = "BEARISH_ICEBERG_ABSORPTION"
1639
+ absorption_note = f"Beli agresif ({buy_pct:.0f}% Taker Buy) ditahan Limit Sell Wall + OI naik {eff_oi_chg:+.2f}%"
1640
+ absorption_score = -1
1641
+
1642
+ # Composite Whale Score [-2, +2]
1643
+ eff_whale_buy = max(whale_buy_vol, sweep_buy_vol)
1644
+ eff_whale_sell = max(whale_sell_vol, sweep_sell_vol)
1645
+ block_score = 0
1646
+ if eff_whale_buy > eff_whale_sell * 1.4 and eff_whale_buy >= threshold:
1647
+ block_score = 2 if eff_whale_buy >= threshold * 3.0 and len(sweep_buys) >= 2 else 1
1648
+ elif eff_whale_sell > eff_whale_buy * 1.4 and eff_whale_sell >= threshold:
1649
+ block_score = -2 if eff_whale_sell >= threshold * 3.0 and len(sweep_sells) >= 2 else -1
1650
+
1651
+ # Neutralize absorbed aggressive block/TWAP flow when passive Iceberg absorption confirms
1652
+ eff_block_score = 0 if (absorption_score * block_score < 0) else block_score
1653
+ eff_twap_score_main = 0 if (absorption_score * twap_score < 0) else twap_score
1654
+ whale_composite_score = max(
1655
+ -2,
1656
+ min(2, eff_block_score + eff_twap_score_main + absorption_score + onchain_score),
1657
+ )
1658
+
1659
  largest_val, largest_is_sell = max(parsed_trades, key=lambda x: x[0])
1660
  largest_side = "SELL" if largest_is_sell else "BUY"
1661
 
1662
+ if absorption_type == "BULLISH_ICEBERG_ABSORPTION" and whale_composite_score >= 0:
1663
+ verdict = f"🛡️ Iceberg Absorption Paus (Bullish): Jualan agresif diserap Limit Buy Wall + OI naik {eff_oi_chg:+.2f}%!"
1664
+ elif absorption_type == "BEARISH_ICEBERG_ABSORPTION" and whale_composite_score <= 0:
1665
+ verdict = f"🛡️ Iceberg Absorption Paus (Bearish): Beli agresif ditahan Limit Sell Wall + OI naik {eff_oi_chg:+.2f}%!"
1666
+ elif len(whale_buys) > 0 and len(whale_sells) == 0:
1667
  verdict = f"Paus Agresif Sisi Beli: {len(whale_buys)} block buy (${whale_buy_vol:,.0f}) tanpa block sell tandingan!"
1668
  elif len(whale_sells) > 0 and len(whale_buys) == 0:
1669
  verdict = f"Paus Agresif Sisi Jual: {len(whale_sells)} block sell (${whale_sell_vol:,.0f}) tanpa block buy tandingan!"
1670
+ elif eff_whale_buy > eff_whale_sell * 1.5 and eff_whale_buy >= threshold:
1671
+ verdict = f"Dominasi Block/Sweep Buy: Whale buy ${eff_whale_buy:,.0f} ({max(len(whale_buys), len(sweep_buys))} orders) vs sell ${eff_whale_sell:,.0f}."
1672
+ elif eff_whale_sell > eff_whale_buy * 1.5 and eff_whale_sell >= threshold:
1673
+ verdict = f"Dominasi Block/Sweep Sell: Whale sell ${eff_whale_sell:,.0f} ({max(len(whale_sells), len(sweep_sells))} orders) vs buy ${eff_whale_buy:,.0f}."
1674
+ elif twap_bias == "WHALE_TWAP_LONG_BUILDUP":
1675
+ verdict = f"Akumulasi TWAP Paus: Net Taker Buy +${twap_delta_usd:,.0f} + OI naik {eff_oi_chg:+.2f}%."
1676
+ elif twap_bias == "WHALE_TWAP_SHORT_BUILDUP":
1677
+ verdict = f"Distribusi TWAP Paus: Net Taker Sell -${abs(twap_delta_usd):,.0f} + OI naik {eff_oi_chg:+.2f}%."
1678
+ elif twap_bias == "TWAP_BUY_ACCUMULATION":
1679
+ verdict = f"Akumulasi TWAP Beli: Net Taker Buy +${twap_delta_usd:,.0f} ({50.0 + twap_delta_ratio * 50.0:.1f}% Taker Buy)."
1680
+ elif twap_bias == "TWAP_SELL_DISTRIBUTION":
1681
+ verdict = f"Distribusi TWAP Jual: Net Taker Sell -${abs(twap_delta_usd):,.0f} ({50.0 - twap_delta_ratio * 50.0:.1f}% Taker Sell)."
1682
  elif buy_pct >= 58.0:
1683
  verdict = f"Taker Buy Dominan: {buy_pct:.1f}% volume taker agresif beli (Rasio {taker_ratio:.2f}x)."
1684
  elif buy_pct <= 42.0:
 
1700
  "largest_trade_side": largest_side,
1701
  "dynamic_threshold_usd": round(threshold, 2),
1702
  "net_whale_threshold_usd": round(net_whale_threshold, 2),
1703
+ "sweep_buy_count": len(sweep_buys),
1704
+ "sweep_sell_count": len(sweep_sells),
1705
+ "sweep_buy_vol_usd": round(sweep_buy_vol, 2),
1706
+ "sweep_sell_vol_usd": round(sweep_sell_vol, 2),
1707
+ "largest_sweep_usd": round(largest_sweep_usd, 2),
1708
+ "twap_bias": twap_bias,
1709
+ "twap_buy_pct": round(50.0 + twap_delta_ratio * 50.0, 1),
1710
+ "twap_net_delta_usd": round(twap_delta_usd, 2),
1711
+ "twap_delta_ratio": round(twap_delta_ratio, 4),
1712
+ "absorption_type": absorption_type,
1713
+ "absorption_note": absorption_note,
1714
+ "is_iceberg_absorbing": absorption_score != 0,
1715
+ "onchain_whale_wallets": onchain_whale_wallets,
1716
+ "onchain_buy_vol_usd": round(onchain_buy_vol_usd, 2),
1717
+ "onchain_sell_vol_usd": round(onchain_sell_vol_usd, 2),
1718
+ "top_whale_wallet_usd": round(top_whale_wallet_usd, 2),
1719
+ "top_whale_wallet_side": top_whale_wallet_side,
1720
+ "whale_position_long_ratio": whale_pos_lr,
1721
+ "retail_account_long_ratio": retail_acc_lr,
1722
+ "smart_money_delta": sm_delta,
1723
+ "whale_composite_score": whale_composite_score,
1724
  "flow_verdict": verdict,
1725
  }
1726
 
 
2053
  hl_mark_px = hyperliquid.get("mark_price") if hyperliquid else None
2054
  ref_mark_px = binance_mark or bybit_mark or bitget_mark or okx_mark or hl_mark_px or 0.0
2055
 
2056
+ # CVD & Whale Order Flow: combine Binance, Bybit, OKX, Bitget, and Hyperliquid (normalized to canonical contract scale).
2057
  trades = []
2058
+ for v_name, v_data, v_mark in [
2059
+ ("binance", binance, binance_mark),
2060
+ ("bybit", bybit, bybit_mark),
2061
+ ("okx", okx, okx_mark),
2062
+ ("bitget", bitget, bitget_mark),
2063
+ ("hyperliquid", hyperliquid, hl_mark_px),
2064
  ]:
2065
  if v_data and v_data.get("trades"):
2066
  v_trades = v_data["trades"]
2067
  sample_px = v_mark or (v_trades[0].get("price") if v_trades else None)
2068
  t_scale = _get_multiplier_scale(sample_px, ref_mark_px)
2069
+ for nt in _normalize_trades_scale(v_trades, t_scale):
2070
+ trades.append({**nt, "venue": v_name})
2071
 
2072
  cvd_signal = _compute_cvd(trades)
2073
 
 
2093
  merged_ohlcv[tf] = candles
2094
 
2095
  mtf_result = mtf_analyzer.analyze(merged_ohlcv)
2096
+ if not trades:
2097
  ref_cvd_bars = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or [])[-10:]
2098
+ tb_cvd_bars = [
2099
+ b for b in ref_cvd_bars
2100
+ if b.get("taker_buy_volume") is not None and float(b.get("volume", 0.0) or 0.0) > 0
2101
+ ]
2102
+ if tb_cvd_bars:
2103
+ net_delta = 0.0
2104
+ tot_vol = 0.0
2105
+ for b in tb_cvd_bars:
2106
+ v_tot = float(b.get("volume", 0.0) or 0.0)
2107
+ v_buy = max(0.0, min(v_tot, float(b.get("taker_buy_volume") or 0.0)))
2108
+ net_delta += (2.0 * v_buy) - v_tot
2109
+ tot_vol += v_tot
2110
+ if tot_vol > 0:
2111
+ ratio = net_delta / tot_vol
2112
+ buy_pct = 50.0 + ratio * 50.0
2113
+ if ratio > 0.06:
2114
+ cvd_signal = {
2115
+ **cvd_signal,
2116
+ "score": 1,
2117
+ "rising": True,
2118
+ "value": round(net_delta, 2),
2119
+ "label": f"Klines Taker CVD Bullish ({buy_pct:.1f}% Buy)",
2120
+ }
2121
+ elif ratio < -0.06:
2122
+ cvd_signal = {
2123
+ **cvd_signal,
2124
+ "score": -1,
2125
+ "rising": False,
2126
+ "value": round(net_delta, 2),
2127
+ "label": f"Klines Taker CVD Bearish ({buy_pct:.1f}% Buy)",
2128
+ }
2129
+ elif horizon_thresholds is not None and ref_cvd_bars:
2130
+ net_delta = 0.0
2131
+ tot_vol = 0.0
2132
+ for b in ref_cvd_bars:
2133
+ if not isinstance(b, dict):
2134
+ continue
2135
+ o = b.get("open")
2136
+ h = b.get("high")
2137
+ l_val = b.get("low")
2138
+ c = b.get("close")
2139
+ v = b.get("volume")
2140
+ if None in (o, h, l_val, c):
2141
+ continue
2142
+ try:
2143
+ o_f, h_f, l_f, c_f = float(o), float(h), float(l_val), float(c)
2144
+ v_f = float(v) if v is not None else 0.0
2145
+ except (TypeError, ValueError):
2146
+ continue
2147
+ rng = max(h_f - l_f, 1e-9)
2148
+ net_delta += ((c_f - o_f) / rng) * v_f
2149
+ tot_vol += v_f
2150
  if tot_vol > 0:
2151
  ratio = net_delta / tot_vol
2152
  if ratio > 0.15:
 
2270
  )
2271
  if mark_price <= 0 and merged_ohlcv:
2272
  for tf in ["15m", "1h", "5m"]:
2273
+ bars = merged_ohlcv.get(tf) or []
2274
+ for bar in reversed(bars):
2275
+ raw_px = bar.get("close") if isinstance(bar, dict) else None
2276
+ if raw_px is None:
2277
+ continue
2278
+ try:
2279
+ candidate_px = float(raw_px)
2280
+ except (TypeError, ValueError):
2281
+ continue
2282
  if candidate_px > 0:
2283
  mark_price = candidate_px
2284
  break
2285
+ if mark_price > 0:
2286
+ break
2287
 
2288
  # Compute Orderbook Resting Skew & Whale Block Order Flow for Confluence Scoring
2289
  ob_skew = _compute_orderbook_skew(orderbook, mark_price)
2290
+ whale_flow_data = _compute_whale_order_flow(
2291
+ trades,
2292
+ mark_price,
2293
+ merged_ohlcv=merged_ohlcv,
2294
+ oi_signal=oi_signal,
2295
+ ls_signal=ls_signal,
2296
+ )
2297
 
2298
+ raw_whale_comp = whale_flow_data.get("whale_composite_score")
2299
+ whale_score = int(raw_whale_comp or 0)
2300
  w_buy = whale_flow_data.get("whale_buy_vol_usd", 0.0)
2301
  w_sell = whale_flow_data.get("whale_sell_vol_usd", 0.0)
2302
  t_buy_pct = whale_flow_data.get("taker_buy_pct", 50.0)
2303
  dyn_whale_thresh = float(whale_flow_data.get("dynamic_threshold_usd", 25000.0) or 25000.0)
2304
+ if raw_whale_comp is None:
2305
+ if w_buy > w_sell * 1.4 and w_buy >= dyn_whale_thresh:
2306
+ whale_score = 1
2307
+ elif w_sell > w_buy * 1.4 and w_sell >= dyn_whale_thresh:
2308
+ whale_score = -1
2309
 
2310
  whale_factor = {
2311
  "score": whale_score,
 
2314
  "taker_ratio": whale_flow_data.get("taker_ratio", 1.0),
2315
  "whale_buy_vol_usd": w_buy,
2316
  "whale_sell_vol_usd": w_sell,
2317
+ "sweep_buy_vol_usd": whale_flow_data.get("sweep_buy_vol_usd", 0.0),
2318
+ "sweep_sell_vol_usd": whale_flow_data.get("sweep_sell_vol_usd", 0.0),
2319
+ "sweep_buy_count": whale_flow_data.get("sweep_buy_count", 0),
2320
+ "sweep_sell_count": whale_flow_data.get("sweep_sell_count", 0),
2321
+ "twap_bias": whale_flow_data.get("twap_bias", "NEUTRAL"),
2322
+ "twap_buy_pct": whale_flow_data.get("twap_buy_pct", 50.0),
2323
+ "absorption_type": whale_flow_data.get("absorption_type"),
2324
+ "absorption_note": whale_flow_data.get("absorption_note"),
2325
+ "whale_position_long_ratio": whale_flow_data.get("whale_position_long_ratio"),
2326
+ "retail_account_long_ratio": whale_flow_data.get("retail_account_long_ratio"),
2327
+ "smart_money_delta": whale_flow_data.get("smart_money_delta"),
2328
+ "onchain_whale_wallets": whale_flow_data.get("onchain_whale_wallets", 0),
2329
+ "onchain_buy_vol_usd": whale_flow_data.get("onchain_buy_vol_usd", 0.0),
2330
+ "onchain_sell_vol_usd": whale_flow_data.get("onchain_sell_vol_usd", 0.0),
2331
  }
2332
 
2333
  ob_factor = {
 
2358
  regime_name = mtf_result.get("regime", mtf_result.get("market_condition", "trending"))
2359
  h_thresh_map = horizon_thresholds or {}
2360
 
2361
+ def _apply_contextual_contrarian_gating(h_factors: dict[str, Any]) -> dict[str, Any]:
2362
+ """Neutralize mild (-1/+1) contrarian funding/basis drag when strong MTF structure AND institutional flow confirm a fresh trend."""
2363
+ ms_sc = int(h_factors.get("market_structure", {}).get("score", 0) or 0)
2364
+ sf_sc = int(h_factors.get("spot_futures_cvd", {}).get("score", 0) or 0)
2365
+ wh_sc = int(h_factors.get("whale_order_flow", {}).get("score", 0) or 0)
2366
+ fr_sc = int(h_factors.get("funding_rate", {}).get("score", 0) or 0)
2367
+ bs_sc = int(h_factors.get("basis", {}).get("score", 0) or 0)
2368
+ out = dict(h_factors)
2369
+ if ms_sc >= 2 and (sf_sc >= 1 or wh_sc >= 1):
2370
+ if fr_sc == -1:
2371
+ out["funding_rate"] = {**h_factors["funding_rate"], "score": 0}
2372
+ if bs_sc == -1:
2373
+ out["basis"] = {**h_factors["basis"], "score": 0}
2374
+ elif ms_sc <= -2 and (sf_sc <= -1 or wh_sc <= -1):
2375
+ if fr_sc == 1:
2376
+ out["funding_rate"] = {**h_factors["funding_rate"], "score": 0}
2377
+ if bs_sc == 1:
2378
+ out["basis"] = {**h_factors["basis"], "score": 0}
2379
+ return out
2380
+
2381
+ factors_primary = _apply_contextual_contrarian_gating(dict(factors))
2382
+ factors_intraday = _apply_contextual_contrarian_gating({
2383
  **factors,
2384
+ "oi_divergence": {**oi_signal, "score": oi_signal.get("intraday_score", oi_signal["score"])},
2385
  "market_structure": {**ms_signal, "score": mtf_result.get("intraday_structure", ms_signal["score"])},
2386
+ })
2387
+ factors_swing = _apply_contextual_contrarian_gating({
2388
  **factors,
2389
+ "oi_divergence": {**oi_signal, "score": oi_signal.get("swing_score", oi_signal["score"])},
2390
  "market_structure": {**ms_signal, "score": mtf_result.get("swing_structure", ms_signal["score"])},
2391
+ })
2392
 
2393
  primary_conf = confluence_scorer.compute(
2394
  factors_primary,
 
2585
  avg_fr_val = float(funding_signal["value"]) * 100.0
2586
  avg_fr_val = avg_fr_val or 0.0
2587
 
2588
+ swing_chased_dir = swing_raw_dir if (swing_ac["blocked"] and swing_raw_dir in ("LONG", "SHORT")) else None
2589
+ # Candidate direction before global circuit breakers (including any chased direction)
2590
  candidate_dir = (
2591
  confluence["direction"]
2592
  if confluence["direction"] in ("LONG", "SHORT")
2593
+ else (intra_chased_dir or swing_chased_dir or primary_conf["direction"])
2594
  )
2595
 
2596
  crowded_long_veto = candidate_dir == "LONG" and avg_fr_val > 0.05
 
2682
  sniper_grade = "WAIT"
2683
  elif intra_dir in ("LONG", "SHORT") and sw_dir == intra_dir:
2684
  sf_aligned = (intra_dir == "LONG" and sf_score > 0) or (intra_dir == "SHORT" and sf_score < 0)
2685
+ whale_aligned = (intra_dir == "LONG" and whale_score > 0) or (intra_dir == "SHORT" and whale_score < 0)
2686
  cvd_sc = int(cvd_signal.get("score", 0) or 0)
2687
  ohlcv_cvd_aligned = bool(horizon_thresholds) and (
2688
  (intra_dir == "LONG" and cvd_sc > 0) or (intra_dir == "SHORT" and cvd_sc < 0)
2689
  )
2690
+ if squeeze_active or sf_aligned or whale_aligned or ohlcv_cvd_aligned:
2691
  sniper_grade = "SNIPER_A_PLUS"
2692
  else:
2693
  sniper_grade = "INTRADAY_ONLY"
 
2762
  extremes_data=extremes_data,
2763
  )
2764
 
2765
+ if (
2766
+ confluence["direction"] == "NEUTRAL"
2767
+ and canonical_veto is None
2768
+ and not is_fake_flag
2769
+ and liquidity_guard.get("passed", True)
2770
+ and breakout_radar_data.get("is_breakout_primed")
2771
+ ):
2772
+ if plan.get("action") in ("WAIT", "DO NOT TRADE / WAIT"):
2773
  plan["action"] = "WATCH BREAKOUT"
2774
  if plan.get("quick_verdict"):
2775
  plan["quick_verdict"] = f"{breakout_radar_data['radar_label']}: {breakout_radar_data['catalyst_summary']}"
backend/engine/symbol_resolver.py CHANGED
@@ -7,24 +7,43 @@ across Binance, Bybit, OKX, and Hyperliquid.
7
 
8
  import re
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  def strip_multiplier_prefix(symbol: str) -> str:
12
  """
13
  Strip exchange contract multiplier prefixes (1000, 10000, 1000000, 1000000000, k/K)
14
- from normalized symbols such as 1000PEPEUSDT -> PEPEUSDT, while preserving tokens like 1INCHUSDT.
15
  """
16
  if not symbol:
17
  return ""
18
- s = str(symbol).strip().upper().replace("/", "").replace("-", "").replace("_", "").replace(" ", "")
19
  quote = ""
 
20
  for q in ("USDT", "USDC", "USD", "BUSD", "EUR"):
21
- if s.endswith(q) and len(s) > len(q):
22
  quote = q
23
- s = s[:-len(q)]
24
  break
25
- bare = re.sub(r'^(1000000000|1000000|100000|10000|1000|k)', '', s, flags=re.IGNORECASE)
26
  if not bare:
27
- bare = s
28
  return f"{bare}{quote}"
29
 
30
 
@@ -38,19 +57,23 @@ def get_symbol_variations(symbol: str) -> list[str]:
38
  """
39
  if not symbol:
40
  return []
41
- s = str(symbol).strip().replace("/", "").replace("-", "").replace("_", "").replace(" ", "")
42
 
43
  quote = "USDT"
 
44
  for q in ("USDT", "USDC", "USD", "BUSD", "EUR"):
45
- if s.upper().endswith(q):
46
  quote = q
47
- s = s[:-len(q)]
48
  break
49
 
50
- # Strip existing multiplier prefix if present to get the clean bare token name
51
- bare = re.sub(r'^(1000000000|1000000|100000|10000|1000|k)', '', s, flags=re.IGNORECASE)
52
 
53
- bases = [s, bare, f"1000{bare}", f"10000{bare}", f"1000000{bare}", f"k{bare}", f"K{bare}"]
 
 
 
54
  unique_bases = []
55
  for b in bases:
56
  if b and b not in unique_bases:
 
7
 
8
  import re
9
 
10
+ # Known meme assets where uppercase 'K' denotes a 1000x contract prefix (e.g. Hyperliquid kPEPE -> KPEPE)
11
+ _KNOWN_K_MULTIPLIER_BASES = frozenset({"PEPE", "SHIB", "BONK", "FLOKI", "LUNC", "NEIRO", "DOGS"})
12
+
13
+
14
+ def _strip_multiplier_from_base(raw_base: str) -> str:
15
+ """Strip exchange multiplier prefixes without mangling tickers that start with 'K' (e.g. KAVA, KAS, KSM)."""
16
+ if not raw_base:
17
+ return ""
18
+ stripped = re.sub(r'^(1000000000|1000000|100000|10000|1000)(?=.)', '', raw_base)
19
+ if stripped != raw_base:
20
+ return stripped.upper()
21
+ if raw_base.startswith("k") and len(raw_base) > 1 and raw_base[1].isupper():
22
+ return raw_base[1:].upper()
23
+ upper_base = raw_base.upper()
24
+ if upper_base.startswith("K") and upper_base[1:] in _KNOWN_K_MULTIPLIER_BASES:
25
+ return upper_base[1:]
26
+ return upper_base
27
+
28
 
29
  def strip_multiplier_prefix(symbol: str) -> str:
30
  """
31
  Strip exchange contract multiplier prefixes (1000, 10000, 1000000, 1000000000, k/K)
32
+ from normalized symbols such as 1000PEPEUSDT -> PEPEUSDT, while preserving tokens like 1INCHUSDT and KAVAUSDT.
33
  """
34
  if not symbol:
35
  return ""
36
+ raw = str(symbol).strip().replace("/", "").replace("-", "").replace("_", "").replace(" ", "")
37
  quote = ""
38
+ raw_upper = raw.upper()
39
  for q in ("USDT", "USDC", "USD", "BUSD", "EUR"):
40
+ if raw_upper.endswith(q) and len(raw) > len(q):
41
  quote = q
42
+ raw = raw[:-len(q)]
43
  break
44
+ bare = _strip_multiplier_from_base(raw)
45
  if not bare:
46
+ bare = raw.upper()
47
  return f"{bare}{quote}"
48
 
49
 
 
57
  """
58
  if not symbol:
59
  return []
60
+ raw = str(symbol).strip().replace("/", "").replace("-", "").replace("_", "").replace(" ", "")
61
 
62
  quote = "USDT"
63
+ raw_upper = raw.upper()
64
  for q in ("USDT", "USDC", "USD", "BUSD", "EUR"):
65
+ if raw_upper.endswith(q) and len(raw) > len(q):
66
  quote = q
67
+ raw = raw[:-len(q)]
68
  break
69
 
70
+ upper_base = raw.upper()
71
+ bare = _strip_multiplier_from_base(raw)
72
 
73
+ bases = [upper_base, bare]
74
+ if raw != upper_base and raw not in bases:
75
+ bases.append(raw)
76
+ bases.extend([f"1000{bare}", f"10000{bare}", f"1000000{bare}", f"k{bare}", f"K{bare}"])
77
  unique_bases = []
78
  for b in bases:
79
  if b and b not in unique_bases:
backend/exchanges/base.py CHANGED
@@ -5,6 +5,7 @@ All methods are async-first and must NOT block the event loop.
5
  """
6
 
7
  from abc import ABC, abstractmethod
 
8
  from typing import Any
9
 
10
 
@@ -93,6 +94,65 @@ class BaseExchange(ABC):
93
  # Convenience
94
  # ------------------------------------------------------------------
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  async def get_full_snapshot(self, symbol: str) -> dict[str, Any]:
97
  """
98
  Collect all data for a symbol in one call.
 
5
  """
6
 
7
  from abc import ABC, abstractmethod
8
+ import time
9
  from typing import Any
10
 
11
 
 
94
  # Convenience
95
  # ------------------------------------------------------------------
96
 
97
+ def _record_oi_change(
98
+ self,
99
+ symbol_key: str,
100
+ current_oi: float,
101
+ window_sec: float = 300.0,
102
+ min_sample_gap_sec: float = 30.0,
103
+ max_age_sec: float = 3600.0,
104
+ ) -> float | None:
105
+ """Compute percentage OI change against a rolling ~5m (or oldest recent) baseline."""
106
+ if current_oi <= 0:
107
+ return None
108
+ snaps_map = getattr(self, "_oi_snapshots", None)
109
+ if snaps_map is None:
110
+ snaps_map = {}
111
+ self._oi_snapshots = snaps_map
112
+ now_ts = time.time()
113
+ raw_snaps = snaps_map.get(symbol_key, [])
114
+ # Drop stale snapshots (e.g. after long idle/sleep) to avoid spurious percentage jumps
115
+ snaps = [(ts, val) for ts, val in raw_snaps if (now_ts - ts) <= max_age_sec and val > 0]
116
+ snaps_map[symbol_key] = snaps
117
+
118
+ oi_change_pct = None
119
+ if snaps:
120
+ anchor = next((val for ts, val in reversed(snaps) if (now_ts - ts) >= window_sec), snaps[0][1])
121
+ if anchor > 0:
122
+ oi_change_pct = round((current_oi - anchor) / anchor * 100.0, 4)
123
+
124
+ if not snaps or (now_ts - snaps[-1][0]) >= min_sample_gap_sec:
125
+ snaps.append((now_ts, current_oi))
126
+ if len(snaps) > 64:
127
+ del snaps[:-64]
128
+ return oi_change_pct
129
+
130
+ @staticmethod
131
+ def _compute_oi_horizons(
132
+ oi_series_oldest_first: list[float],
133
+ ) -> tuple[float | None, float | None, float | None]:
134
+ """Compute 15m, 1h (>=5 bars), and 4h (>=13 bars) OI % changes without mislabeling short history."""
135
+ if len(oi_series_oldest_first) < 2:
136
+ return None, None, None
137
+
138
+ curr_oi = oi_series_oldest_first[-1]
139
+ prev_15m = oi_series_oldest_first[-2]
140
+ oi_15m = round(((curr_oi - prev_15m) / prev_15m) * 100.0, 4) if prev_15m > 0 else None
141
+
142
+ oi_1h = None
143
+ if len(oi_series_oldest_first) >= 5:
144
+ prev_1h = oi_series_oldest_first[-5]
145
+ if prev_1h > 0:
146
+ oi_1h = round(((curr_oi - prev_1h) / prev_1h) * 100.0, 4)
147
+
148
+ oi_4h = None
149
+ if len(oi_series_oldest_first) >= 13:
150
+ prev_4h = oi_series_oldest_first[max(0, len(oi_series_oldest_first) - 17)]
151
+ if prev_4h > 0:
152
+ oi_4h = round(((curr_oi - prev_4h) / prev_4h) * 100.0, 4)
153
+
154
+ return oi_15m, oi_1h, oi_4h
155
+
156
  async def get_full_snapshot(self, symbol: str) -> dict[str, Any]:
157
  """
158
  Collect all data for a symbol in one call.
backend/exchanges/binance.py CHANGED
@@ -24,9 +24,12 @@ logger = logging.getLogger(__name__)
24
  # Timeframe mapping: our standard → Binance kline interval
25
  TF_MAP = {
26
  "1m": "1m",
 
27
  "5m": "5m",
28
  "15m": "15m",
 
29
  "1h": "1h",
 
30
  "4h": "4h",
31
  "1d": "1d",
32
  }
@@ -124,7 +127,7 @@ class BinanceClient(BaseExchange):
124
  # Check negative cache to avoid spamming failed probes on every 60s loop
125
  import time
126
  now = time.time()
127
- if symbol in self._negative_cache and (now - self._negative_cache[symbol] < 900):
128
  return False
129
 
130
  # 2. If known symbols empty, trigger bulk load first
@@ -155,7 +158,7 @@ class BinanceClient(BaseExchange):
155
  if self._known_symbols and sym in self._known_symbols:
156
  return True
157
 
158
- self._negative_cache[symbol] = now
159
  return False
160
 
161
  async def get_mark_price(self, symbol: str) -> dict[str, Any]:
@@ -185,32 +188,46 @@ class BinanceClient(BaseExchange):
185
  }
186
 
187
  async def get_open_interest(self, symbol: str) -> dict[str, Any]:
188
- """Fetch current and 15m historical Open Interest to compute change %."""
189
  sym = self.resolve_symbol(symbol)
190
  if not sym:
191
- return {"open_interest": 0.0, "prev_open_interest": None, "oi_change_pct": 0.0, "open_interest_value": None}
 
 
 
 
 
 
 
192
  try:
193
  hist = await self._get(
194
  "/futures/data/openInterestHist",
195
- {"symbol": sym, "period": "15m", "limit": 2},
196
  )
197
  if isinstance(hist, list) and len(hist) >= 2:
198
- # Binance returns oldest to newest: hist[0] is prev, hist[1] is curr
199
- prev_oi = float(hist[0].get("sumOpenInterest", 0))
200
- curr_oi = float(hist[1].get("sumOpenInterest", 0))
201
- oi_change_pct = ((curr_oi - prev_oi) / prev_oi * 100) if prev_oi else 0.0
 
 
 
202
  return {
203
  "open_interest": curr_oi,
204
  "prev_open_interest": prev_oi,
205
- "oi_change_pct": round(oi_change_pct, 4),
206
- "open_interest_value": float(hist[1].get("sumOpenInterestValue", 0)) if hist[1].get("sumOpenInterestValue") else None,
 
 
207
  }
208
  elif isinstance(hist, list) and len(hist) == 1:
209
  curr_oi = float(hist[0].get("sumOpenInterest", 0))
210
  return {
211
  "open_interest": curr_oi,
212
  "prev_open_interest": None,
213
- "oi_change_pct": 0.0,
 
 
214
  "open_interest_value": float(hist[0].get("sumOpenInterestValue", 0)) if hist[0].get("sumOpenInterestValue") else None,
215
  }
216
  except Exception as exc:
@@ -221,45 +238,70 @@ class BinanceClient(BaseExchange):
221
  return {
222
  "open_interest": float(data.get("openInterest", 0)),
223
  "prev_open_interest": None,
224
- "oi_change_pct": 0.0,
 
 
225
  "open_interest_value": None,
226
  }
227
 
228
  async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
229
- """Top-trader account L/S ratio."""
230
  sym = self.resolve_symbol(symbol)
231
  if not sym:
232
  return {"long_ratio": None, "short_ratio": None, "source": "unavailable"}
233
- try:
234
- data = await self._get(
235
- "/futures/data/topLongShortAccountRatio",
236
- {"symbol": sym, "period": period, "limit": 1},
237
- )
238
- if data and "longAccount" in data[0]:
239
- return {
240
- "long_ratio": float(data[0]["longAccount"]),
241
- "short_ratio": float(data[0]["shortAccount"]),
242
- "source": "top_trader",
243
- }
244
- except Exception:
245
- pass
246
 
247
- try:
248
- # Fallback: global L/S ratio
249
- data = await self._get(
250
- "/futures/data/globalLongShortAccountRatio",
251
- {"symbol": sym, "period": period, "limit": 1},
252
- )
253
- if data and "longAccount" in data[0]:
254
- return {
255
- "long_ratio": float(data[0]["longAccount"]),
256
- "short_ratio": float(data[0]["shortAccount"]),
257
- "source": "global",
258
- }
259
- except Exception:
260
- pass
261
 
262
- return {"long_ratio": None, "short_ratio": None, "source": "unavailable"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
 
264
  async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100) -> list[dict]:
265
  sym = self.resolve_symbol(symbol) or symbol
@@ -270,17 +312,21 @@ class BinanceClient(BaseExchange):
270
  )
271
  candles = []
272
  for k in data:
273
- candles.append(
274
- {
275
- "timestamp": k[0],
276
- "open": float(k[1]),
277
- "high": float(k[2]),
278
- "low": float(k[3]),
279
- "close": float(k[4]),
280
- "volume": float(k[5]),
281
- "taker_buy_volume": float(k[9]),
282
- }
283
- )
 
 
 
 
284
  return candles
285
 
286
  async def get_recent_trades(self, symbol: str, limit: int = 500) -> list[dict]:
@@ -293,6 +339,7 @@ class BinanceClient(BaseExchange):
293
  "qty": float(t["qty"]),
294
  "is_buyer_maker": bool(t.get("isBuyerMaker", False)),
295
  "time": int(t["time"]),
 
296
  }
297
  for t in data
298
  ]
@@ -301,10 +348,11 @@ class BinanceClient(BaseExchange):
301
 
302
  async def get_spot_trades(self, symbol: str, limit: int = 500) -> list[dict]:
303
  """Fetch spot trades from Binance Spot API for Spot CVD vs Futures CVD analysis."""
304
- import re
305
- clean_symbol = re.sub(r'^(1000000000|1000000|100000|10000|1000|k)', '', symbol, flags=re.IGNORECASE).upper()
306
- symbols_to_try = [symbol]
307
- if clean_symbol != symbol and clean_symbol.endswith("USDT"):
 
308
  symbols_to_try.append(clean_symbol)
309
 
310
  data = []
@@ -330,6 +378,7 @@ class BinanceClient(BaseExchange):
330
  "qty": float(t["qty"]),
331
  "is_buyer_maker": bool(t.get("isBuyerMaker", False)),
332
  "time": int(t["time"]),
 
333
  }
334
  for t in data
335
  ]
 
24
  # Timeframe mapping: our standard → Binance kline interval
25
  TF_MAP = {
26
  "1m": "1m",
27
+ "3m": "3m",
28
  "5m": "5m",
29
  "15m": "15m",
30
+ "30m": "30m",
31
  "1h": "1h",
32
+ "2h": "2h",
33
  "4h": "4h",
34
  "1d": "1d",
35
  }
 
127
  # Check negative cache to avoid spamming failed probes on every 60s loop
128
  import time
129
  now = time.time()
130
+ if sym in self._negative_cache and (now - self._negative_cache[sym] < 900):
131
  return False
132
 
133
  # 2. If known symbols empty, trigger bulk load first
 
158
  if self._known_symbols and sym in self._known_symbols:
159
  return True
160
 
161
+ self._negative_cache[sym] = now
162
  return False
163
 
164
  async def get_mark_price(self, symbol: str) -> dict[str, Any]:
 
188
  }
189
 
190
  async def get_open_interest(self, symbol: str) -> dict[str, Any]:
191
+ """Fetch current and multi-horizon (15m, 1h, 4h) historical Open Interest to compute change %."""
192
  sym = self.resolve_symbol(symbol)
193
  if not sym:
194
+ return {
195
+ "open_interest": 0.0,
196
+ "prev_open_interest": None,
197
+ "oi_change_pct": None,
198
+ "oi_change_1h_pct": None,
199
+ "oi_change_4h_pct": None,
200
+ "open_interest_value": None,
201
+ }
202
  try:
203
  hist = await self._get(
204
  "/futures/data/openInterestHist",
205
+ {"symbol": sym, "period": "15m", "limit": 17},
206
  )
207
  if isinstance(hist, list) and len(hist) >= 2:
208
+ # Binance returns oldest to newest: hist[-1] is curr, hist[-2] is prev 15m
209
+ series = [float(item.get("sumOpenInterest", 0) or 0) for item in hist]
210
+ curr_item = hist[-1]
211
+ curr_oi = series[-1]
212
+ prev_oi = series[-2]
213
+ oi_15m, oi_1h, oi_4h = self._compute_oi_horizons(series)
214
+
215
  return {
216
  "open_interest": curr_oi,
217
  "prev_open_interest": prev_oi,
218
+ "oi_change_pct": oi_15m,
219
+ "oi_change_1h_pct": oi_1h,
220
+ "oi_change_4h_pct": oi_4h,
221
+ "open_interest_value": float(curr_item.get("sumOpenInterestValue", 0)) if curr_item.get("sumOpenInterestValue") else None,
222
  }
223
  elif isinstance(hist, list) and len(hist) == 1:
224
  curr_oi = float(hist[0].get("sumOpenInterest", 0))
225
  return {
226
  "open_interest": curr_oi,
227
  "prev_open_interest": None,
228
+ "oi_change_pct": None,
229
+ "oi_change_1h_pct": None,
230
+ "oi_change_4h_pct": None,
231
  "open_interest_value": float(hist[0].get("sumOpenInterestValue", 0)) if hist[0].get("sumOpenInterestValue") else None,
232
  }
233
  except Exception as exc:
 
238
  return {
239
  "open_interest": float(data.get("openInterest", 0)),
240
  "prev_open_interest": None,
241
+ "oi_change_pct": None,
242
+ "oi_change_1h_pct": None,
243
+ "oi_change_4h_pct": None,
244
  "open_interest_value": None,
245
  }
246
 
247
  async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
248
+ """Fetch Whale Top-Trader Position/Account L/S ratios alongside Global Retail L/S ratio."""
249
  sym = self.resolve_symbol(symbol)
250
  if not sym:
251
  return {"long_ratio": None, "short_ratio": None, "source": "unavailable"}
 
 
 
 
 
 
 
 
 
 
 
 
 
252
 
253
+ async def _fetch_ls(endpoint: str) -> tuple[float, float] | None:
254
+ try:
255
+ data = await self._get(endpoint, {"symbol": sym, "period": period, "limit": 1})
256
+ if isinstance(data, list) and data and "longAccount" in data[0]:
257
+ return float(data[0]["longAccount"]), float(data[0]["shortAccount"])
258
+ except Exception:
259
+ pass
260
+ return None
 
 
 
 
 
 
261
 
262
+ top_acc, global_acc, top_pos = await asyncio.gather(
263
+ _fetch_ls("/futures/data/topLongShortAccountRatio"),
264
+ _fetch_ls("/futures/data/globalLongShortAccountRatio"),
265
+ _fetch_ls("/futures/data/topLongShortPositionRatio"),
266
+ )
267
+
268
+ top_acc_long = top_acc[0] if top_acc else None
269
+ global_acc_long = global_acc[0] if global_acc else None
270
+ top_pos_long = top_pos[0] if top_pos else None
271
+
272
+ # Retail global account ratio is the true contrarian crowd indicator; fallback to top_acc or top_pos
273
+ primary_long = (
274
+ global_acc_long
275
+ if global_acc_long is not None
276
+ else (top_acc_long if top_acc_long is not None else top_pos_long)
277
+ )
278
+ if primary_long is None:
279
+ return {"long_ratio": None, "short_ratio": None, "source": "unavailable"}
280
+
281
+ primary_short = (
282
+ global_acc[1]
283
+ if global_acc is not None
284
+ else (top_acc[1] if top_acc is not None else (top_pos[1] if top_pos is not None else round(1.0 - primary_long, 4)))
285
+ )
286
+ whale_delta = (
287
+ round(top_pos_long - global_acc_long, 4)
288
+ if (top_pos_long is not None and global_acc_long is not None)
289
+ else 0.0
290
+ )
291
+ source = (
292
+ "smart_money"
293
+ if (top_pos_long is not None and global_acc_long is not None)
294
+ else ("top_trader" if top_acc_long is not None else "global")
295
+ )
296
+ return {
297
+ "long_ratio": primary_long,
298
+ "short_ratio": primary_short,
299
+ "top_position_long_ratio": top_pos_long,
300
+ "top_account_long_ratio": top_acc_long,
301
+ "retail_long_ratio": global_acc_long,
302
+ "whale_retail_delta": whale_delta,
303
+ "source": source,
304
+ }
305
 
306
  async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100) -> list[dict]:
307
  sym = self.resolve_symbol(symbol) or symbol
 
312
  )
313
  candles = []
314
  for k in data:
315
+ c_dict: dict[str, Any] = {
316
+ "timestamp": k[0],
317
+ "open": float(k[1]),
318
+ "high": float(k[2]),
319
+ "low": float(k[3]),
320
+ "close": float(k[4]),
321
+ "volume": float(k[5]),
322
+ }
323
+ if len(k) > 9 and k[9] is not None:
324
+ c_dict["taker_buy_volume"] = float(k[9])
325
+ if len(k) > 7 and k[7] is not None:
326
+ c_dict["quote_volume"] = float(k[7])
327
+ if len(k) > 10 and k[10] is not None:
328
+ c_dict["taker_buy_quote_volume"] = float(k[10])
329
+ candles.append(c_dict)
330
  return candles
331
 
332
  async def get_recent_trades(self, symbol: str, limit: int = 500) -> list[dict]:
 
339
  "qty": float(t["qty"]),
340
  "is_buyer_maker": bool(t.get("isBuyerMaker", False)),
341
  "time": int(t["time"]),
342
+ "venue": "binance",
343
  }
344
  for t in data
345
  ]
 
348
 
349
  async def get_spot_trades(self, symbol: str, limit: int = 500) -> list[dict]:
350
  """Fetch spot trades from Binance Spot API for Spot CVD vs Futures CVD analysis."""
351
+ from engine.symbol_resolver import strip_multiplier_prefix
352
+ raw_sym = symbol.upper().strip().replace("/", "").replace("-", "")
353
+ clean_symbol = strip_multiplier_prefix(symbol)
354
+ symbols_to_try = [raw_sym]
355
+ if clean_symbol and clean_symbol != raw_sym and clean_symbol.endswith(("USDT", "USDC", "USD", "BUSD", "EUR")):
356
  symbols_to_try.append(clean_symbol)
357
 
358
  data = []
 
378
  "qty": float(t["qty"]),
379
  "is_buyer_maker": bool(t.get("isBuyerMaker", False)),
380
  "time": int(t["time"]),
381
+ "venue": "binance_spot",
382
  }
383
  for t in data
384
  ]
backend/exchanges/bitget.py CHANGED
@@ -23,9 +23,12 @@ BITGET_BASE_URL = "https://api.bitget.com"
23
 
24
  TIMEFRAME_MAP = {
25
  "1m": "1m",
 
26
  "5m": "5m",
27
  "15m": "15m",
 
28
  "1h": "1H",
 
29
  "4h": "4H",
30
  "1d": "1Dutc",
31
  }
@@ -73,7 +76,7 @@ class BitgetClient(BaseExchange):
73
  resolved = self.resolve_symbol(symbol)
74
  if resolved:
75
  return resolved
76
- return symbol.upper().strip()
77
 
78
  async def _get(self, path: str, params: dict | None = None) -> Any:
79
  try:
@@ -207,21 +210,24 @@ class BitgetClient(BaseExchange):
207
  sym = self._to_bitget_symbol(symbol)
208
  data = await self._get("/api/v2/mix/market/open-interest", {"productType": "USDT-FUTURES", "symbol": sym})
209
  if not data or not isinstance(data, dict):
210
- return {"open_interest": None, "open_interest_value": None}
211
 
212
  oi_list = data.get("openInterestList", [])
213
  if not oi_list:
214
- return {"open_interest": None, "open_interest_value": None}
215
 
216
  try:
217
  size_coins = float(oi_list[0].get("size", 0.0))
218
  mp_data = await self.get_mark_price(symbol)
219
- mp = mp_data.get("mark_price") or 1.0
220
- oi_usd = size_coins * mp
 
 
 
221
  return {
222
  "open_interest": round(size_coins, 4),
223
- "open_interest_value": round(oi_usd, 2),
224
- "oi_change_pct": None,
225
  }
226
  except (ValueError, TypeError):
227
  return {"open_interest": None, "open_interest_value": None, "oi_change_pct": None}
@@ -307,12 +313,13 @@ class BitgetClient(BaseExchange):
307
  {
308
  "price": float(f["price"]),
309
  "qty": float(f["size"]),
310
- "is_buyer_maker": f.get("side") == "sell",
311
  "time": int(f.get("ts", 0)),
312
  }
313
  )
314
  except (KeyError, ValueError, TypeError):
315
  continue
 
316
  return trades
317
 
318
  async def get_orderbook(self, symbol: str, depth: int = 20) -> dict[str, Any]:
@@ -329,8 +336,15 @@ class BitgetClient(BaseExchange):
329
  return {"bids": [], "asks": []}
330
 
331
  try:
332
- bids = [[float(b[0]), float(b[1])] for b in data.get("bids", [])[:depth] if len(b) >= 2]
333
- asks = [[float(a[0]), float(a[1])] for a in data.get("asks", [])[:depth] if len(a) >= 2]
 
 
 
 
 
 
 
334
  return {"bids": bids, "asks": asks}
335
  except (ValueError, TypeError):
336
  return {"bids": [], "asks": []}
 
23
 
24
  TIMEFRAME_MAP = {
25
  "1m": "1m",
26
+ "3m": "3m",
27
  "5m": "5m",
28
  "15m": "15m",
29
+ "30m": "30m",
30
  "1h": "1H",
31
+ "2h": "2H",
32
  "4h": "4H",
33
  "1d": "1Dutc",
34
  }
 
76
  resolved = self.resolve_symbol(symbol)
77
  if resolved:
78
  return resolved
79
+ return symbol.upper().replace("/", "").replace("-", "").replace("_", "").replace(" ", "").strip()
80
 
81
  async def _get(self, path: str, params: dict | None = None) -> Any:
82
  try:
 
210
  sym = self._to_bitget_symbol(symbol)
211
  data = await self._get("/api/v2/mix/market/open-interest", {"productType": "USDT-FUTURES", "symbol": sym})
212
  if not data or not isinstance(data, dict):
213
+ return {"open_interest": None, "open_interest_value": None, "oi_change_pct": None}
214
 
215
  oi_list = data.get("openInterestList", [])
216
  if not oi_list:
217
+ return {"open_interest": None, "open_interest_value": None, "oi_change_pct": None}
218
 
219
  try:
220
  size_coins = float(oi_list[0].get("size", 0.0))
221
  mp_data = await self.get_mark_price(symbol)
222
+ mp = mp_data.get("mark_price")
223
+ oi_usd = round(size_coins * float(mp), 2) if mp is not None and float(mp) > 0 else None
224
+
225
+ oi_change_pct = self._record_oi_change(sym, size_coins)
226
+
227
  return {
228
  "open_interest": round(size_coins, 4),
229
+ "open_interest_value": oi_usd,
230
+ "oi_change_pct": oi_change_pct,
231
  }
232
  except (ValueError, TypeError):
233
  return {"open_interest": None, "open_interest_value": None, "oi_change_pct": None}
 
313
  {
314
  "price": float(f["price"]),
315
  "qty": float(f["size"]),
316
+ "is_buyer_maker": str(f.get("side", "")).strip().lower() == "sell",
317
  "time": int(f.get("ts", 0)),
318
  }
319
  )
320
  except (KeyError, ValueError, TypeError):
321
  continue
322
+ trades.sort(key=lambda x: x["time"])
323
  return trades
324
 
325
  async def get_orderbook(self, symbol: str, depth: int = 20) -> dict[str, Any]:
 
336
  return {"bids": [], "asks": []}
337
 
338
  try:
339
+ bids = sorted(
340
+ ([float(b[0]), float(b[1])] for b in data.get("bids", []) if len(b) >= 2),
341
+ key=lambda x: x[0],
342
+ reverse=True,
343
+ )[:depth]
344
+ asks = sorted(
345
+ ([float(a[0]), float(a[1])] for a in data.get("asks", []) if len(a) >= 2),
346
+ key=lambda x: x[0],
347
+ )[:depth]
348
  return {"bids": bids, "asks": asks}
349
  except (ValueError, TypeError):
350
  return {"bids": [], "asks": []}
backend/exchanges/bybit.py CHANGED
@@ -20,9 +20,12 @@ logger = logging.getLogger(__name__)
20
 
21
  TF_MAP = {
22
  "1m": "1",
 
23
  "5m": "5",
24
  "15m": "15",
 
25
  "1h": "60",
 
26
  "4h": "240",
27
  "1d": "D",
28
  }
@@ -115,7 +118,7 @@ class BybitClient(BaseExchange):
115
  # Check negative cache to avoid spamming failed probes on every 60s loop
116
  import time
117
  now = time.time()
118
- if symbol in self._negative_cache and (now - self._negative_cache[symbol] < 900):
119
  return False
120
 
121
  # 2. If known symbols empty, trigger bulk load first
@@ -152,7 +155,7 @@ class BybitClient(BaseExchange):
152
  if self._known_symbols and sym in self._known_symbols:
153
  return True
154
 
155
- self._negative_cache[symbol] = now
156
  return False
157
 
158
  async def get_mark_price(self, symbol: str) -> dict[str, Any]:
@@ -165,8 +168,8 @@ class BybitClient(BaseExchange):
165
  if not items:
166
  raise ValueError(f"No ticker data for {sym}")
167
  t = items[0]
168
- mark = float(t.get("markPrice", 0))
169
- index = float(t.get("indexPrice", 0))
170
  basis_pct = ((mark - index) / index * 100) if index else 0.0
171
  return {
172
  "mark_price": mark,
@@ -185,54 +188,76 @@ class BybitClient(BaseExchange):
185
  raise ValueError(f"No ticker data for {sym}")
186
  t = items[0]
187
  return {
188
- "funding_rate": float(t.get("fundingRate", 0)),
189
  "next_funding_time": t.get("nextFundingTime"),
190
  }
191
 
192
  async def get_open_interest(self, symbol: str) -> dict[str, Any]:
193
- """Fetch current and 15m historical Open Interest from Bybit."""
194
  sym = self.resolve_symbol(symbol)
195
  if not sym:
196
- return {"open_interest": 0.0, "prev_open_interest": None, "oi_change_pct": 0.0, "open_interest_value": None}
 
 
 
 
 
 
 
 
 
197
  try:
198
  result = await self._get(
199
  "/v5/market/open-interest",
200
- {"category": "linear", "symbol": sym, "intervalTime": "15min", "limit": 2},
201
  )
202
  items = result.get("list", [])
203
  if len(items) >= 2:
204
- # Bybit returns newest first: items[0] is curr, items[1] is prev
205
- curr_oi = float(items[0].get("openInterest", 0))
206
- prev_oi = float(items[1].get("openInterest", 0))
207
- oi_change_pct = ((curr_oi - prev_oi) / prev_oi * 100) if prev_oi else 0.0
 
208
  return {
209
  "open_interest": curr_oi,
210
  "prev_open_interest": prev_oi,
211
- "oi_change_pct": round(oi_change_pct, 4),
212
- "open_interest_value": None,
 
 
213
  }
214
  elif items:
215
  curr_oi = float(items[0].get("openInterest", 0))
216
  return {
217
  "open_interest": curr_oi,
218
  "prev_open_interest": None,
219
- "oi_change_pct": 0.0,
220
- "open_interest_value": None,
 
 
221
  }
222
  except Exception as exc:
223
  logger.debug("[Bybit] OI fetch note for %s: %s", sym, exc)
224
 
225
  # Fallback to bulk ticker OI if available
226
- bulk_oi = bulk_fetcher.get_bybit_24h_and_oi(symbol)
227
  if bulk_oi and bulk_oi.get("open_interest"):
228
  return {
229
  "open_interest": bulk_oi["open_interest"],
230
  "prev_open_interest": None,
231
- "oi_change_pct": 0.0,
232
- "open_interest_value": bulk_oi.get("open_interest_value"),
 
 
233
  }
234
 
235
- return {"open_interest": 0.0, "prev_open_interest": None, "oi_change_pct": 0.0, "open_interest_value": None}
 
 
 
 
 
 
 
236
 
237
  async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
238
  """
@@ -311,29 +336,36 @@ class BybitClient(BaseExchange):
311
  async def get_spot_trades(self, symbol: str, limit: int = 500) -> list[dict]:
312
  """Fetch spot trades from Bybit Spot market for Spot vs Futures CVD divergence analysis."""
313
  from engine.data_collector import _clean_spot_symbol
 
314
  spot_sym = _clean_spot_symbol(symbol)
 
315
  limit = min(limit, 1000)
316
- try:
317
- result = await self._get(
318
- "/v5/market/recent-trade",
319
- {"category": "spot", "symbol": spot_sym, "limit": limit},
320
- )
321
- trades = []
322
- for t in result.get("list", []):
323
- side = str(t.get("side", "Buy")).strip().lower()
324
- is_buyer_maker = (side == "sell")
325
- trades.append(
326
- {
327
- "price": float(t["price"]),
328
- "qty": float(t["size"]),
329
- "is_buyer_maker": is_buyer_maker,
330
- "time": int(t["time"]),
331
- }
332
  )
333
- trades.sort(key=lambda t: t["time"])
334
- return trades
335
- except Exception:
336
- return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
 
338
  async def get_orderbook(self, symbol: str, depth: int = 20) -> dict[str, Any]:
339
  sym = self.resolve_symbol(symbol) or symbol
 
20
 
21
  TF_MAP = {
22
  "1m": "1",
23
+ "3m": "3",
24
  "5m": "5",
25
  "15m": "15",
26
+ "30m": "30",
27
  "1h": "60",
28
+ "2h": "120",
29
  "4h": "240",
30
  "1d": "D",
31
  }
 
118
  # Check negative cache to avoid spamming failed probes on every 60s loop
119
  import time
120
  now = time.time()
121
+ if sym in self._negative_cache and (now - self._negative_cache[sym] < 900):
122
  return False
123
 
124
  # 2. If known symbols empty, trigger bulk load first
 
155
  if self._known_symbols and sym in self._known_symbols:
156
  return True
157
 
158
+ self._negative_cache[sym] = now
159
  return False
160
 
161
  async def get_mark_price(self, symbol: str) -> dict[str, Any]:
 
168
  if not items:
169
  raise ValueError(f"No ticker data for {sym}")
170
  t = items[0]
171
+ mark = float(t.get("markPrice") or 0)
172
+ index = float(t.get("indexPrice") or 0)
173
  basis_pct = ((mark - index) / index * 100) if index else 0.0
174
  return {
175
  "mark_price": mark,
 
188
  raise ValueError(f"No ticker data for {sym}")
189
  t = items[0]
190
  return {
191
+ "funding_rate": float(t.get("fundingRate") or 0),
192
  "next_funding_time": t.get("nextFundingTime"),
193
  }
194
 
195
  async def get_open_interest(self, symbol: str) -> dict[str, Any]:
196
+ """Fetch current and multi-horizon (15m, 1h, 4h) historical Open Interest from Bybit."""
197
  sym = self.resolve_symbol(symbol)
198
  if not sym:
199
+ return {
200
+ "open_interest": 0.0,
201
+ "prev_open_interest": None,
202
+ "oi_change_pct": None,
203
+ "oi_change_1h_pct": None,
204
+ "oi_change_4h_pct": None,
205
+ "open_interest_value": None,
206
+ }
207
+ bulk_oi = bulk_fetcher.get_bybit_24h_and_oi(symbol)
208
+ bulk_oi_val = bulk_oi.get("open_interest_value") if bulk_oi else None
209
  try:
210
  result = await self._get(
211
  "/v5/market/open-interest",
212
+ {"category": "linear", "symbol": sym, "intervalTime": "15min", "limit": 17},
213
  )
214
  items = result.get("list", [])
215
  if len(items) >= 2:
216
+ # Bybit returns newest first: reverse to oldest->newest for shared horizon calculation
217
+ series = [float(item.get("openInterest", 0) or 0) for item in reversed(items)]
218
+ curr_oi = series[-1]
219
+ prev_oi = series[-2]
220
+ oi_15m, oi_1h, oi_4h = self._compute_oi_horizons(series)
221
  return {
222
  "open_interest": curr_oi,
223
  "prev_open_interest": prev_oi,
224
+ "oi_change_pct": oi_15m,
225
+ "oi_change_1h_pct": oi_1h,
226
+ "oi_change_4h_pct": oi_4h,
227
+ "open_interest_value": bulk_oi_val,
228
  }
229
  elif items:
230
  curr_oi = float(items[0].get("openInterest", 0))
231
  return {
232
  "open_interest": curr_oi,
233
  "prev_open_interest": None,
234
+ "oi_change_pct": None,
235
+ "oi_change_1h_pct": None,
236
+ "oi_change_4h_pct": None,
237
+ "open_interest_value": bulk_oi_val,
238
  }
239
  except Exception as exc:
240
  logger.debug("[Bybit] OI fetch note for %s: %s", sym, exc)
241
 
242
  # Fallback to bulk ticker OI if available
 
243
  if bulk_oi and bulk_oi.get("open_interest"):
244
  return {
245
  "open_interest": bulk_oi["open_interest"],
246
  "prev_open_interest": None,
247
+ "oi_change_pct": None,
248
+ "oi_change_1h_pct": None,
249
+ "oi_change_4h_pct": None,
250
+ "open_interest_value": bulk_oi_val,
251
  }
252
 
253
+ return {
254
+ "open_interest": 0.0,
255
+ "prev_open_interest": None,
256
+ "oi_change_pct": None,
257
+ "oi_change_1h_pct": None,
258
+ "oi_change_4h_pct": None,
259
+ "open_interest_value": None,
260
+ }
261
 
262
  async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
263
  """
 
336
  async def get_spot_trades(self, symbol: str, limit: int = 500) -> list[dict]:
337
  """Fetch spot trades from Bybit Spot market for Spot vs Futures CVD divergence analysis."""
338
  from engine.data_collector import _clean_spot_symbol
339
+ raw_sym = symbol.upper().replace("-", "").replace("/", "").replace("_", "").strip()
340
  spot_sym = _clean_spot_symbol(symbol)
341
+ probe_syms = [raw_sym] if raw_sym == spot_sym else [raw_sym, spot_sym]
342
  limit = min(limit, 1000)
343
+ for cand_sym in probe_syms:
344
+ try:
345
+ result = await self._get(
346
+ "/v5/market/recent-trade",
347
+ {"category": "spot", "symbol": cand_sym, "limit": limit},
 
 
 
 
 
 
 
 
 
 
 
348
  )
349
+ raw_list = result.get("list") or []
350
+ if not raw_list:
351
+ continue
352
+ trades = []
353
+ for t in raw_list:
354
+ side = str(t.get("side", "Buy")).strip().lower()
355
+ is_buyer_maker = (side == "sell")
356
+ trades.append(
357
+ {
358
+ "price": float(t["price"]),
359
+ "qty": float(t["size"]),
360
+ "is_buyer_maker": is_buyer_maker,
361
+ "time": int(t["time"]),
362
+ }
363
+ )
364
+ trades.sort(key=lambda t: t["time"])
365
+ return trades
366
+ except Exception:
367
+ continue
368
+ return []
369
 
370
  async def get_orderbook(self, symbol: str, depth: int = 20) -> dict[str, Any]:
371
  sym = self.resolve_symbol(symbol) or symbol
backend/exchanges/hyperliquid.py CHANGED
@@ -44,10 +44,10 @@ class HyperliquidClient:
44
  self._lock = asyncio.Lock()
45
 
46
  def _format_symbol(self, symbol: str) -> str:
47
- """Strip quote currency (e.g. BTCUSDT -> BTC) preserving case."""
48
- sym = str(symbol).strip()
49
  for q in ("USDT", "USDC", "USD", "BUSD", "EUR"):
50
- if sym.upper().endswith(q):
51
  return sym[:-len(q)]
52
  return sym
53
 
@@ -130,6 +130,58 @@ class HyperliquidClient:
130
  logger.debug("[Hyperliquid] Error fetching orderbook for %s: %s", coin, exc)
131
  return None
132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  async def get_market_data(self, symbol: str) -> dict[str, Any] | None:
134
  """
135
  Fetch funding rate, open interest, mark price, and premium for symbol.
 
44
  self._lock = asyncio.Lock()
45
 
46
  def _format_symbol(self, symbol: str) -> str:
47
+ """Strip delimiters & quote currency (e.g. BTC/USDT, kPEPE-USDT -> BTC, kPEPE) preserving case."""
48
+ sym = str(symbol).replace("/", "").replace("-", "").replace("_", "").strip()
49
  for q in ("USDT", "USDC", "USD", "BUSD", "EUR"):
50
+ if sym.upper().endswith(q) and len(sym) > len(q):
51
  return sym[:-len(q)]
52
  return sym
53
 
 
130
  logger.debug("[Hyperliquid] Error fetching orderbook for %s: %s", coin, exc)
131
  return None
132
 
133
+ async def get_recent_trades(self, symbol: str, limit: int = 500) -> list[dict]:
134
+ """
135
+ Fetch recent on-chain trades from Hyperliquid DEX including wallet addresses (`users`).
136
+ """
137
+ await self._refresh_meta()
138
+ coin = self.resolve_coin(symbol)
139
+ if not coin:
140
+ return []
141
+ try:
142
+ resp = await self._client.post(
143
+ HYPERLIQUID_INFO_URL,
144
+ json={"type": "recentTrades", "coin": coin},
145
+ )
146
+ resp.raise_for_status()
147
+ data = resp.json()
148
+ if not isinstance(data, list):
149
+ return []
150
+ trades = []
151
+ for t in data:
152
+ try:
153
+ px = float(t.get("px", 0.0))
154
+ sz = float(t.get("sz", 0.0))
155
+ if px <= 0 or sz <= 0:
156
+ continue
157
+ side_str = str(t.get("side", "B")).upper()
158
+ # In Hyperliquid: 'B' = Bid/Buy aggressor (is_buyer_maker=False), 'A' = Ask/Sell aggressor (is_buyer_maker=True)
159
+ is_buyer_maker = side_str in ("A", "SELL", "S")
160
+ users = t.get("users")
161
+ taker_wallet = None
162
+ if isinstance(users, list) and len(users) >= 2:
163
+ # Hyperliquid users tuple is [buyer, seller]: sell aggressor (is_buyer_maker=True) -> users[1], buy aggressor -> users[0]
164
+ raw_wallet = users[1] if is_buyer_maker else users[0]
165
+ if raw_wallet:
166
+ taker_wallet = str(raw_wallet)
167
+ trades.append({
168
+ "price": px,
169
+ "qty": sz,
170
+ "is_buyer_maker": is_buyer_maker,
171
+ "time": int(t.get("time", 0) or 0),
172
+ "venue": "hyperliquid",
173
+ "taker_wallet": taker_wallet,
174
+ })
175
+ except (ValueError, TypeError):
176
+ continue
177
+ trades.sort(key=lambda x: x["time"])
178
+ if limit > 0 and len(trades) > limit:
179
+ trades = trades[-limit:]
180
+ return trades
181
+ except Exception as exc:
182
+ logger.debug("[Hyperliquid] Error fetching recentTrades for %s: %s", coin, exc)
183
+ return []
184
+
185
  async def get_market_data(self, symbol: str) -> dict[str, Any] | None:
186
  """
187
  Fetch funding rate, open interest, mark price, and premium for symbol.
backend/exchanges/okx.py CHANGED
@@ -11,6 +11,7 @@ Provides:
11
 
12
  import asyncio
13
  import logging
 
14
  from typing import Any
15
 
16
  import httpx
@@ -28,9 +29,12 @@ OKX_BASE_URL = "https://www.okx.com"
28
 
29
  TF_MAP = {
30
  "1m": "1m",
 
31
  "5m": "5m",
32
  "15m": "15m",
 
33
  "1h": "1H",
 
34
  "4h": "4H",
35
  "1d": "1D",
36
  }
@@ -72,14 +76,18 @@ class OKXClient(BaseExchange):
72
  return None
73
 
74
  def _to_inst_id(self, symbol: str) -> str:
75
- """Convert any symbol (e.g. BTCUSDT, 1000PEPEUSDT) -> OKX instId."""
76
  resolved = self.resolve_inst_id(symbol)
77
  if resolved:
78
  return resolved
79
- sym = symbol.upper().strip()
80
- if sym.endswith("USDT"):
81
- base = sym[:-4]
82
- return f"{base}-USDT-SWAP"
 
 
 
 
83
  return f"{sym}-SWAP"
84
 
85
  async def _get(self, path: str, params: dict | None = None) -> Any:
@@ -120,10 +128,12 @@ class OKXClient(BaseExchange):
120
  if self.resolve_inst_id(symbol):
121
  return True
122
 
 
 
123
  # Check negative cache to avoid spamming failed probes on every 60s loop
124
  import time
125
  now = time.time()
126
- if symbol in self._negative_cache and (now - self._negative_cache[symbol] < 900):
127
  return False
128
 
129
  # 2. Ensure known symbols are loaded via single bulk call
@@ -133,7 +143,7 @@ class OKXClient(BaseExchange):
133
  return True
134
 
135
  # 3. Direct lightweight probe fallback (only target most probable instrument IDs)
136
- clean = symbol.upper().replace("/", "").replace("-", "")
137
  base = clean[:-4] if clean.endswith("USDT") or clean.endswith("USDC") else clean
138
  candidates = [f"{base}-USDT-SWAP", f"{clean}-SWAP"]
139
  for inst_cand in candidates:
@@ -146,13 +156,13 @@ class OKXClient(BaseExchange):
146
  if resp.status_code == 200:
147
  data = resp.json()
148
  if data.get("code") == "0" and len(data.get("data", [])) > 0:
149
- self._known_symbols.add(symbol.upper())
150
- self._inst_map[symbol.upper()] = inst_cand
151
  return True
152
  except Exception:
153
  pass
154
 
155
- self._negative_cache[symbol] = now
156
  return False
157
 
158
  async def get_mark_price(self, symbol: str) -> dict[str, Any]:
@@ -226,14 +236,18 @@ class OKXClient(BaseExchange):
226
  inst_id = self._to_inst_id(symbol)
227
  data = await self._get("/api/v5/public/open-interest", {"instType": "SWAP", "instId": inst_id})
228
  if not data:
229
- return {"open_interest": 0.0, "open_interest_value": None}
230
  oi = float(data[0].get("oiCcy", 0.0))
231
  # OKX returns oi (contracts), oiCcy (base coins), and oiUsd (USD notional value)
232
  oi_usd = data[0].get("oiUsd")
233
  oi_val = float(oi_usd) if oi_usd is not None and oi_usd != "" else None
 
 
 
234
  return {
235
  "open_interest": oi,
236
  "open_interest_value": oi_val,
 
237
  }
238
 
239
  async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
@@ -254,6 +268,8 @@ class OKXClient(BaseExchange):
254
  if data and len(data) > 0:
255
  # OKX returns [ts, ratio] where ratio = long_accounts / short_accounts
256
  ratio = float(data[0][1])
 
 
257
  # Convert ratio = L / S where L + S = 1 => L = ratio / (1 + ratio)
258
  long_ratio = ratio / (1.0 + ratio)
259
  short_ratio = 1.0 - long_ratio
 
11
 
12
  import asyncio
13
  import logging
14
+ import time
15
  from typing import Any
16
 
17
  import httpx
 
29
 
30
  TF_MAP = {
31
  "1m": "1m",
32
+ "3m": "3m",
33
  "5m": "5m",
34
  "15m": "15m",
35
+ "30m": "30m",
36
  "1h": "1H",
37
+ "2h": "2H",
38
  "4h": "4H",
39
  "1d": "1D",
40
  }
 
76
  return None
77
 
78
  def _to_inst_id(self, symbol: str) -> str:
79
+ """Convert any symbol (e.g. BTCUSDT, BTC/USDC, 1000PEPEUSDT) -> OKX instId."""
80
  resolved = self.resolve_inst_id(symbol)
81
  if resolved:
82
  return resolved
83
+ raw_upper = symbol.upper().strip()
84
+ if raw_upper.endswith("-SWAP") and "-" in raw_upper[:-5]:
85
+ return raw_upper
86
+ sym = raw_upper.replace("/", "").replace("-", "").replace("_", "").replace(" ", "")
87
+ for quote in ("USDT", "USDC", "USD", "EUR"):
88
+ if sym.endswith(quote) and len(sym) > len(quote):
89
+ base = sym[:-len(quote)]
90
+ return f"{base}-{quote}-SWAP"
91
  return f"{sym}-SWAP"
92
 
93
  async def _get(self, path: str, params: dict | None = None) -> Any:
 
128
  if self.resolve_inst_id(symbol):
129
  return True
130
 
131
+ sym_key = symbol.strip().upper().replace("/", "").replace("-", "")
132
+
133
  # Check negative cache to avoid spamming failed probes on every 60s loop
134
  import time
135
  now = time.time()
136
+ if sym_key in self._negative_cache and (now - self._negative_cache[sym_key] < 900):
137
  return False
138
 
139
  # 2. Ensure known symbols are loaded via single bulk call
 
143
  return True
144
 
145
  # 3. Direct lightweight probe fallback (only target most probable instrument IDs)
146
+ clean = sym_key
147
  base = clean[:-4] if clean.endswith("USDT") or clean.endswith("USDC") else clean
148
  candidates = [f"{base}-USDT-SWAP", f"{clean}-SWAP"]
149
  for inst_cand in candidates:
 
156
  if resp.status_code == 200:
157
  data = resp.json()
158
  if data.get("code") == "0" and len(data.get("data", [])) > 0:
159
+ self._known_symbols.add(sym_key)
160
+ self._inst_map[sym_key] = inst_cand
161
  return True
162
  except Exception:
163
  pass
164
 
165
+ self._negative_cache[sym_key] = now
166
  return False
167
 
168
  async def get_mark_price(self, symbol: str) -> dict[str, Any]:
 
236
  inst_id = self._to_inst_id(symbol)
237
  data = await self._get("/api/v5/public/open-interest", {"instType": "SWAP", "instId": inst_id})
238
  if not data:
239
+ return {"open_interest": 0.0, "open_interest_value": None, "oi_change_pct": None}
240
  oi = float(data[0].get("oiCcy", 0.0))
241
  # OKX returns oi (contracts), oiCcy (base coins), and oiUsd (USD notional value)
242
  oi_usd = data[0].get("oiUsd")
243
  oi_val = float(oi_usd) if oi_usd is not None and oi_usd != "" else None
244
+
245
+ oi_change_pct = self._record_oi_change(inst_id, oi)
246
+
247
  return {
248
  "open_interest": oi,
249
  "open_interest_value": oi_val,
250
+ "oi_change_pct": oi_change_pct,
251
  }
252
 
253
  async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
 
268
  if data and len(data) > 0:
269
  # OKX returns [ts, ratio] where ratio = long_accounts / short_accounts
270
  ratio = float(data[0][1])
271
+ if ratio < 0:
272
+ return None
273
  # Convert ratio = L / S where L + S = 1 => L = ratio / (1 + ratio)
274
  long_ratio = ratio / (1.0 + ratio)
275
  short_ratio = 1.0 - long_ratio
backend/main.py CHANGED
@@ -68,6 +68,15 @@ from engine.doh_resolver import enable_doh_bypass
68
  enable_doh_bypass()
69
 
70
  signal_engine = SignalEngine()
 
 
 
 
 
 
 
 
 
71
 
72
 
73
  # ─────────────────────────────────────────────────────────────────────────────
@@ -385,12 +394,12 @@ async def lifespan(app: FastAPI):
385
 
386
  if not is_serverless:
387
  # Warm up symbol caches and bulk market pre-fetcher in non-blocking background tasks on persistent boot
388
- asyncio.create_task(bulk_fetcher.refresh_if_stale(force=True))
389
- asyncio.create_task(binance._load_symbols())
390
- asyncio.create_task(bybit._load_symbols())
391
- asyncio.create_task(okx._load_symbols())
392
- asyncio.create_task(bitget._refresh_symbols_universe())
393
- asyncio.create_task(hyperliquid._refresh_meta())
394
 
395
  # Dedicated DB retention janitor worker (runs every 30 minutes in the background)
396
  async def _retention_janitor_loop():
@@ -628,7 +637,7 @@ async def add_pair(body: AddPairRequest, request: Request):
628
  pair = await async_get_pair(symbol)
629
  collector = getattr(request.app.state, "collector", None)
630
  if collector and pair:
631
- asyncio.create_task(_process_pair(pair, collector))
632
  return pair
633
 
634
  binance: BinanceClient = request.app.state.binance
@@ -694,7 +703,7 @@ async def add_pair(body: AddPairRequest, request: Request):
694
  # Immediately compute signal in background for the newly added pair
695
  collector = getattr(request.app.state, "collector", None)
696
  if collector:
697
- asyncio.create_task(_process_pair(pair, collector))
698
 
699
  return pair
700
 
@@ -783,7 +792,14 @@ if os.path.exists(STATIC_DIR):
783
  ):
784
  raise HTTPException(status_code=404, detail="Not Found")
785
 
786
- target_file = os.path.join(STATIC_DIR, full_path)
 
 
 
 
 
 
 
787
  if os.path.isfile(target_file):
788
  return FileResponse(target_file)
789
 
 
68
  enable_doh_bypass()
69
 
70
  signal_engine = SignalEngine()
71
+ _background_tasks: set[asyncio.Task] = set()
72
+
73
+
74
+ def _spawn_background_task(coro: Any) -> asyncio.Task:
75
+ """Create a background task with a strong reference so GC cannot drop it prematurely."""
76
+ task = asyncio.create_task(coro)
77
+ _background_tasks.add(task)
78
+ task.add_done_callback(_background_tasks.discard)
79
+ return task
80
 
81
 
82
  # ─────────────────────────────────────────────────────────────────────────────
 
394
 
395
  if not is_serverless:
396
  # Warm up symbol caches and bulk market pre-fetcher in non-blocking background tasks on persistent boot
397
+ _spawn_background_task(bulk_fetcher.refresh_if_stale(force=True))
398
+ _spawn_background_task(binance._load_symbols())
399
+ _spawn_background_task(bybit._load_symbols())
400
+ _spawn_background_task(okx._load_symbols())
401
+ _spawn_background_task(bitget._refresh_symbols_universe())
402
+ _spawn_background_task(hyperliquid._refresh_meta())
403
 
404
  # Dedicated DB retention janitor worker (runs every 30 minutes in the background)
405
  async def _retention_janitor_loop():
 
637
  pair = await async_get_pair(symbol)
638
  collector = getattr(request.app.state, "collector", None)
639
  if collector and pair:
640
+ _spawn_background_task(_process_pair(pair, collector))
641
  return pair
642
 
643
  binance: BinanceClient = request.app.state.binance
 
703
  # Immediately compute signal in background for the newly added pair
704
  collector = getattr(request.app.state, "collector", None)
705
  if collector:
706
+ _spawn_background_task(_process_pair(pair, collector))
707
 
708
  return pair
709
 
 
792
  ):
793
  raise HTTPException(status_code=404, detail="Not Found")
794
 
795
+ static_root = os.path.realpath(STATIC_DIR)
796
+ target_file = os.path.realpath(os.path.join(static_root, full_path))
797
+ try:
798
+ in_static = os.path.commonpath([static_root, target_file]) == static_root
799
+ except ValueError:
800
+ in_static = False
801
+ if not in_static:
802
+ raise HTTPException(status_code=404, detail="Not Found")
803
  if os.path.isfile(target_file):
804
  return FileResponse(target_file)
805
 
backend/routers/ai.py CHANGED
@@ -8,9 +8,12 @@ import os
8
  import re
9
  import time
10
  import asyncio
 
11
  import logging
 
12
  from datetime import datetime, timezone
13
  from typing import Any
 
14
 
15
  import httpx
16
  from fastapi import APIRouter, HTTPException, Request
@@ -49,6 +52,7 @@ def get_ai_http_client() -> httpx.AsyncClient:
49
  _AI_HTTP_CLIENT = httpx.AsyncClient(
50
  timeout=None,
51
  verify=True,
 
52
  limits=httpx.Limits(
53
  max_keepalive_connections=10,
54
  max_connections=25,
@@ -262,18 +266,14 @@ def _build_ai_prompt(
262
  if snapshots:
263
  for s in snapshots:
264
  ex = s.get("exchange", "")
265
- oi_val = s.get("oi") or s.get("open_interest") or 0.0
266
- px = s.get("mark_price") or mark_price
267
- oi_usd = oi_val if oi_val > 1e6 else (oi_val * px if px else 0.0)
268
  if oi_usd > 0:
269
  total_oi_usd += oi_usd
270
  venue_oi_str_list.append(f"{ex.upper()}: {_fmt_usd(oi_usd)}")
271
  else:
272
  for ex, d in active_exch_data.items():
273
  if not d: continue
274
- oi_val = d.get("oi") or 0.0
275
- px = d.get("mark_price") or mark_price
276
- oi_usd = oi_val if oi_val > 1e6 else (oi_val * px if px else 0.0)
277
  if oi_usd > 0:
278
  total_oi_usd += oi_usd
279
  venue_oi_str_list.append(f"{ex.upper()}: {_fmt_usd(oi_usd)}")
@@ -288,10 +288,8 @@ def _build_ai_prompt(
288
  fr = d.get("funding_rate")
289
  if fr is not None:
290
  fr_vals.append(float(fr))
291
- oi_raw = float(d.get("oi") or d.get("open_interest") or 0.0)
292
- px_raw = float(d.get("mark_price") or mark_price or 0.0)
293
- oi_usd_w = oi_raw if oi_raw > 1e6 else (oi_raw * px_raw if px_raw > 0 else oi_raw)
294
- fr_weights.append(oi_usd_w)
295
  avg_fr_8h = _oi_weighted_average(fr_vals, fr_weights) if fr_vals else 0.0
296
  avg_fr_8h_pct = avg_fr_8h * 100
297
  annualized_apr_pct = avg_fr_8h * 3 * 365 * 100
@@ -315,7 +313,7 @@ def _build_ai_prompt(
315
  bitget_ls = f"{bitget.get('long_ratio', 0)*100:.1f}%L" if bitget.get('long_ratio') else "N/A"
316
 
317
  cross = factors.get("cross_exchange") or {}
318
- div_pct = cross.get("divergence_pct", 0.0)
319
 
320
  # 3. CVD & Flow
321
  spot_fut = factors.get("spot_futures_cvd") or {}
@@ -327,42 +325,104 @@ def _build_ai_prompt(
327
  spot_status_str = "Pasar Spot Riil Terdaftar (Likuiditas Organik Ada)" if has_spot else "⚠️ PERP-ONLY (Sintetis 100%, rawan wick sweep & manipulasi bandar)"
328
 
329
  # Hyperliquid
330
- hl_basis = hl.get("basis_pct", 0.0)
331
  hl_sig = factors.get("hyperliquid") or {}
332
  hl_label = hl_sig.get("label", "Equilibrium")
333
 
334
  # OI Divergence
335
  oi_div = factors.get("oi_divergence") or {}
336
  oi_div_str = oi_div.get("direction_val") or oi_div.get("value") or oi_div.get("label", "Balanced Market Flow")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
 
338
  # 4. Multi-Timeframe & Squeeze
339
  ms = factors.get("market_structure") or {}
340
- active_tf = ms.get("tf", "1h")
341
  struct_map = ms.get("structure_per_tf") or {}
342
 
343
  squeeze = pred.get("volatility_squeeze") or {}
344
- squeeze_intensity = squeeze.get("squeeze_intensity", "NORMAL")
345
- compression_ratio = squeeze.get("compression_ratio", 1.0)
 
346
 
347
  # Orderbook depth skew
348
  ob_skew = pred.get("orderbook_skew") or {}
349
- resting_pressure = ob_skew.get("resting_pressure", "BALANCED")
350
- bid_depth = ob_skew.get("bid_depth_usd", 0.0)
351
- ask_depth = ob_skew.get("ask_depth_usd", 0.0)
352
  depth_ratio = (bid_depth / ask_depth) if ask_depth > 0 else (99.0 if bid_depth > 0 else 1.0)
353
 
354
  # Liquidation Magnets & Predictive Targets
355
  magnets = pred.get("liquidation_magnets") or {}
356
- upper_mag = magnets.get("upper_magnet_str", "N/A")
357
- lower_mag = magnets.get("lower_magnet_str", "N/A")
358
- dist_up = magnets.get("dist_upper_pct", 0.0)
359
- dist_down = magnets.get("dist_lower_pct", 0.0)
360
 
361
  pred_target = pred.get("predicted_target")
362
  pred_target_str = _fmt_px(pred_target) if pred_target else "N/A"
363
- target_type = pred.get("target_type", "N/A")
364
- target_dist_pct = pred.get("target_dist_pct", 0.0)
365
- anticipation_text = pred.get("anticipation", "Menunggu konfirmasi momentum likuiditas.")
366
 
367
  # 5. Confluence Consensus & Streak
368
  conviction = signal.get("conviction", 0) if signal else (signals_data.get("conviction", 0))
@@ -375,8 +435,12 @@ def _build_ai_prompt(
375
  neutral_signals = []
376
  for k, v in factors.items():
377
  if isinstance(v, dict):
378
- sc = v.get("score", 0)
379
- lbl = v.get("label", k)
 
 
 
 
380
  if sc > 0: bullish_signals.append(f"{k} (+{sc}): {lbl}")
381
  elif sc < 0: bearish_signals.append(f"{k} ({sc}): {lbl}")
382
  else: neutral_signals.append(f"{k} (0): {lbl}")
@@ -411,7 +475,7 @@ def _build_ai_prompt(
411
  # 7. Fakeout / Manipulation Detector
412
  fake_det = factors.get("fake_detector") or {}
413
  is_fake = fake_det.get("is_fake", False)
414
- fake_reason = fake_det.get("reason", "")
415
  fake_status_str = f"🚨 TERDETEKSI MANIPULASI HARGA: {fake_reason}" if is_fake else "✅ Bersih (Tidak terdeteksi anomali wick sweep / divergensi spread manipulatif)"
416
 
417
  # Pre-calculated trade levels (if existing in signal engine)
@@ -543,6 +607,16 @@ PERATURAN KRITIS UNTUK DAMIAN:
543
  [1-2 poin tindakan taktis praktis menanggapi kondisi yang ditanyakan user]
544
  """
545
 
 
 
 
 
 
 
 
 
 
 
546
  prompt = f"""Role: Damian — Senior Institutional Crypto Derivatives Quantitative Strategist.
547
  Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presisi kuantitatif, dan tanpa basa-basi pembuka/penutup.
548
 
@@ -556,15 +630,15 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi
556
  2. HARGA MULTI-BURSA, DISPARITAS LEAD-LAG & LIKUIDITAS
557
  • Mark Price Utama: {_fmt_px(mark_price)} | Index Price: {_fmt_px(index_price)} | Basis Spread: {div_pct:+.3f}%
558
  • Matrix Harga Bursa: Binance: {_px_venue(binance_px)} | Bybit: {_px_venue(bybit_px)} | OKX: {_px_venue(okx_px)} | Bitget: {_px_venue(bitget_px)} | Hyperliquid DEX: {_px_venue(hl_px)}
559
- • 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')}
560
  • Total Open Interest Agregat (5 Bursa): {total_oi_str} ({venue_oi_breakdown})
561
  • Status Pasar: {spot_status_str}
562
 
563
  3. EXTREMES 24 JAM & PROFIL RENTANG HARGA
564
- • 24H High: {_fmt_px(extremes.get('high_24h', mark_price))} ({extremes.get('dist_to_high_pct', 0.0):+.2f}% dari harga saat ini)
565
- • 24H Low: {_fmt_px(extremes.get('low_24h', mark_price))} ({extremes.get('dist_to_low_pct', 0.0):+.2f}% dari harga saat ini)
566
- • Rentang 24H: {_fmt_px(extremes.get('range_usd', 0.0))} ({extremes.get('range_pct', 0.0):.2f}% rentang volatilitas)
567
- • Posisi Rentang: {extremes.get('range_position_pct', 50.0):.1f}% -> {extremes.get('zone_label', 'Equilibrium')}
568
 
569
  4. FUNDING RATES, COUNTDOWN SETTLEMENT & ANNUALIZED CARRY (APR %)
570
  • Rata-rata Funding Rate 8H: {avg_fr_8h_pct:+.4f}% | Annualized APR: {annualized_apr_pct:+.2f}% APR
@@ -574,14 +648,16 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi
574
 
575
  5. ORDER FLOW INSTITUSIONAL, WHALE BLOCK TRADES & CVD
576
  • Spot CVD: {spot_cvd} | Futures CVD: {fut_cvd} -> Status Aliran: {cvd_label}
577
- • 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)
578
- • 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})
579
- • Trade Terbesar: {_fmt_usd(whale_flow.get('largest_trade_usd', 0.0))} ({whale_flow.get('largest_trade_side', 'NONE')}) -> {whale_flow.get('flow_verdict', '')}
 
 
580
  • Hyperliquid DEX Whale Flow: {hl_label} (Basis Mark-Oracle: {hl_basis:+.3f}%)
581
  • Open Interest Divergence: {oi_div_str}
582
 
583
  6. STRUKTUR MULTI-TIMEFRAME (MTF), VOLATILITAS & ORDERBOOK
584
- • 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()})
585
  • Volatility Squeeze: {squeeze_intensity} (Compression Ratio: {compression_ratio:.2f})
586
  • Radar Squeeze & Breakout: {breakout.get('radar_label')} | Stage: {breakout.get('squeeze_stage')} | Proyeksi Arah: {breakout.get('projected_direction')}
587
  • Katalis Breakout: {breakout.get('catalyst_summary')}
@@ -610,8 +686,8 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi
610
  "mark_price_str": _fmt_px(mark_price),
611
  "total_oi_usd": total_oi_usd,
612
  "total_oi_str": total_oi_str,
613
- "avg_fr_8h_pct": avg_fr_8h_pct,
614
- "annualized_apr_pct": annualized_apr_pct,
615
  "triangulation_spread_pct": div_pct,
616
  "binance_fr": binance_fr,
617
  "bybit_fr": bybit_fr,
@@ -646,22 +722,115 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi
646
  "leading_exchange": lead_lag.get("leading_exchange"),
647
  "funding_countdown": settlement.get("countdown_str"),
648
  "is_settlement_imminent": settlement.get("is_settlement_imminent"),
649
- "taker_buy_pct": whale_flow.get("taker_buy_pct"),
650
- "taker_ratio": whale_flow.get("taker_ratio"),
651
- "whale_buy_count": whale_flow.get("whale_buy_count"),
652
- "whale_sell_count": whale_flow.get("whale_sell_count"),
653
- "whale_buy_vol_usd": whale_flow.get("whale_buy_vol_usd"),
654
- "whale_sell_vol_usd": whale_flow.get("whale_sell_vol_usd"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
655
  "breakout_radar": breakout,
656
  "market_structure": struct_map,
657
  "global_regime": regime_text,
658
  "fake_status": fake_status_str,
659
- "warnings": signal.get("warnings") or [],
660
  }
661
 
662
  return prompt, data_summary
663
 
664
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
665
  async def execute_llm_completion(
666
  provider: str,
667
  clean_api_key: str,
@@ -684,6 +853,11 @@ async def execute_llm_completion(
684
  """
685
  clean_key = clean_api_key.strip().strip('"\'')
686
  prov = provider.lower().strip()
 
 
 
 
 
687
  client = get_ai_http_client()
688
 
689
  if prov == "gemini":
@@ -753,18 +927,15 @@ async def execute_llm_completion(
753
  resolved_base_url = "https://openrouter.ai/api/v1"
754
  default_model = "anthropic/claude-3.5-sonnet"
755
  elif prov == "custom":
756
- resolved_base_url = (base_url or "https://api.vikey.ai/v1").rstrip("/")
 
 
 
757
  default_model = "anthropic/claude-fable-5"
758
  else: # openai
759
  resolved_base_url = "https://api.openai.com/v1"
760
  default_model = "gpt-4o-mini"
761
 
762
- if base_url and base_url.strip():
763
- b_url = base_url.strip().rstrip("/")
764
- if not b_url.endswith("/v1") and not "/v1" in b_url:
765
- b_url = f"{b_url}/v1"
766
- resolved_base_url = b_url
767
-
768
  resolved_model = model_name.strip().strip('"\'') if (model_name and model_name.strip()) else default_model
769
  used_model = resolved_model
770
 
@@ -948,7 +1119,10 @@ async def execute_llm_completion(
948
  return text_result, used_model
949
 
950
  else:
951
- raise HTTPException(status_code=400, detail=f"Provider '{prov}' tidak didukung. Gunakan 'vikey', 'gemini', 'openai', atau 'groq'.")
 
 
 
952
 
953
 
954
  @router.post("/analyze")
@@ -957,16 +1131,29 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request):
957
  AI Market Analysis endpoint.
958
  Includes in-memory 3-minute caching to eliminate token waste.
959
  """
960
- symbol = body.symbol.upper().strip()
961
- if not symbol.endswith("USDT"):
962
  symbol = f"{symbol}USDT"
963
 
 
 
 
 
 
 
 
 
 
 
964
  # Check cache first if no custom question and not forcing refresh
965
  now_ts = time.time()
966
  _prune_ai_cache(now_ts)
967
- req_provider = body.provider.lower().strip()
968
  model_key = (body.model or "default").strip()
969
- cache_key = f"{symbol}:{req_provider}:{model_key}"
 
 
 
 
970
  cache_entry = _AI_CACHE.get(cache_key)
971
 
972
  logger.info("[%s] AI /analyze request: provider=%s, model=%s, force_refresh=%s", symbol, req_provider, model_key, body.force_refresh)
@@ -980,13 +1167,12 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request):
980
  logger.info("[%s] Returning cached AI analysis (%s, age: %ds, 0 tokens burned)", symbol, cache_key, int(age_seconds))
981
  return cached_data
982
 
983
- # Resolve API Key
984
- api_key = (
985
- body.api_key
986
- or request.headers.get("x-api-key")
987
- or (os.getenv("VIKEY_API_KEY") if req_provider == "vikey"
988
- else os.getenv("GEMINI_API_KEY") if req_provider == "gemini"
989
- else os.getenv("OPENAI_API_KEY"))
990
  )
991
 
992
  if not api_key or not api_key.strip():
@@ -1007,7 +1193,9 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request):
1007
  is_signal_stale = True
1008
  if signal and signal.get("created_at"):
1009
  try:
1010
- created_dt = datetime.fromisoformat(str(signal["created_at"]))
 
 
1011
  if (now_dt - created_dt).total_seconds() < 60:
1012
  is_signal_stale = False
1013
  except Exception:
@@ -1038,16 +1226,16 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request):
1038
  fresh_signal = eng.compute(raw)
1039
  if fresh_signal:
1040
  signal = fresh_signal
1041
- # Persist asynchronously so the DB and dashboard stay fresh without blocking
1042
- asyncio.create_task(
1043
- async_save_signal(
1044
  symbol=symbol,
1045
  timeframe=fresh_signal.get("active_timeframe", "adaptive"),
1046
  direction=fresh_signal["direction"],
1047
  conviction=fresh_signal["conviction"],
1048
  signal_data=fresh_signal,
1049
  )
1050
- )
 
1051
  except Exception as exc:
1052
  logger.warning("[%s] On-demand live signal collect failed, using DB snapshot fallback: %s", symbol, exc)
1053
 
 
8
  import re
9
  import time
10
  import asyncio
11
+ import ipaddress
12
  import logging
13
+ import socket
14
  from datetime import datetime, timezone
15
  from typing import Any
16
+ from urllib.parse import urlparse
17
 
18
  import httpx
19
  from fastapi import APIRouter, HTTPException, Request
 
52
  _AI_HTTP_CLIENT = httpx.AsyncClient(
53
  timeout=None,
54
  verify=True,
55
+ follow_redirects=False,
56
  limits=httpx.Limits(
57
  max_keepalive_connections=10,
58
  max_connections=25,
 
266
  if snapshots:
267
  for s in snapshots:
268
  ex = s.get("exchange", "")
269
+ oi_usd = float(s.get("oi") or s.get("open_interest") or 0.0)
 
 
270
  if oi_usd > 0:
271
  total_oi_usd += oi_usd
272
  venue_oi_str_list.append(f"{ex.upper()}: {_fmt_usd(oi_usd)}")
273
  else:
274
  for ex, d in active_exch_data.items():
275
  if not d: continue
276
+ oi_usd = float(d.get("oi") or d.get("open_interest") or 0.0)
 
 
277
  if oi_usd > 0:
278
  total_oi_usd += oi_usd
279
  venue_oi_str_list.append(f"{ex.upper()}: {_fmt_usd(oi_usd)}")
 
288
  fr = d.get("funding_rate")
289
  if fr is not None:
290
  fr_vals.append(float(fr))
291
+ oi_usd_w = float(d.get("oi") or d.get("open_interest") or 0.0)
292
+ fr_weights.append(max(0.0, oi_usd_w))
 
 
293
  avg_fr_8h = _oi_weighted_average(fr_vals, fr_weights) if fr_vals else 0.0
294
  avg_fr_8h_pct = avg_fr_8h * 100
295
  annualized_apr_pct = avg_fr_8h * 3 * 365 * 100
 
313
  bitget_ls = f"{bitget.get('long_ratio', 0)*100:.1f}%L" if bitget.get('long_ratio') else "N/A"
314
 
315
  cross = factors.get("cross_exchange") or {}
316
+ div_pct = float(cross.get("divergence_pct") or 0.0)
317
 
318
  # 3. CVD & Flow
319
  spot_fut = factors.get("spot_futures_cvd") or {}
 
325
  spot_status_str = "Pasar Spot Riil Terdaftar (Likuiditas Organik Ada)" if has_spot else "⚠️ PERP-ONLY (Sintetis 100%, rawan wick sweep & manipulasi bandar)"
326
 
327
  # Hyperliquid
328
+ hl_basis = float(hl.get("basis_pct") or 0.0)
329
  hl_sig = factors.get("hyperliquid") or {}
330
  hl_label = hl_sig.get("label", "Equilibrium")
331
 
332
  # OI Divergence
333
  oi_div = factors.get("oi_divergence") or {}
334
  oi_div_str = oi_div.get("direction_val") or oi_div.get("value") or oi_div.get("label", "Balanced Market Flow")
335
+ oi_1h_pct = oi_div.get("oi_change_1h_pct")
336
+ oi_4h_pct = oi_div.get("oi_change_4h_pct")
337
+ oi_multi_parts = []
338
+ if oi_1h_pct is not None:
339
+ oi_multi_parts.append(f"1H OI: {float(oi_1h_pct):+.2f}%")
340
+ if oi_4h_pct is not None:
341
+ oi_multi_parts.append(f"4H OI: {float(oi_4h_pct):+.2f}%")
342
+ if oi_multi_parts:
343
+ oi_div_str = f"{oi_div_str} ({' | '.join(oi_multi_parts)})"
344
+
345
+ # Safe 5-layer whale telemetry formatting (prevents NoneType.__format__ and 0.0% hallucinations)
346
+ ls_factor = factors.get("ls_ratio") or {}
347
+
348
+ def _wf_num(key: str, default: float) -> float:
349
+ val = whale_flow.get(key)
350
+ if val is None:
351
+ return default
352
+ try:
353
+ return float(val)
354
+ except (TypeError, ValueError):
355
+ return default
356
+
357
+ wf_taker_buy_pct = _wf_num("taker_buy_pct", 50.0)
358
+ wf_taker_ratio = _wf_num("taker_ratio", 1.0)
359
+ wf_buy_count = int(_wf_num("whale_buy_count", 0))
360
+ wf_sell_count = int(_wf_num("whale_sell_count", 0))
361
+ wf_buy_vol = _wf_num("whale_buy_vol_usd", 0.0)
362
+ wf_sell_vol = _wf_num("whale_sell_vol_usd", 0.0)
363
+ wf_sweep_buy_cnt = int(_wf_num("sweep_buy_count", 0))
364
+ wf_sweep_sell_cnt = int(_wf_num("sweep_sell_count", 0))
365
+ wf_sweep_buy_vol = _wf_num("sweep_buy_vol_usd", 0.0)
366
+ wf_sweep_sell_vol = _wf_num("sweep_sell_vol_usd", 0.0)
367
+ wf_twap_bias = whale_flow.get("twap_bias") or "NEUTRAL"
368
+ wf_twap_buy_pct = _wf_num("twap_buy_pct", 50.0)
369
+ wf_abs_note = whale_flow.get("absorption_note")
370
+ wf_abs_type = whale_flow.get("absorption_type")
371
+ wf_absorption_str = (
372
+ wf_abs_note
373
+ or (wf_abs_type if wf_abs_type and wf_abs_type != "NONE" else None)
374
+ or "Tidak ada"
375
+ )
376
+ wf_whale_lr = whale_flow.get("whale_position_long_ratio")
377
+ if wf_whale_lr is None:
378
+ wf_whale_lr = ls_factor.get("whale_position_long_ratio")
379
+ wf_retail_lr = whale_flow.get("retail_account_long_ratio")
380
+ if wf_retail_lr is None:
381
+ wf_retail_lr = ls_factor.get("retail")
382
+ wf_sm_delta = whale_flow.get("smart_money_delta")
383
+ if wf_sm_delta is None:
384
+ wf_sm_delta = ls_factor.get("smart_money_delta")
385
+ wf_whale_lr_str = f"{float(wf_whale_lr) * 100:.1f}%" if wf_whale_lr is not None else "N/A"
386
+ wf_retail_lr_str = f"{float(wf_retail_lr) * 100:.1f}%" if wf_retail_lr is not None else "N/A"
387
+ wf_sm_delta_str = (
388
+ f"{float(wf_sm_delta) * 100:+.1f}%"
389
+ if (wf_sm_delta is not None and (wf_whale_lr is not None or wf_retail_lr is not None))
390
+ else "N/A"
391
+ )
392
+ wf_onchain_wallets = int(_wf_num("onchain_whale_wallets", 0))
393
+ wf_largest_usd = _wf_num("largest_trade_usd", 0.0)
394
+ wf_largest_side = whale_flow.get("largest_trade_side") or "NONE"
395
+ wf_verdict = whale_flow.get("flow_verdict") or "Order Flow Agregat Seimbang"
396
 
397
  # 4. Multi-Timeframe & Squeeze
398
  ms = factors.get("market_structure") or {}
399
+ active_tf = ms.get("tf") or "1h"
400
  struct_map = ms.get("structure_per_tf") or {}
401
 
402
  squeeze = pred.get("volatility_squeeze") or {}
403
+ squeeze_intensity = squeeze.get("squeeze_intensity") or "NORMAL"
404
+ raw_compression = squeeze.get("compression_ratio")
405
+ compression_ratio = float(raw_compression) if raw_compression is not None else 1.0
406
 
407
  # Orderbook depth skew
408
  ob_skew = pred.get("orderbook_skew") or {}
409
+ resting_pressure = ob_skew.get("resting_pressure") or "BALANCED"
410
+ bid_depth = float(ob_skew.get("bid_depth_usd") or 0.0)
411
+ ask_depth = float(ob_skew.get("ask_depth_usd") or 0.0)
412
  depth_ratio = (bid_depth / ask_depth) if ask_depth > 0 else (99.0 if bid_depth > 0 else 1.0)
413
 
414
  # Liquidation Magnets & Predictive Targets
415
  magnets = pred.get("liquidation_magnets") or {}
416
+ upper_mag = magnets.get("upper_magnet_str") or "N/A"
417
+ lower_mag = magnets.get("lower_magnet_str") or "N/A"
418
+ dist_up = float(magnets.get("dist_upper_pct") or 0.0)
419
+ dist_down = float(magnets.get("dist_lower_pct") or 0.0)
420
 
421
  pred_target = pred.get("predicted_target")
422
  pred_target_str = _fmt_px(pred_target) if pred_target else "N/A"
423
+ target_type = pred.get("target_type") or "N/A"
424
+ target_dist_pct = float(pred.get("target_dist_pct") or 0.0)
425
+ anticipation_text = pred.get("anticipation") or "Menunggu konfirmasi momentum likuiditas."
426
 
427
  # 5. Confluence Consensus & Streak
428
  conviction = signal.get("conviction", 0) if signal else (signals_data.get("conviction", 0))
 
435
  neutral_signals = []
436
  for k, v in factors.items():
437
  if isinstance(v, dict):
438
+ try:
439
+ raw_sc = v.get("score", 0)
440
+ sc = int(float(raw_sc)) if raw_sc is not None else 0
441
+ except (TypeError, ValueError):
442
+ sc = 0
443
+ lbl = v.get("label") or k
444
  if sc > 0: bullish_signals.append(f"{k} (+{sc}): {lbl}")
445
  elif sc < 0: bearish_signals.append(f"{k} ({sc}): {lbl}")
446
  else: neutral_signals.append(f"{k} (0): {lbl}")
 
475
  # 7. Fakeout / Manipulation Detector
476
  fake_det = factors.get("fake_detector") or {}
477
  is_fake = fake_det.get("is_fake", False)
478
+ fake_reason = fake_det.get("reason") or "; ".join(fake_det.get("warnings") or [])
479
  fake_status_str = f"🚨 TERDETEKSI MANIPULASI HARGA: {fake_reason}" if is_fake else "✅ Bersih (Tidak terdeteksi anomali wick sweep / divergensi spread manipulatif)"
480
 
481
  # Pre-calculated trade levels (if existing in signal engine)
 
607
  [1-2 poin tindakan taktis praktis menanggapi kondisi yang ditanyakan user]
608
  """
609
 
610
+ ll_spread_bps = float(lead_lag.get("max_spread_bps") or 0.0)
611
+ ll_spread_usd = float(lead_lag.get("max_spread_usd") or 0.0)
612
+ ext_high = extremes.get("high_24h") or mark_price
613
+ ext_low = extremes.get("low_24h") or mark_price
614
+ ext_dist_high = float(extremes.get("dist_to_high_pct") or 0.0)
615
+ ext_dist_low = float(extremes.get("dist_to_low_pct") or 0.0)
616
+ ext_range_usd = float(extremes.get("range_usd") or 0.0)
617
+ ext_range_pct = float(extremes.get("range_pct") or 0.0)
618
+ ext_range_pos = float(extremes.get("range_position_pct") if extremes.get("range_position_pct") is not None else 50.0)
619
+
620
  prompt = f"""Role: Damian — Senior Institutional Crypto Derivatives Quantitative Strategist.
621
  Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presisi kuantitatif, dan tanpa basa-basi pembuka/penutup.
622
 
 
630
  2. HARGA MULTI-BURSA, DISPARITAS LEAD-LAG & LIKUIDITAS
631
  • Mark Price Utama: {_fmt_px(mark_price)} | Index Price: {_fmt_px(index_price)} | Basis Spread: {div_pct:+.3f}%
632
  • Matrix Harga Bursa: Binance: {_px_venue(binance_px)} | Bybit: {_px_venue(bybit_px)} | OKX: {_px_venue(okx_px)} | Bitget: {_px_venue(bitget_px)} | Hyperliquid DEX: {_px_venue(hl_px)}
633
+ • Lead-Lag Disparity: Spread Maksimal {ll_spread_bps:.1f} bps ({_fmt_px(ll_spread_usd)}) | Status: {lead_lag.get('lead_lag_summary') or 'Ketat / Seimbang'}
634
  • Total Open Interest Agregat (5 Bursa): {total_oi_str} ({venue_oi_breakdown})
635
  • Status Pasar: {spot_status_str}
636
 
637
  3. EXTREMES 24 JAM & PROFIL RENTANG HARGA
638
+ • 24H High: {_fmt_px(ext_high)} ({ext_dist_high:+.2f}% dari harga saat ini)
639
+ • 24H Low: {_fmt_px(ext_low)} ({ext_dist_low:+.2f}% dari harga saat ini)
640
+ • Rentang 24H: {_fmt_px(ext_range_usd)} ({ext_range_pct:.2f}% rentang volatilitas)
641
+ • Posisi Rentang: {ext_range_pos:.1f}% -> {extremes.get('zone_label') or 'Equilibrium'}
642
 
643
  4. FUNDING RATES, COUNTDOWN SETTLEMENT & ANNUALIZED CARRY (APR %)
644
  • Rata-rata Funding Rate 8H: {avg_fr_8h_pct:+.4f}% | Annualized APR: {annualized_apr_pct:+.2f}% APR
 
648
 
649
  5. ORDER FLOW INSTITUSIONAL, WHALE BLOCK TRADES & CVD
650
  • Spot CVD: {spot_cvd} | Futures CVD: {fut_cvd} -> Status Aliran: {cvd_label}
651
+ • Agresivitas Taker: Buy {wf_taker_buy_pct:.1f}% vs Sell {100.0 - wf_taker_buy_pct:.1f}% (Rasio Taker: {wf_taker_ratio:.2f}x)
652
+ • Whale Block & Reconstructed Sweeps: {wf_buy_count} Buy Blocks (${wf_buy_vol:,.0f}) vs {wf_sell_count} Sell Blocks (${wf_sell_vol:,.0f}) | Sweeps: {wf_sweep_buy_cnt} Buy (${wf_sweep_buy_vol:,.0f}) vs {wf_sweep_sell_cnt} Sell (${wf_sweep_sell_vol:,.0f})
653
+ • Whale TWAP & Iceberg Absorption: TWAP Bias: {wf_twap_bias} ({wf_twap_buy_pct:.1f}% Klines Taker Buy) | Absorption: {wf_absorption_str}
654
+ • Smart Money Position vs Retail & On-Chain Wallets: Whale Pos Long: {wf_whale_lr_str} vs Retail Long: {wf_retail_lr_str} (Delta: {wf_sm_delta_str}) | Hyperliquid Whale Wallets: {wf_onchain_wallets}
655
+ • Trade Terbesar: {_fmt_usd(wf_largest_usd)} ({wf_largest_side}) -> {wf_verdict}
656
  • Hyperliquid DEX Whale Flow: {hl_label} (Basis Mark-Oracle: {hl_basis:+.3f}%)
657
  • Open Interest Divergence: {oi_div_str}
658
 
659
  6. STRUKTUR MULTI-TIMEFRAME (MTF), VOLATILITAS & ORDERBOOK
660
+ • Struktur MTF: 1D: {(struct_map.get('1d') or 'unknown').upper()} | 4H: {(struct_map.get('4h') or 'unknown').upper()} | 1H: {(struct_map.get('1h') or 'unknown').upper()} | 15M: {(struct_map.get('15m') or 'unknown').upper()} (Active TF: {active_tf.upper()})
661
  • Volatility Squeeze: {squeeze_intensity} (Compression Ratio: {compression_ratio:.2f})
662
  • Radar Squeeze & Breakout: {breakout.get('radar_label')} | Stage: {breakout.get('squeeze_stage')} | Proyeksi Arah: {breakout.get('projected_direction')}
663
  • Katalis Breakout: {breakout.get('catalyst_summary')}
 
686
  "mark_price_str": _fmt_px(mark_price),
687
  "total_oi_usd": total_oi_usd,
688
  "total_oi_str": total_oi_str,
689
+ "avg_fr_8h_pct": round(avg_fr_8h_pct, 4),
690
+ "annualized_apr_pct": round(annualized_apr_pct, 2),
691
  "triangulation_spread_pct": div_pct,
692
  "binance_fr": binance_fr,
693
  "bybit_fr": bybit_fr,
 
722
  "leading_exchange": lead_lag.get("leading_exchange"),
723
  "funding_countdown": settlement.get("countdown_str"),
724
  "is_settlement_imminent": settlement.get("is_settlement_imminent"),
725
+ "taker_buy_pct": wf_taker_buy_pct,
726
+ "taker_ratio": wf_taker_ratio,
727
+ "whale_buy_count": wf_buy_count,
728
+ "whale_sell_count": wf_sell_count,
729
+ "whale_buy_vol_usd": wf_buy_vol,
730
+ "whale_sell_vol_usd": wf_sell_vol,
731
+ "sweep_buy_count": wf_sweep_buy_cnt,
732
+ "sweep_sell_count": wf_sweep_sell_cnt,
733
+ "sweep_buy_vol_usd": wf_sweep_buy_vol,
734
+ "sweep_sell_vol_usd": wf_sweep_sell_vol,
735
+ "twap_bias": wf_twap_bias,
736
+ "twap_buy_pct": wf_twap_buy_pct,
737
+ "absorption_type": wf_abs_type,
738
+ "absorption_note": wf_abs_note,
739
+ "whale_position_long_ratio": wf_whale_lr,
740
+ "retail_account_long_ratio": wf_retail_lr,
741
+ "smart_money_delta": wf_sm_delta,
742
+ "onchain_whale_wallets": wf_onchain_wallets,
743
+ "oi_change_1h_pct": oi_1h_pct,
744
+ "oi_change_4h_pct": oi_4h_pct,
745
  "breakout_radar": breakout,
746
  "market_structure": struct_map,
747
  "global_regime": regime_text,
748
  "fake_status": fake_status_str,
749
+ "warnings": (signal or {}).get("warnings") or [],
750
  }
751
 
752
  return prompt, data_summary
753
 
754
 
755
+ def resolve_ai_api_key(
756
+ provider: str,
757
+ body_api_key: str | None,
758
+ header_api_key: str | None,
759
+ base_url: str | None = None,
760
+ ) -> str | None:
761
+ """Resolve API key safely: never fall back to server env secrets when custom endpoints are used."""
762
+ explicit = (body_api_key or header_api_key or "").strip()
763
+ if explicit:
764
+ return explicit
765
+ prov = (provider or "").lower().strip()
766
+ if prov == "custom" or (base_url and base_url.strip()):
767
+ return None
768
+ env_var_map = {
769
+ "vikey": "VIKEY_API_KEY",
770
+ "gemini": "GEMINI_API_KEY",
771
+ "openai": "OPENAI_API_KEY",
772
+ "openrouter": "OPENROUTER_API_KEY",
773
+ "groq": "GROQ_API_KEY",
774
+ }
775
+ env_name = env_var_map.get(prov)
776
+ return os.getenv(env_name) if env_name else None
777
+
778
+
779
+ def _validate_ai_base_url(raw_url: str) -> str:
780
+ """Validate custom LLM base URL against unsafe schemes, userinfo, and private/internal IPs (SSRF)."""
781
+ b_url = raw_url.strip().rstrip("/")
782
+ parsed = urlparse(b_url)
783
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
784
+ raise HTTPException(
785
+ status_code=400,
786
+ detail="Custom base_url tidak valid (harus URL http/https yang sah).",
787
+ )
788
+ if parsed.username or parsed.password:
789
+ raise HTTPException(
790
+ status_code=400,
791
+ detail="Custom base_url tidak boleh menyertakan kredensial userinfo.",
792
+ )
793
+
794
+ host = parsed.hostname.lower().rstrip(".")
795
+ if host in ("localhost", "localhost.localdomain") or host.endswith(".local") or host.endswith(".internal"):
796
+ raise HTTPException(
797
+ status_code=400,
798
+ detail="Custom base_url tidak diizinkan mengarah ke host internal atau lokal.",
799
+ )
800
+
801
+ try:
802
+ ip_obj = ipaddress.ip_address(host)
803
+ except ValueError:
804
+ ip_obj = None
805
+
806
+ if ip_obj is not None:
807
+ if not ip_obj.is_global:
808
+ raise HTTPException(
809
+ status_code=400,
810
+ detail="Custom base_url tidak diizinkan mengarah ke IP privat, loopback, atau link-local.",
811
+ )
812
+ else:
813
+ try:
814
+ addr_infos = socket.getaddrinfo(host, None)
815
+ except socket.gaierror:
816
+ addr_infos = []
817
+ for info in addr_infos:
818
+ resolved_ip = info[4][0].split("%")[0]
819
+ try:
820
+ resolved_obj = ipaddress.ip_address(resolved_ip)
821
+ except ValueError:
822
+ continue
823
+ if not resolved_obj.is_global:
824
+ raise HTTPException(
825
+ status_code=400,
826
+ detail="Custom base_url resolves ke alamat IP privat atau internal yang dilarang.",
827
+ )
828
+
829
+ if not b_url.endswith("/v1") and "/v1" not in parsed.path:
830
+ b_url = f"{b_url}/v1"
831
+ return b_url
832
+
833
+
834
  async def execute_llm_completion(
835
  provider: str,
836
  clean_api_key: str,
 
853
  """
854
  clean_key = clean_api_key.strip().strip('"\'')
855
  prov = provider.lower().strip()
856
+ if base_url and base_url.strip() and prov != "custom":
857
+ raise HTTPException(
858
+ status_code=400,
859
+ detail=f"Parameter base_url hanya diizinkan untuk provider 'custom', bukan '{prov}'.",
860
+ )
861
  client = get_ai_http_client()
862
 
863
  if prov == "gemini":
 
927
  resolved_base_url = "https://openrouter.ai/api/v1"
928
  default_model = "anthropic/claude-3.5-sonnet"
929
  elif prov == "custom":
930
+ if base_url and base_url.strip():
931
+ resolved_base_url = _validate_ai_base_url(base_url)
932
+ else:
933
+ resolved_base_url = "https://api.vikey.ai/v1"
934
  default_model = "anthropic/claude-fable-5"
935
  else: # openai
936
  resolved_base_url = "https://api.openai.com/v1"
937
  default_model = "gpt-4o-mini"
938
 
 
 
 
 
 
 
939
  resolved_model = model_name.strip().strip('"\'') if (model_name and model_name.strip()) else default_model
940
  used_model = resolved_model
941
 
 
1119
  return text_result, used_model
1120
 
1121
  else:
1122
+ raise HTTPException(
1123
+ status_code=400,
1124
+ detail=f"Provider '{prov}' tidak didukung. Gunakan 'vikey', 'gemini', 'openai', 'openrouter', 'groq', atau 'custom'.",
1125
+ )
1126
 
1127
 
1128
  @router.post("/analyze")
 
1131
  AI Market Analysis endpoint.
1132
  Includes in-memory 3-minute caching to eliminate token waste.
1133
  """
1134
+ symbol = body.symbol.upper().strip().replace("/", "").replace("-", "")
1135
+ if not any(symbol.endswith(q) and len(symbol) > len(q) for q in ("USDT", "USDC", "USD", "BUSD", "EUR")):
1136
  symbol = f"{symbol}USDT"
1137
 
1138
+ req_provider = body.provider.lower().strip()
1139
+ validated_base_url = ""
1140
+ if body.base_url and body.base_url.strip():
1141
+ if req_provider != "custom":
1142
+ raise HTTPException(
1143
+ status_code=400,
1144
+ detail=f"Parameter base_url hanya diizinkan untuk provider 'custom', bukan '{req_provider}'.",
1145
+ )
1146
+ validated_base_url = _validate_ai_base_url(body.base_url)
1147
+
1148
  # Check cache first if no custom question and not forcing refresh
1149
  now_ts = time.time()
1150
  _prune_ai_cache(now_ts)
 
1151
  model_key = (body.model or "default").strip()
1152
+ cache_key = (
1153
+ f"{symbol}:{req_provider}:{model_key}:{validated_base_url}"
1154
+ if validated_base_url
1155
+ else f"{symbol}:{req_provider}:{model_key}"
1156
+ )
1157
  cache_entry = _AI_CACHE.get(cache_key)
1158
 
1159
  logger.info("[%s] AI /analyze request: provider=%s, model=%s, force_refresh=%s", symbol, req_provider, model_key, body.force_refresh)
 
1167
  logger.info("[%s] Returning cached AI analysis (%s, age: %ds, 0 tokens burned)", symbol, cache_key, int(age_seconds))
1168
  return cached_data
1169
 
1170
+ # Resolve API Key safely (never expose server env credentials to custom endpoints)
1171
+ api_key = resolve_ai_api_key(
1172
+ provider=req_provider,
1173
+ body_api_key=body.api_key,
1174
+ header_api_key=request.headers.get("x-api-key"),
1175
+ base_url=body.base_url,
 
1176
  )
1177
 
1178
  if not api_key or not api_key.strip():
 
1193
  is_signal_stale = True
1194
  if signal and signal.get("created_at"):
1195
  try:
1196
+ created_dt = datetime.fromisoformat(str(signal["created_at"]).replace("Z", "+00:00"))
1197
+ if created_dt.tzinfo is None:
1198
+ created_dt = created_dt.replace(tzinfo=timezone.utc)
1199
  if (now_dt - created_dt).total_seconds() < 60:
1200
  is_signal_stale = False
1201
  except Exception:
 
1226
  fresh_signal = eng.compute(raw)
1227
  if fresh_signal:
1228
  signal = fresh_signal
1229
+ try:
1230
+ await async_save_signal(
 
1231
  symbol=symbol,
1232
  timeframe=fresh_signal.get("active_timeframe", "adaptive"),
1233
  direction=fresh_signal["direction"],
1234
  conviction=fresh_signal["conviction"],
1235
  signal_data=fresh_signal,
1236
  )
1237
+ except Exception as save_exc:
1238
+ logger.debug("[%s] Failed to persist on-demand AI signal: %s", symbol, save_exc)
1239
  except Exception as exc:
1240
  logger.warning("[%s] On-demand live signal collect failed, using DB snapshot fallback: %s", symbol, exc)
1241
 
backend/routers/execution.py CHANGED
@@ -350,12 +350,19 @@ async def execute_bybit_order(
350
  journal_entry = None
351
  if body.log_to_journal:
352
  try:
 
 
 
 
 
 
353
  bias_label = "STRONG LONG" if body.side.upper() in ("BUY", "LONG") else "STRONG SHORT"
354
- tp_str = f"TP1: ${body.take_profit_1:,.4f} ({body.tp1_percent:.0f}%)"
355
- if body.take_profit_2:
356
- tp_str += f" | TP2: ${body.take_profit_2:,.4f} ({100 - body.tp1_percent:.0f}%)"
 
357
 
358
- entry_str = f"${body.entry_price:,.4f}" if body.entry_price else "MARKET ORDER"
359
 
360
  margin_label = (
361
  f"Margin: ${body.margin_usd:.1f} ({body.margin_percent:.1f}% eq) | Lev: {body.leverage}x"
@@ -364,10 +371,10 @@ async def execute_bybit_order(
364
  )
365
 
366
  journal_entry = await async_create_journal_entry({
367
- "symbol": body.symbol.upper(),
368
  "bias": bias_label,
369
  "entry_zone": entry_str,
370
- "stop_loss": f"${body.stop_loss:,.4f}",
371
  "take_profit": tp_str,
372
  "risk_reward": margin_label,
373
  "leverage": f"{body.leverage}x",
@@ -379,7 +386,7 @@ async def execute_bybit_order(
379
  "mode": exec_result.get("mode"),
380
  "margin_usd": body.margin_usd,
381
  "margin_percent": body.margin_percent,
382
- "tp1_percent": body.tp1_percent,
383
  },
384
  "status": "PENDING",
385
  })
 
350
  journal_entry = None
351
  if body.log_to_journal:
352
  try:
353
+ def _fmt_exec_price(price: float) -> str:
354
+ if abs(price) >= 0.01 or price == 0:
355
+ return f"${price:,.4f}"
356
+ decimals = 10 if abs(price) < 0.0001 else 8
357
+ return f"${price:.{decimals}f}".rstrip("0").rstrip(".")
358
+
359
  bias_label = "STRONG LONG" if body.side.upper() in ("BUY", "LONG") else "STRONG SHORT"
360
+ tp1_pct = body.tp1_percent if has_runner else 100.0
361
+ tp_str = f"TP1: {_fmt_exec_price(body.take_profit_1)} ({tp1_pct:.0f}%)"
362
+ if has_runner and body.take_profit_2:
363
+ tp_str += f" | TP2: {_fmt_exec_price(body.take_profit_2)} ({100 - tp1_pct:.0f}%)"
364
 
365
+ entry_str = _fmt_exec_price(body.entry_price) if body.entry_price else "MARKET ORDER"
366
 
367
  margin_label = (
368
  f"Margin: ${body.margin_usd:.1f} ({body.margin_percent:.1f}% eq) | Lev: {body.leverage}x"
 
371
  )
372
 
373
  journal_entry = await async_create_journal_entry({
374
+ "symbol": body.symbol.upper().strip().replace("/", "").replace("-", "").replace("_", "").replace(" ", ""),
375
  "bias": bias_label,
376
  "entry_zone": entry_str,
377
+ "stop_loss": _fmt_exec_price(body.stop_loss),
378
  "take_profit": tp_str,
379
  "risk_reward": margin_label,
380
  "leverage": f"{body.leverage}x",
 
386
  "mode": exec_result.get("mode"),
387
  "margin_usd": body.margin_usd,
388
  "margin_percent": body.margin_percent,
389
+ "tp1_percent": tp1_pct,
390
  },
391
  "status": "PENDING",
392
  })
backend/routers/journal.py CHANGED
@@ -304,14 +304,14 @@ async def synthesize_damian_memory(body: SynthesizeAuditRequest, request: Reques
304
  detail="Tidak ada riwayat trade Stop Loss yang perlu diaudit saat ini.",
305
  )
306
 
307
- # 2. Resolve API key & endpoint
 
308
  provider = body.provider.lower().strip()
309
- api_key = (
310
- body.api_key
311
- or request.headers.get("x-api-key")
312
- or (os.getenv("VIKEY_API_KEY") if provider == "vikey"
313
- else os.getenv("GEMINI_API_KEY") if provider == "gemini"
314
- else os.getenv("OPENAI_API_KEY"))
315
  )
316
 
317
  if not api_key or not api_key.strip():
 
304
  detail="Tidak ada riwayat trade Stop Loss yang perlu diaudit saat ini.",
305
  )
306
 
307
+ # 2. Resolve API key & endpoint safely (never expose server env keys to custom base_url)
308
+ from routers.ai import resolve_ai_api_key
309
  provider = body.provider.lower().strip()
310
+ api_key = resolve_ai_api_key(
311
+ provider=provider,
312
+ body_api_key=body.api_key,
313
+ header_api_key=request.headers.get("x-api-key"),
314
+ base_url=body.base_url,
 
315
  )
316
 
317
  if not api_key or not api_key.strip():
backend/routers/market.py CHANGED
@@ -26,6 +26,38 @@ def _safe_get(data: Any, key: str, default: Any = None) -> Any:
26
  return default
27
 
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  def _calculate_candle_delta(c: dict[str, Any] | None) -> float:
30
  """
31
  Calculate directional or taker-volume delta for a single candle.
@@ -44,7 +76,7 @@ def _calculate_candle_delta(c: dict[str, Any] | None) -> float:
44
  tbv = c.get("taker_buy_volume")
45
  if tbv is not None and str(tbv).strip() != "":
46
  try:
47
- buy_vol = float(tbv)
48
  sell_vol = max(0.0, vol - buy_vol)
49
  return buy_vol - sell_vol
50
  except (ValueError, TypeError):
@@ -161,7 +193,7 @@ async def get_market_candles(
161
  exchanges_included.append(ex_name)
162
  m = {}
163
  for item in c_list:
164
- s_ts = item.get("timestamp", 0)
165
  s_sec = int(s_ts / 1000) if s_ts > 100_000_000_000 else int(s_ts)
166
  m[s_sec] = item
167
  aux_exchange_maps[ex_name] = m
@@ -205,12 +237,14 @@ async def get_market_candles(
205
  )
206
 
207
  # Sort candles chronologically by timestamp
208
- raw_primary_candles.sort(key=lambda c: c.get("timestamp", 0))
209
 
210
  # Index OI data by time_sec
211
  binance_oi_map: dict[int, float] = {}
212
  for item in raw_binance_oi:
213
- ts = int(item.get("timestamp", 0))
 
 
214
  sec = int(ts / 1000) if ts > 100_000_000_000 else ts
215
  oi_val = float(item.get("open_interest_usd") or 0.0)
216
  if oi_val > 0:
@@ -218,7 +252,9 @@ async def get_market_candles(
218
 
219
  bybit_oi_map: dict[int, float] = {}
220
  for item in raw_bybit_oi:
221
- ts = int(item.get("timestamp", 0))
 
 
222
  sec = int(ts / 1000) if ts > 100_000_000_000 else ts
223
  oi_coins = float(item.get("open_interest") or 0.0)
224
  if oi_coins > 0:
@@ -250,7 +286,7 @@ async def get_market_candles(
250
  seen_times: set[int] = set()
251
 
252
  for c in raw_primary_candles:
253
- ts = c.get("timestamp", 0)
254
  time_sec = int(ts / 1000) if ts > 100_000_000_000 else int(ts)
255
  if time_sec in seen_times:
256
  continue
@@ -391,40 +427,63 @@ async def get_multi_exchange_stream(symbol: str, request: Request):
391
  for k, r in zip(keys, res_list):
392
  results[k] = r if not isinstance(r, Exception) else None
393
 
 
 
 
 
 
 
394
  # Synthesize Binance
395
  binance_price = _safe_get(bnb_mp, "mark_price") or _safe_get(results.get("binance_mp"), "mark_price")
396
  binance_index = _safe_get(bnb_mp, "index_price") or _safe_get(results.get("binance_mp"), "index_price")
397
- binance_funding = _safe_get(bnb_fr, "funding_rate") or _safe_get(results.get("binance_fr"), "funding_rate")
398
- binance_oi = _safe_get(results.get("binance_oi"), "open_interest")
 
399
 
400
  # Synthesize Bybit
401
  bybit_price = _safe_get(bybit_mp, "mark_price") or _safe_get(results.get("bybit_mp"), "mark_price")
402
  bybit_index = _safe_get(bybit_mp, "index_price") or _safe_get(results.get("bybit_mp"), "index_price")
403
- bybit_funding = _safe_get(bybit_fr, "funding_rate") or _safe_get(results.get("bybit_fr"), "funding_rate")
404
- bybit_oi = _safe_get(bybit_24h, "open_interest") or _safe_get(results.get("bybit_oi"), "open_interest")
 
 
 
 
 
 
 
405
 
406
  # Synthesize OKX
407
  okx_price = _safe_get(results.get("okx_mp"), "mark_price")
408
  okx_index = _safe_get(results.get("okx_mp"), "index_price")
409
  okx_funding = _safe_get(results.get("okx_fr"), "funding_rate")
410
- okx_oi = _safe_get(results.get("okx_oi"), "open_interest")
 
411
 
412
  # Synthesize Bitget
413
  bitget_price = _safe_get(results.get("bitget_mp"), "mark_price")
414
  bitget_index = _safe_get(results.get("bitget_mp"), "index_price")
415
  bitget_funding = _safe_get(results.get("bitget_fr"), "funding_rate")
416
- bitget_oi = _safe_get(results.get("bitget_oi"), "open_interest")
 
417
 
418
  # Synthesize Hyperliquid
419
  hl_res = results.get("hl_data")
420
  hl_price = _safe_get(hl_res, "mark_price")
421
  hl_funding = _safe_get(hl_res, "funding_rate")
422
- hl_oi = _safe_get(hl_res, "open_interest")
423
 
424
  # Reference Price (average of valid mark prices)
425
  valid_prices = [p for p in (binance_price, bybit_price, okx_price, bitget_price, hl_price) if p and p > 0]
426
  ref_price = (sum(valid_prices) / len(valid_prices)) if valid_prices else 0.0
427
 
 
 
 
 
 
 
 
428
  def _diff_pct(p: float | None) -> float | None:
429
  if not p or not ref_price:
430
  return None
@@ -522,7 +581,7 @@ async def get_market_funding_history(
522
  time_map: dict[int, dict[str, float | None]] = {}
523
  for ex_name in ("binance", "bybit", "okx", "bitget"):
524
  for item in results.get(ex_name, []):
525
- raw_ts = int(item.get("timestamp", 0))
526
  ts = int(raw_ts / 1000) if raw_ts > 100_000_000_000 else raw_ts
527
  # Settle intervals on standard funding epochs (aligned to hourly boundary)
528
  aligned_ts = round(ts / 3600) * 3600
 
26
  return default
27
 
28
 
29
+ def _extract_oi_usd(
30
+ oi_val: Any,
31
+ oi_coins: Any,
32
+ mark_price: Any,
33
+ fallback_price: float = 0.0,
34
+ ) -> float | None:
35
+ """Resolve USD notional Open Interest across CEX/DEX venue payloads."""
36
+ has_explicit_zero = False
37
+ try:
38
+ if oi_val is not None:
39
+ val_f = float(oi_val)
40
+ if val_f > 0:
41
+ return round(val_f, 2)
42
+ if val_f == 0:
43
+ has_explicit_zero = True
44
+ except (ValueError, TypeError):
45
+ pass
46
+ try:
47
+ if oi_coins is not None:
48
+ coins = float(oi_coins)
49
+ px = float(mark_price) if mark_price is not None else 0.0
50
+ if px <= 0 and fallback_price > 0:
51
+ px = fallback_price
52
+ if coins > 0 and px > 0:
53
+ return round(coins * px, 2)
54
+ if coins == 0:
55
+ has_explicit_zero = True
56
+ except (ValueError, TypeError):
57
+ pass
58
+ return 0.0 if has_explicit_zero else None
59
+
60
+
61
  def _calculate_candle_delta(c: dict[str, Any] | None) -> float:
62
  """
63
  Calculate directional or taker-volume delta for a single candle.
 
76
  tbv = c.get("taker_buy_volume")
77
  if tbv is not None and str(tbv).strip() != "":
78
  try:
79
+ buy_vol = max(0.0, min(vol, float(tbv)))
80
  sell_vol = max(0.0, vol - buy_vol)
81
  return buy_vol - sell_vol
82
  except (ValueError, TypeError):
 
193
  exchanges_included.append(ex_name)
194
  m = {}
195
  for item in c_list:
196
+ s_ts = item.get("timestamp") or 0
197
  s_sec = int(s_ts / 1000) if s_ts > 100_000_000_000 else int(s_ts)
198
  m[s_sec] = item
199
  aux_exchange_maps[ex_name] = m
 
237
  )
238
 
239
  # Sort candles chronologically by timestamp
240
+ raw_primary_candles.sort(key=lambda c: c.get("timestamp") or 0)
241
 
242
  # Index OI data by time_sec
243
  binance_oi_map: dict[int, float] = {}
244
  for item in raw_binance_oi:
245
+ ts = int(item.get("timestamp") or 0)
246
+ if ts <= 0:
247
+ continue
248
  sec = int(ts / 1000) if ts > 100_000_000_000 else ts
249
  oi_val = float(item.get("open_interest_usd") or 0.0)
250
  if oi_val > 0:
 
252
 
253
  bybit_oi_map: dict[int, float] = {}
254
  for item in raw_bybit_oi:
255
+ ts = int(item.get("timestamp") or 0)
256
+ if ts <= 0:
257
+ continue
258
  sec = int(ts / 1000) if ts > 100_000_000_000 else ts
259
  oi_coins = float(item.get("open_interest") or 0.0)
260
  if oi_coins > 0:
 
286
  seen_times: set[int] = set()
287
 
288
  for c in raw_primary_candles:
289
+ ts = c.get("timestamp") or 0
290
  time_sec = int(ts / 1000) if ts > 100_000_000_000 else int(ts)
291
  if time_sec in seen_times:
292
  continue
 
427
  for k, r in zip(keys, res_list):
428
  results[k] = r if not isinstance(r, Exception) else None
429
 
430
+ def _first_present(*values):
431
+ for val in values:
432
+ if val is not None:
433
+ return val
434
+ return None
435
+
436
  # Synthesize Binance
437
  binance_price = _safe_get(bnb_mp, "mark_price") or _safe_get(results.get("binance_mp"), "mark_price")
438
  binance_index = _safe_get(bnb_mp, "index_price") or _safe_get(results.get("binance_mp"), "index_price")
439
+ binance_funding = _first_present(_safe_get(bnb_fr, "funding_rate"), _safe_get(results.get("binance_fr"), "funding_rate"))
440
+ binance_oi_val = _safe_get(results.get("binance_oi"), "open_interest_value")
441
+ binance_oi_coins = _safe_get(results.get("binance_oi"), "open_interest")
442
 
443
  # Synthesize Bybit
444
  bybit_price = _safe_get(bybit_mp, "mark_price") or _safe_get(results.get("bybit_mp"), "mark_price")
445
  bybit_index = _safe_get(bybit_mp, "index_price") or _safe_get(results.get("bybit_mp"), "index_price")
446
+ bybit_funding = _first_present(_safe_get(bybit_fr, "funding_rate"), _safe_get(results.get("bybit_fr"), "funding_rate"))
447
+ bybit_oi_val = _first_present(
448
+ _safe_get(bybit_24h, "open_interest_value"),
449
+ _safe_get(results.get("bybit_oi"), "open_interest_value"),
450
+ )
451
+ bybit_oi_coins = _first_present(
452
+ _safe_get(bybit_24h, "open_interest"),
453
+ _safe_get(results.get("bybit_oi"), "open_interest"),
454
+ )
455
 
456
  # Synthesize OKX
457
  okx_price = _safe_get(results.get("okx_mp"), "mark_price")
458
  okx_index = _safe_get(results.get("okx_mp"), "index_price")
459
  okx_funding = _safe_get(results.get("okx_fr"), "funding_rate")
460
+ okx_oi_val = _safe_get(results.get("okx_oi"), "open_interest_value")
461
+ okx_oi_coins = _safe_get(results.get("okx_oi"), "open_interest")
462
 
463
  # Synthesize Bitget
464
  bitget_price = _safe_get(results.get("bitget_mp"), "mark_price")
465
  bitget_index = _safe_get(results.get("bitget_mp"), "index_price")
466
  bitget_funding = _safe_get(results.get("bitget_fr"), "funding_rate")
467
+ bitget_oi_val = _safe_get(results.get("bitget_oi"), "open_interest_value")
468
+ bitget_oi_coins = _safe_get(results.get("bitget_oi"), "open_interest")
469
 
470
  # Synthesize Hyperliquid
471
  hl_res = results.get("hl_data")
472
  hl_price = _safe_get(hl_res, "mark_price")
473
  hl_funding = _safe_get(hl_res, "funding_rate")
474
+ hl_oi_coins = _safe_get(hl_res, "open_interest")
475
 
476
  # Reference Price (average of valid mark prices)
477
  valid_prices = [p for p in (binance_price, bybit_price, okx_price, bitget_price, hl_price) if p and p > 0]
478
  ref_price = (sum(valid_prices) / len(valid_prices)) if valid_prices else 0.0
479
 
480
+ # Resolve Open Interest strictly as USD notional so frontend $B/$M/$K formatting is consistent
481
+ binance_oi = _extract_oi_usd(binance_oi_val, binance_oi_coins, binance_price, fallback_price=ref_price)
482
+ bybit_oi = _extract_oi_usd(bybit_oi_val, bybit_oi_coins, bybit_price, fallback_price=ref_price)
483
+ okx_oi = _extract_oi_usd(okx_oi_val, okx_oi_coins, okx_price, fallback_price=ref_price)
484
+ bitget_oi = _extract_oi_usd(bitget_oi_val, bitget_oi_coins, bitget_price, fallback_price=ref_price)
485
+ hl_oi = _extract_oi_usd(None, hl_oi_coins, hl_price, fallback_price=ref_price)
486
+
487
  def _diff_pct(p: float | None) -> float | None:
488
  if not p or not ref_price:
489
  return None
 
581
  time_map: dict[int, dict[str, float | None]] = {}
582
  for ex_name in ("binance", "bybit", "okx", "bitget"):
583
  for item in results.get(ex_name, []):
584
+ raw_ts = int(item.get("timestamp") or 0)
585
  ts = int(raw_ts / 1000) if raw_ts > 100_000_000_000 else raw_ts
586
  # Settle intervals on standard funding epochs (aligned to hourly boundary)
587
  aligned_ts = round(ts / 3600) * 3600
backend/routers/signals.py CHANGED
@@ -24,7 +24,7 @@ from database.db import (
24
  from engine.outcome_evaluator import async_evaluate_pending_predictions, async_log_prediction_if_new
25
  from engine.signal_engine import SignalEngine
26
  from routers.ws import broadcast
27
- from security import require_api_token
28
 
29
  router = APIRouter(prefix="/api/signals", tags=["signals"])
30
  logger = logging.getLogger(__name__)
@@ -57,7 +57,9 @@ async def get_all_signals(request: Request, background_tasks: BackgroundTasks):
57
  if not u_str:
58
  stale_count += 1
59
  else:
60
- dt = datetime.fromisoformat(u_str)
 
 
61
  if (now_dt - dt).total_seconds() > 120:
62
  stale_count += 1
63
  except Exception:
@@ -88,7 +90,7 @@ async def refresh_all_signals(request: Request):
88
  }
89
 
90
 
91
- @router.get("/cron")
92
  async def cron_refresh(request: Request):
93
  """Cron endpoint for Vercel/external schedulers to keep pairs refreshed."""
94
  collector = getattr(request.app.state, "collector", None)
 
24
  from engine.outcome_evaluator import async_evaluate_pending_predictions, async_log_prediction_if_new
25
  from engine.signal_engine import SignalEngine
26
  from routers.ws import broadcast
27
+ from security import require_api_token, require_cron_or_api_token
28
 
29
  router = APIRouter(prefix="/api/signals", tags=["signals"])
30
  logger = logging.getLogger(__name__)
 
57
  if not u_str:
58
  stale_count += 1
59
  else:
60
+ dt = datetime.fromisoformat(str(u_str).replace("Z", "+00:00"))
61
+ if dt.tzinfo is None:
62
+ dt = dt.replace(tzinfo=timezone.utc)
63
  if (now_dt - dt).total_seconds() > 120:
64
  stale_count += 1
65
  except Exception:
 
90
  }
91
 
92
 
93
+ @router.get("/cron", dependencies=[Depends(require_cron_or_api_token)])
94
  async def cron_refresh(request: Request):
95
  """Cron endpoint for Vercel/external schedulers to keep pairs refreshed."""
96
  collector = getattr(request.app.state, "collector", None)
backend/routers/ws.py CHANGED
@@ -8,6 +8,7 @@ WebSocket endpoints that stream signal and real-time chart updates to connected
8
  import asyncio
9
  import json
10
  import logging
 
11
  import time
12
  from typing import Any
13
 
@@ -23,11 +24,26 @@ router = APIRouter(tags=["websocket"])
23
  _connections: set[WebSocket] = set()
24
 
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  async def broadcast(data: Any) -> None:
27
  """Send a JSON payload to every connected WebSocket client concurrently with timeout guard."""
28
  if not _connections:
29
  return
30
- message = json.dumps(data, default=str)
31
  clients = list(_connections)
32
  dead: set[WebSocket] = set()
33
 
@@ -124,22 +140,53 @@ async def ws_chart(websocket: WebSocket, symbol: str):
124
  except Exception:
125
  pass
126
 
127
- prices = [p for p in (price_binance, price_bybit) if p and p > 0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  live_price = prices[0] if prices else 0.0
129
 
130
  if live_price > 0:
131
  now_ts = int(time.time())
 
 
 
 
 
 
 
 
132
  payload = {
133
  "type": "chart_tick",
134
  "symbol": clean_sym,
135
  "time": now_ts,
136
  "price": live_price,
137
- "exchanges": {
138
- "binance": price_binance,
139
- "bybit": price_bybit,
140
- },
141
  }
142
- await websocket.send_text(json.dumps(payload))
143
  await asyncio.sleep(1.5)
144
  except (asyncio.CancelledError, WebSocketDisconnect, RuntimeError):
145
  break
 
8
  import asyncio
9
  import json
10
  import logging
11
+ import math
12
  import time
13
  from typing import Any
14
 
 
24
  _connections: set[WebSocket] = set()
25
 
26
 
27
+ def _sanitize_json_value(obj: Any) -> Any:
28
+ """Recursively replace non-finite floats (NaN/Inf) with None for RFC-8259 strict JSON."""
29
+ if isinstance(obj, float):
30
+ return obj if math.isfinite(obj) else None
31
+ if isinstance(obj, dict):
32
+ return {k: _sanitize_json_value(v) for k, v in obj.items()}
33
+ if isinstance(obj, (list, tuple)):
34
+ return [_sanitize_json_value(v) for v in obj]
35
+ return obj
36
+
37
+
38
+ def _safe_json_dumps(data: Any) -> str:
39
+ return json.dumps(_sanitize_json_value(data), default=str, allow_nan=False)
40
+
41
+
42
  async def broadcast(data: Any) -> None:
43
  """Send a JSON payload to every connected WebSocket client concurrently with timeout guard."""
44
  if not _connections:
45
  return
46
+ message = _safe_json_dumps(data)
47
  clients = list(_connections)
48
  dead: set[WebSocket] = set()
49
 
 
140
  except Exception:
141
  pass
142
 
143
+ price_okx = None
144
+ price_bitget = None
145
+ prices = [
146
+ float(p) for p in (price_binance, price_bybit)
147
+ if p is not None and math.isfinite(float(p)) and float(p) > 0
148
+ ]
149
+
150
+ # Fallback to OKX and Bitget for pairs not listed on Binance or Bybit
151
+ if not prices:
152
+ if okx:
153
+ try:
154
+ mp = await okx.get_mark_price(clean_sym)
155
+ raw_okx = mp.get("mark_price") if isinstance(mp, dict) else None
156
+ if raw_okx is not None and math.isfinite(float(raw_okx)) and float(raw_okx) > 0:
157
+ price_okx = float(raw_okx)
158
+ except Exception:
159
+ pass
160
+ if bitget:
161
+ try:
162
+ mp = await bitget.get_mark_price(clean_sym)
163
+ raw_bg = mp.get("mark_price") if isinstance(mp, dict) else None
164
+ if raw_bg is not None and math.isfinite(float(raw_bg)) and float(raw_bg) > 0:
165
+ price_bitget = float(raw_bg)
166
+ except Exception:
167
+ pass
168
+ prices = [p for p in (price_okx, price_bitget) if p and p > 0]
169
+
170
  live_price = prices[0] if prices else 0.0
171
 
172
  if live_price > 0:
173
  now_ts = int(time.time())
174
+ exchanges_payload: dict[str, Any] = {
175
+ "binance": price_binance,
176
+ "bybit": price_bybit,
177
+ }
178
+ if price_okx is not None:
179
+ exchanges_payload["okx"] = price_okx
180
+ if price_bitget is not None:
181
+ exchanges_payload["bitget"] = price_bitget
182
  payload = {
183
  "type": "chart_tick",
184
  "symbol": clean_sym,
185
  "time": now_ts,
186
  "price": live_price,
187
+ "exchanges": exchanges_payload,
 
 
 
188
  }
189
+ await websocket.send_text(_safe_json_dumps(payload))
190
  await asyncio.sleep(1.5)
191
  except (asyncio.CancelledError, WebSocketDisconnect, RuntimeError):
192
  break
backend/scripts/run_backtest.py CHANGED
@@ -62,6 +62,7 @@ async def fetch_historical_dataset(symbol: str, days: int) -> tuple[list[dict],
62
  "low": float(row[3]),
63
  "close": float(row[4]),
64
  "volume": float(row[5]),
 
65
  }
66
  for row in klines_raw
67
  ]
@@ -89,6 +90,7 @@ async def fetch_historical_dataset(symbol: str, days: int) -> tuple[list[dict],
89
  "low": float(row[3]),
90
  "close": float(row[4]),
91
  "volume": float(row[5]),
 
92
  })
93
  next_cursor = int(batch[-1][0]) + 900_000
94
  if next_cursor <= cursor_ms or len(batch) < page_limit:
 
62
  "low": float(row[3]),
63
  "close": float(row[4]),
64
  "volume": float(row[5]),
65
+ "taker_buy_volume": float(row[9]) if len(row) > 9 else None,
66
  }
67
  for row in klines_raw
68
  ]
 
90
  "low": float(row[3]),
91
  "close": float(row[4]),
92
  "volume": float(row[5]),
93
+ "taker_buy_volume": float(row[9]) if len(row) > 9 else None,
94
  })
95
  next_cursor = int(batch[-1][0]) + 900_000
96
  if next_cursor <= cursor_ms or len(batch) < page_limit:
frontend/dist/assets/AIAnalysisPanel-BbXTq8TV.js DELETED
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/GlobalAISettingsModal-y_W5Q-P7.js","assets/vendor-query-BSPl6-aq.js","assets/index-FYyQL2Qc.js","assets/vendor-react-BnvheTds.js","assets/vendor-icons-BBZkXbgm.js","assets/index--kfpEFWJ.css"])))=>i.map(i=>d[i]);
2
- import{u as G,a as F,V as o,G as E,O as M,B as u,F as U,A as K,h as V,_ as H}from"./index-FYyQL2Qc.js";import{r as i,j as e}from"./vendor-query-BSPl6-aq.js";import{m as Q,Z as j,E as f,R as D,C as z,j as v,G as $,k as W,l as Y,f as Z,g as q,H as X}from"./vendor-icons-BBZkXbgm.js";import"./vendor-react-BnvheTds.js";const J=i.lazy(()=>H(()=>import("./GlobalAISettingsModal-y_W5Q-P7.js"),__vite__mapDeps([0,1,2,3,4,5])).then(l=>({default:l.GlobalAISettingsModal})));function re({symbol:l}){const{settings:t,isConfigured:h}=G(),[L,N]=i.useState(t.model),[y,x]=i.useState(!1),[n,k]=i.useState(!1),[_,b]=i.useState(null),[a,T]=i.useState(null),[p,g]=i.useState(""),[A,P]=i.useState(!1),[I,C]=i.useState(!1),{toast:c}=F();i.useEffect(()=>{N(t.model)},[t.provider,t.model]);const r=L||t.model,d=async(s,O=!1)=>{if(!n){if(!h){x(!0),c("Silakan masukkan API Key Anda pada Pengaturan AI Universal","error");return}k(!0),b(null);try{const m=await V.analyze({symbol:l,api_key:t.api_key,provider:t.provider,base_url:t.base_url,model:r,question:s||void 0,force_refresh:O,max_tokens:t.max_tokens});T(m),b(null),s&&g(""),m.is_cached?c("Hasil tersimpan (0 token terpakai)","info"):c(`Analisa AI (${m.model}) selesai dimuat`,"success")}catch(m){const w=m.message||"Gagal melakukan analisa AI";b(w),c(w,"error")}finally{k(!1)}}},R=()=>{a&&(navigator.clipboard.writeText(a.analysis),C(!0),c("Hasil analisa AI disalin ke clipboard!","success"),setTimeout(()=>C(!1),2e3))},B=s=>s.includes("LONG")?"bg-signal-long/20 text-signal-long border-signal-long/40":s.includes("SHORT")?"bg-signal-short/20 text-signal-short border-signal-short/40":"bg-amber-500/20 text-amber-300 border-amber-500/40",S=t.provider==="vikey"?"Vikey AI":t.provider==="gemini"?"Google Gemini":t.provider==="openai"?"OpenAI":"Custom AI";return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 p-2.5 rounded-lg bg-bg-elevated/80 border border-purple-500/20",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"p-1 rounded bg-purple-500/20 text-purple-400 shrink-0",children:e.jsx(Q,{size:13})}),e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:"text-[11px] font-bold text-purple-300 font-mono shrink-0",children:[S,":"]}),e.jsx("select",{value:r,onChange:s=>N(s.target.value),className:"bg-bg-primary/90 border border-purple-500/30 hover:border-purple-400 rounded px-1.5 py-0.5 text-[11px] text-text-primary font-mono outline-none max-w-[130px] xs:max-w-[170px] sm:max-w-[220px] truncate cursor-pointer",title:"Pilih model AI untuk pair ini",children:t.provider==="vikey"?e.jsxs(e.Fragment,{children:[e.jsx("optgroup",{label:"Anthropic (Claude)",children:o.filter(s=>s.category==="Anthropic").map(s=>e.jsx("option",{value:s.id,children:s.id},s.id))}),e.jsx("optgroup",{label:"DeepSeek",children:o.filter(s=>s.category==="DeepSeek").map(s=>e.jsx("option",{value:s.id,children:s.id},s.id))}),e.jsx("optgroup",{label:"OpenAI",children:o.filter(s=>s.category==="OpenAI").map(s=>e.jsx("option",{value:s.id,children:s.id},s.id))}),e.jsx("optgroup",{label:"Google",children:o.filter(s=>s.category==="Google").map(s=>e.jsx("option",{value:s.id,children:s.id},s.id))}),e.jsx("optgroup",{label:"Lainnya",children:o.filter(s=>["Qwen","Moonshot","MiniMax","GLM"].includes(s.category)).map(s=>e.jsx("option",{value:s.id,children:s.id},s.id))}),!o.some(s=>s.id===r)&&e.jsxs("option",{value:r,children:["Custom: ",r]})]}):t.provider==="gemini"?e.jsxs(e.Fragment,{children:[E.map(s=>e.jsx("option",{value:s.id,children:s.id},s.id)),!E.some(s=>s.id===r)&&e.jsxs("option",{value:r,children:["Custom: ",r]})]}):e.jsxs(e.Fragment,{children:[M.map(s=>e.jsx("option",{value:s.id,children:s.id},s.id)),!M.some(s=>s.id===r)&&e.jsxs("option",{value:r,children:["Custom: ",r]})]})}),a?.is_cached&&e.jsxs("span",{className:"px-1.5 py-0.2 rounded text-[9px] font-mono bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 flex items-center gap-0.5 shrink-0",children:[e.jsx(j,{size:9}),"Cached (0 Token)"]})]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("button",{type:"button",onClick:()=>x(!0),className:"px-2 py-0.5 rounded text-[11px] border border-border hover:border-purple-400 text-text-secondary hover:text-text-primary flex items-center gap-1 transition-colors bg-bg-primary/50 shrink-0",title:"Buka Pengaturan AI Universal untuk ganti API Key atau tambah model",children:[e.jsx(f,{size:11,className:"text-purple-400"}),e.jsx("span",{className:"hidden xs:inline",children:"Pengaturan AI"}),e.jsx("span",{className:"xs:hidden",children:"Atur"})]}),a&&e.jsx(u,{variant:"ghost",size:"sm",onClick:()=>d(void 0,!0),loading:n,icon:e.jsx(D,{size:11}),title:"Paksa Analisa Baru (Bypass Cache)",children:"Fresh Run"})]})]}),!h&&e.jsxs("div",{className:"p-3.5 rounded-lg bg-amber-500/10 border border-amber-500/30 space-y-2 animate-fade-in text-center sm:text-left sm:flex sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx(z,{size:16,className:"text-amber-400 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-amber-200",children:"API Key Belum Dikonfigurasi"}),e.jsx("p",{className:"text-[11px] text-text-secondary mt-0.5",children:"Masukkan API Key Vikey, Gemini, atau OpenAI satu kali di Pengaturan Universal untuk menganalisa seluruh pair tanpa perlu input berulang."})]})]}),e.jsx(u,{variant:"primary",size:"sm",onClick:()=>x(!0),icon:e.jsx(f,{size:12}),className:"shrink-0 bg-amber-600 hover:bg-amber-500 text-white",children:"Atur AI Sekarang"})]}),_&&e.jsxs("div",{className:"p-3.5 rounded-lg bg-red-500/10 border border-red-500/30 text-xs text-red-200 flex items-start gap-3 animate-fade-in",children:[e.jsx(z,{size:16,className:"text-red-400 shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"font-bold text-red-300",children:["Gagal Memuat Analisa AI (",r,")"]}),e.jsx("span",{className:"text-[10px] text-red-400/80 font-mono uppercase",children:t.provider})]}),e.jsx("p",{className:"text-[11px] text-red-200/90 leading-relaxed font-mono bg-red-950/40 p-2 rounded border border-red-500/20 break-words",children:_}),e.jsxs("div",{className:"pt-1 flex flex-wrap items-center gap-2",children:[e.jsx(u,{variant:"ghost",size:"sm",onClick:()=>d(void 0,!0),loading:n,icon:e.jsx(D,{size:11}),className:"text-[11px] h-7 px-2.5 bg-red-500/20 hover:bg-red-500/30 text-red-100 border border-red-500/30",children:"Coba Lagi"}),e.jsxs("button",{type:"button",onClick:()=>x(!0),className:"text-[11px] text-purple-300 hover:text-purple-200 underline flex items-center gap-1 ml-1",children:[e.jsx(f,{size:11}),"Buka Pengaturan AI (Cek API Key / Ganti Model)"]})]})]})]}),n&&e.jsxs("div",{className:"py-8 flex flex-col items-center justify-center space-y-2.5 text-center animate-fade-in",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"w-9 h-9 rounded-full border-2 border-purple-500/30 border-t-purple-500 animate-spin"}),e.jsx(v,{size:14,className:"absolute inset-0 m-auto text-purple-400 animate-pulse"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs font-semibold text-text-primary",children:["AI Sedang Menganalisa Data Live ",l,"..."]}),e.jsxs("p",{className:"text-[10px] text-text-muted mt-0.5",children:["Mengirim data orderbook, likuidasi, Spot vs Futures CVD ke ",r,"..."]})]})]}),!n&&a&&e.jsxs("div",{className:"space-y-2.5 animate-fade-in",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 p-2 rounded-lg bg-bg-elevated/60 border border-border/80",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] text-text-secondary uppercase font-semibold",children:"Bias AI:"}),e.jsx("span",{className:`px-2 py-0.5 rounded text-[11px] font-mono font-bold border ${B(a.bias)}`,children:a.bias}),e.jsxs("span",{className:"text-[10px] text-text-muted font-mono hidden sm:inline",children:["(",a.model,")"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("button",{onClick:()=>P(s=>!s),className:"px-2 py-0.5 rounded text-[10px] border border-border text-text-secondary hover:text-text-primary flex items-center gap-1 hover:bg-bg-elevated transition-colors",title:"Lihat Data yang Dikirim ke AI",children:[e.jsx($,{size:10}),e.jsx("span",{children:"Data Bursa"}),A?e.jsx(W,{size:10}):e.jsx(Y,{size:10})]}),e.jsxs("button",{onClick:R,className:"px-2 py-0.5 rounded text-[10px] border border-border text-text-secondary hover:text-text-primary flex items-center gap-1 hover:bg-bg-elevated transition-colors",children:[I?e.jsx(Z,{size:11,className:"text-signal-long"}):e.jsx(q,{size:11}),e.jsx("span",{children:I?"Tersalin":"Salin"})]})]})]}),A&&a.data_snapshot&&e.jsxs("div",{className:"p-2.5 rounded-lg bg-bg-primary border border-border/80 text-[10px] font-mono grid grid-cols-2 sm:grid-cols-3 gap-2 animate-fade-in",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"MARK PRICE"}),e.jsx("span",{className:"text-text-primary font-bold",children:a.data_snapshot.mark_price_str||`$${a.data_snapshot.mark_price}`})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"MULTI-VENUE SPREAD"}),e.jsxs("span",{className:"text-text-primary",children:[a.data_snapshot.triangulation_spread_pct.toFixed(4),"%"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"BINANCE FR"}),e.jsx("span",{className:"text-text-primary",children:a.data_snapshot.binance_fr})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"BYBIT FR"}),e.jsx("span",{className:"text-text-primary",children:a.data_snapshot.bybit_fr})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"OKX FR"}),e.jsx("span",{className:"text-text-primary",children:a.data_snapshot.okx_fr})]}),a.data_snapshot.bitget_fr&&e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"BITGET FR"}),e.jsx("span",{className:"text-text-primary",children:a.data_snapshot.bitget_fr})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"HYPERLIQUID FR"}),e.jsx("span",{className:"text-purple-300",children:a.data_snapshot.hyperliquid_fr})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"SPOT vs FUT CVD"}),e.jsxs("span",{className:"text-amber-300",children:["Spot: ",a.data_snapshot.spot_cvd," | Fut: ",a.data_snapshot.futures_cvd]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"LIQ MAGNET ATAS"}),e.jsx("span",{className:"text-signal-long",children:a.data_snapshot.upper_magnet})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"LIQ MAGNET BAWAH"}),e.jsx("span",{className:"text-signal-short",children:a.data_snapshot.lower_magnet})]}),a.data_snapshot.lead_lag_spread_bps!==void 0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"LEAD-LAG SPREAD"}),e.jsxs("span",{className:"text-cyan-300",children:[a.data_snapshot.lead_lag_spread_bps.toFixed(1)," bps (",a.data_snapshot.leading_exchange?.toUpperCase()||"BALANCED",")"]})]}),a.data_snapshot.funding_countdown&&e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"SETTLEMENT COUNTDOWN"}),e.jsx("span",{className:a.data_snapshot.is_settlement_imminent?"text-amber-400 font-bold":"text-text-primary",children:a.data_snapshot.funding_countdown})]}),a.data_snapshot.range_24h_pct!==void 0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"RENTANG 24 JAM"}),e.jsxs("span",{className:"text-text-primary",children:[a.data_snapshot.range_24h_pct.toFixed(2),"% (",a.data_snapshot.range_position_pct?.toFixed(0),"% pos)"]})]}),a.data_snapshot.whale_buy_count!==void 0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"WHALE BLOCK TRADES"}),e.jsxs("span",{className:"text-emerald-400",children:[a.data_snapshot.whale_buy_count," Buys / ",a.data_snapshot.whale_sell_count," Sells"]})]}),a.data_snapshot.breakout_radar?.is_breakout_primed&&e.jsxs("div",{className:"col-span-2 sm:col-span-3 p-1.5 rounded bg-purple-500/15 border border-purple-500/30 flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-yellow-400 font-bold text-[9px] flex items-center gap-1 shrink-0",children:[e.jsx(j,{size:10})," SQUEEZE RADAR:"]}),e.jsxs("span",{className:"text-purple-200 text-[10px] font-semibold break-words text-right",children:[a.data_snapshot.breakout_radar.radar_label," — ",a.data_snapshot.breakout_radar.catalyst_summary]})]})]}),e.jsx("div",{className:"p-3.5 rounded-lg bg-bg-elevated/30 border border-border/70 max-h-[420px] overflow-y-auto custom-scrollbar",children:e.jsx(U,{content:a.analysis})}),e.jsx(K,{symbol:l,content:a.analysis,bias:a.bias,dataSnapshot:a.data_snapshot,modelUsed:a.model}),e.jsxs("div",{className:"p-2.5 rounded-lg bg-bg-elevated/40 border border-border space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-[10px] font-semibold text-text-secondary uppercase tracking-wider flex items-center gap-1",children:[e.jsx(v,{size:10,className:"text-purple-400"}),"Tanya Lanjutan ke AI (",l,")"]}),e.jsx("span",{className:"text-[9px] text-text-muted",children:"Tekan chip untuk tanya instan"})]}),e.jsx("div",{className:"flex flex-wrap gap-1 pb-1",children:["⚡ Di mana potensi wick hunt terdekat?","⚠️ Apakah ada risiko leverage trap?","🛡️ Aman scalping sekarang atau tunggu pullback?","🎯 Berapa target likuidasi whale berikutnya?"].map(s=>e.jsx("button",{type:"button",onClick:()=>{g(s),d(s)},disabled:n,className:"text-[10px] px-2 py-0.5 rounded-full bg-purple-500/10 hover:bg-purple-500/20 text-purple-300 border border-purple-500/20 hover:border-purple-400 transition-all cursor-pointer disabled:opacity-50",children:s},s))}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("input",{type:"text",className:"input-field flex-1 text-xs font-sans py-1",placeholder:"Contoh: 'Aman gak scalping sekarang?' atau 'Kalau kena SL gimana?'",value:p,onChange:s=>g(s.target.value),onKeyDown:s=>{s.key==="Enter"&&p.trim()&&d(p)}}),e.jsx(u,{variant:"primary",size:"sm",onClick:()=>d(p),disabled:!p.trim()||n,icon:e.jsx(X,{size:11}),children:"Tanya"})]})]})]}),!n&&!a&&h&&e.jsxs("div",{className:"py-6 flex flex-col items-center justify-center text-center space-y-2",children:[e.jsx("div",{className:"p-2.5 rounded-full bg-purple-500/10 text-purple-400 border border-purple-500/20",children:e.jsx(v,{size:18})}),e.jsxs("div",{children:[e.jsxs("h4",{className:"text-xs font-bold text-text-primary",children:["Mulai Analisa AI Independen untuk ",l]}),e.jsxs("p",{className:"text-[11px] text-text-muted max-w-sm mt-0.5",children:["Menggunakan model ",e.jsx("span",{className:"font-mono text-purple-300 font-semibold",children:r})," (",S,"). Data Binance, Bybit, OKX, Hyperliquid, CVD, & Likuidasi akan dirangkum otomatis."]})]}),e.jsx(u,{variant:"primary",size:"sm",onClick:()=>d(),loading:n,disabled:n,icon:e.jsx(j,{size:12}),className:"bg-purple-600 hover:bg-purple-500 text-white shadow-lg shadow-purple-500/20",children:n?"Sedang Menganalisa...":"Mulai Analisa AI"})]}),y&&e.jsx(i.Suspense,{fallback:null,children:e.jsx(J,{isOpen:y,onClose:()=>x(!1)})})]})}export{re as AIAnalysisPanel};
 
 
 
frontend/dist/assets/AIAnalysisPanel-DsgKGe3C.js ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/GlobalAISettingsModal-BOzCh0qM.js","assets/vendor-query-BSPl6-aq.js","assets/index-CaCGPr1l.js","assets/vendor-react-BnvheTds.js","assets/vendor-icons-BBZkXbgm.js","assets/index-DaWuxWbx.css"])))=>i.map(i=>d[i]);
2
+ import{u as U,a as K,V as o,G as M,b as D,c as L,O,B as u,F as V,A as H,j as Q,_ as q}from"./index-CaCGPr1l.js";import{r as n,j as e}from"./vendor-query-BSPl6-aq.js";import{m as $,Z as j,E as v,R as z,C as R,j as f,G as W,k as Y,l as Z,f as X,g as J,H as ee}from"./vendor-icons-BBZkXbgm.js";import"./vendor-react-BnvheTds.js";const se=n.lazy(()=>q(()=>import("./GlobalAISettingsModal-BOzCh0qM.js"),__vite__mapDeps([0,1,2,3,4,5])).then(l=>({default:l.GlobalAISettingsModal})));function ie({symbol:l}){const{settings:t,isConfigured:g}=U(),[T,N]=n.useState(t.model),[k,x]=n.useState(!1),[i,y]=n.useState(!1),[_,h]=n.useState(null),[a,A]=n.useState(null),[p,b]=n.useState(""),[I,P]=n.useState(!1),[C,S]=n.useState(!1),{toast:c}=K();n.useEffect(()=>{N(t.model)},[t.provider,t.model]),n.useEffect(()=>{A(null),h(null),b("")},[l]);const r=T||t.model,d=async(s,F=!1)=>{if(!i){if(!g){x(!0),c("Silakan masukkan API Key Anda pada Pengaturan AI Universal","error");return}y(!0),h(null);try{const m=await Q.analyze({symbol:l,api_key:t.api_key,provider:t.provider,base_url:t.provider==="custom"?t.base_url:void 0,model:r,question:s||void 0,force_refresh:F,max_tokens:t.max_tokens});A(m),h(null),s&&b(""),m.is_cached?c("Hasil tersimpan (0 token terpakai)","info"):c(`Analisa AI (${m.model}) selesai dimuat`,"success")}catch(m){const E=m.message||"Gagal melakukan analisa AI";h(E),c(E,"error")}finally{y(!1)}}},B=()=>{a&&(navigator.clipboard.writeText(a.analysis),S(!0),c("Hasil analisa AI disalin ke clipboard!","success"),setTimeout(()=>S(!1),2e3))},G=s=>s.includes("LONG")?"bg-signal-long/20 text-signal-long border-signal-long/40":s.includes("SHORT")?"bg-signal-short/20 text-signal-short border-signal-short/40":"bg-amber-500/20 text-amber-300 border-amber-500/40",w=t.provider==="vikey"?"Vikey AI":t.provider==="gemini"?"Google Gemini":t.provider==="openai"?"OpenAI":t.provider==="openrouter"?"OpenRouter":t.provider==="groq"?"Groq":"Custom AI";return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 p-2.5 rounded-lg bg-bg-elevated/80 border border-purple-500/20",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"p-1 rounded bg-purple-500/20 text-purple-400 shrink-0",children:e.jsx($,{size:13})}),e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:"text-[11px] font-bold text-purple-300 font-mono shrink-0",children:[w,":"]}),e.jsx("select",{value:r,onChange:s=>N(s.target.value),className:"bg-bg-primary/90 border border-purple-500/30 hover:border-purple-400 rounded px-1.5 py-0.5 text-[11px] text-text-primary font-mono outline-none max-w-[130px] xs:max-w-[170px] sm:max-w-[220px] truncate cursor-pointer",title:"Pilih model AI untuk pair ini",children:t.provider==="vikey"?e.jsxs(e.Fragment,{children:[e.jsx("optgroup",{label:"Anthropic (Claude)",children:o.filter(s=>s.category==="Anthropic").map(s=>e.jsx("option",{value:s.id,children:s.id},s.id))}),e.jsx("optgroup",{label:"DeepSeek",children:o.filter(s=>s.category==="DeepSeek").map(s=>e.jsx("option",{value:s.id,children:s.id},s.id))}),e.jsx("optgroup",{label:"OpenAI",children:o.filter(s=>s.category==="OpenAI").map(s=>e.jsx("option",{value:s.id,children:s.id},s.id))}),e.jsx("optgroup",{label:"Google",children:o.filter(s=>s.category==="Google").map(s=>e.jsx("option",{value:s.id,children:s.id},s.id))}),e.jsx("optgroup",{label:"Lainnya",children:o.filter(s=>["Qwen","Moonshot","MiniMax","GLM"].includes(s.category)).map(s=>e.jsx("option",{value:s.id,children:s.id},s.id))}),!o.some(s=>s.id===r)&&e.jsxs("option",{value:r,children:["Custom: ",r]})]}):t.provider==="gemini"?e.jsxs(e.Fragment,{children:[M.map(s=>e.jsx("option",{value:s.id,children:s.id},s.id)),!M.some(s=>s.id===r)&&e.jsxs("option",{value:r,children:["Custom: ",r]})]}):t.provider==="openrouter"?e.jsxs(e.Fragment,{children:[D.map(s=>e.jsx("option",{value:s.id,children:s.id},s.id)),!D.some(s=>s.id===r)&&e.jsxs("option",{value:r,children:["Custom: ",r]})]}):t.provider==="groq"?e.jsxs(e.Fragment,{children:[L.map(s=>e.jsx("option",{value:s.id,children:s.id},s.id)),!L.some(s=>s.id===r)&&e.jsxs("option",{value:r,children:["Custom: ",r]})]}):e.jsxs(e.Fragment,{children:[O.map(s=>e.jsx("option",{value:s.id,children:s.id},s.id)),!O.some(s=>s.id===r)&&e.jsxs("option",{value:r,children:["Custom: ",r]})]})}),a?.is_cached&&e.jsxs("span",{className:"px-1.5 py-0.2 rounded text-[9px] font-mono bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 flex items-center gap-0.5 shrink-0",children:[e.jsx(j,{size:9}),"Cached (0 Token)"]})]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("button",{type:"button",onClick:()=>x(!0),className:"px-2 py-0.5 rounded text-[11px] border border-border hover:border-purple-400 text-text-secondary hover:text-text-primary flex items-center gap-1 transition-colors bg-bg-primary/50 shrink-0",title:"Buka Pengaturan AI Universal untuk ganti API Key atau tambah model",children:[e.jsx(v,{size:11,className:"text-purple-400"}),e.jsx("span",{className:"hidden xs:inline",children:"Pengaturan AI"}),e.jsx("span",{className:"xs:hidden",children:"Atur"})]}),a&&e.jsx(u,{variant:"ghost",size:"sm",onClick:()=>d(void 0,!0),loading:i,icon:e.jsx(z,{size:11}),title:"Paksa Analisa Baru (Bypass Cache)",children:"Fresh Run"})]})]}),!g&&e.jsxs("div",{className:"p-3.5 rounded-lg bg-amber-500/10 border border-amber-500/30 space-y-2 animate-fade-in text-center sm:text-left sm:flex sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx(R,{size:16,className:"text-amber-400 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-amber-200",children:"API Key Belum Dikonfigurasi"}),e.jsx("p",{className:"text-[11px] text-text-secondary mt-0.5",children:"Masukkan API Key Vikey, Gemini, atau OpenAI satu kali di Pengaturan Universal untuk menganalisa seluruh pair tanpa perlu input berulang."})]})]}),e.jsx(u,{variant:"primary",size:"sm",onClick:()=>x(!0),icon:e.jsx(v,{size:12}),className:"shrink-0 bg-amber-600 hover:bg-amber-500 text-white",children:"Atur AI Sekarang"})]}),_&&e.jsxs("div",{className:"p-3.5 rounded-lg bg-red-500/10 border border-red-500/30 text-xs text-red-200 flex items-start gap-3 animate-fade-in",children:[e.jsx(R,{size:16,className:"text-red-400 shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"font-bold text-red-300",children:["Gagal Memuat Analisa AI (",r,")"]}),e.jsx("span",{className:"text-[10px] text-red-400/80 font-mono uppercase",children:t.provider})]}),e.jsx("p",{className:"text-[11px] text-red-200/90 leading-relaxed font-mono bg-red-950/40 p-2 rounded border border-red-500/20 break-words",children:_}),e.jsxs("div",{className:"pt-1 flex flex-wrap items-center gap-2",children:[e.jsx(u,{variant:"ghost",size:"sm",onClick:()=>d(void 0,!0),loading:i,icon:e.jsx(z,{size:11}),className:"text-[11px] h-7 px-2.5 bg-red-500/20 hover:bg-red-500/30 text-red-100 border border-red-500/30",children:"Coba Lagi"}),e.jsxs("button",{type:"button",onClick:()=>x(!0),className:"text-[11px] text-purple-300 hover:text-purple-200 underline flex items-center gap-1 ml-1",children:[e.jsx(v,{size:11}),"Buka Pengaturan AI (Cek API Key / Ganti Model)"]})]})]})]}),i&&e.jsxs("div",{className:"py-8 flex flex-col items-center justify-center space-y-2.5 text-center animate-fade-in",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"w-9 h-9 rounded-full border-2 border-purple-500/30 border-t-purple-500 animate-spin"}),e.jsx(f,{size:14,className:"absolute inset-0 m-auto text-purple-400 animate-pulse"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs font-semibold text-text-primary",children:["AI Sedang Menganalisa Data Live ",l,"..."]}),e.jsxs("p",{className:"text-[10px] text-text-muted mt-0.5",children:["Mengirim data orderbook, likuidasi, Spot vs Futures CVD ke ",r,"..."]})]})]}),!i&&a&&e.jsxs("div",{className:"space-y-2.5 animate-fade-in",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 p-2 rounded-lg bg-bg-elevated/60 border border-border/80",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] text-text-secondary uppercase font-semibold",children:"Bias AI:"}),e.jsx("span",{className:`px-2 py-0.5 rounded text-[11px] font-mono font-bold border ${G(a.bias)}`,children:a.bias}),e.jsxs("span",{className:"text-[10px] text-text-muted font-mono hidden sm:inline",children:["(",a.model,")"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("button",{onClick:()=>P(s=>!s),className:"px-2 py-0.5 rounded text-[10px] border border-border text-text-secondary hover:text-text-primary flex items-center gap-1 hover:bg-bg-elevated transition-colors",title:"Lihat Data yang Dikirim ke AI",children:[e.jsx(W,{size:10}),e.jsx("span",{children:"Data Bursa"}),I?e.jsx(Y,{size:10}):e.jsx(Z,{size:10})]}),e.jsxs("button",{onClick:B,className:"px-2 py-0.5 rounded text-[10px] border border-border text-text-secondary hover:text-text-primary flex items-center gap-1 hover:bg-bg-elevated transition-colors",children:[C?e.jsx(X,{size:11,className:"text-signal-long"}):e.jsx(J,{size:11}),e.jsx("span",{children:C?"Tersalin":"Salin"})]})]})]}),I&&a.data_snapshot&&e.jsxs("div",{className:"p-2.5 rounded-lg bg-bg-primary border border-border/80 text-[10px] font-mono grid grid-cols-2 sm:grid-cols-3 gap-2 animate-fade-in",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"MARK PRICE"}),e.jsx("span",{className:"text-text-primary font-bold",children:a.data_snapshot.mark_price_str||`$${a.data_snapshot.mark_price}`})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"MULTI-VENUE SPREAD"}),e.jsxs("span",{className:"text-text-primary",children:[(a.data_snapshot.triangulation_spread_pct??0).toFixed(4),"%"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"BINANCE FR"}),e.jsx("span",{className:"text-text-primary",children:a.data_snapshot.binance_fr})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"BYBIT FR"}),e.jsx("span",{className:"text-text-primary",children:a.data_snapshot.bybit_fr})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"OKX FR"}),e.jsx("span",{className:"text-text-primary",children:a.data_snapshot.okx_fr})]}),a.data_snapshot.bitget_fr&&e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"BITGET FR"}),e.jsx("span",{className:"text-text-primary",children:a.data_snapshot.bitget_fr})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"HYPERLIQUID FR"}),e.jsx("span",{className:"text-purple-300",children:a.data_snapshot.hyperliquid_fr})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"SPOT vs FUT CVD"}),e.jsxs("span",{className:"text-amber-300",children:["Spot: ",a.data_snapshot.spot_cvd," | Fut: ",a.data_snapshot.futures_cvd]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"LIQ MAGNET ATAS"}),e.jsx("span",{className:"text-signal-long",children:a.data_snapshot.upper_magnet})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"LIQ MAGNET BAWAH"}),e.jsx("span",{className:"text-signal-short",children:a.data_snapshot.lower_magnet})]}),a.data_snapshot.lead_lag_spread_bps!=null&&e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"LEAD-LAG SPREAD"}),e.jsxs("span",{className:"text-cyan-300",children:[(a.data_snapshot.lead_lag_spread_bps??0).toFixed(1)," bps (",a.data_snapshot.leading_exchange?.toUpperCase()||"BALANCED",")"]})]}),a.data_snapshot.funding_countdown&&e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"SETTLEMENT COUNTDOWN"}),e.jsx("span",{className:a.data_snapshot.is_settlement_imminent?"text-amber-400 font-bold":"text-text-primary",children:a.data_snapshot.funding_countdown})]}),a.data_snapshot.range_24h_pct!=null&&e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"RENTANG 24 JAM"}),e.jsxs("span",{className:"text-text-primary",children:[(a.data_snapshot.range_24h_pct??0).toFixed(2),"% (",(a.data_snapshot.range_position_pct??0).toFixed(0),"% pos)"]})]}),a.data_snapshot.whale_buy_count!==void 0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted block text-[9px]",children:"WHALE BLOCK TRADES"}),e.jsxs("span",{className:"text-emerald-400",children:[a.data_snapshot.whale_buy_count," Buys / ",a.data_snapshot.whale_sell_count," Sells"]})]}),a.data_snapshot.breakout_radar?.is_breakout_primed&&e.jsxs("div",{className:"col-span-2 sm:col-span-3 p-1.5 rounded bg-purple-500/15 border border-purple-500/30 flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-yellow-400 font-bold text-[9px] flex items-center gap-1 shrink-0",children:[e.jsx(j,{size:10})," SQUEEZE RADAR:"]}),e.jsxs("span",{className:"text-purple-200 text-[10px] font-semibold break-words text-right",children:[a.data_snapshot.breakout_radar.radar_label," — ",a.data_snapshot.breakout_radar.catalyst_summary]})]})]}),e.jsx("div",{className:"p-3.5 rounded-lg bg-bg-elevated/30 border border-border/70 max-h-[420px] overflow-y-auto custom-scrollbar",children:e.jsx(V,{content:a.analysis})}),e.jsx(H,{symbol:l,content:a.analysis,bias:a.bias,dataSnapshot:a.data_snapshot,modelUsed:a.model}),e.jsxs("div",{className:"p-2.5 rounded-lg bg-bg-elevated/40 border border-border space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-[10px] font-semibold text-text-secondary uppercase tracking-wider flex items-center gap-1",children:[e.jsx(f,{size:10,className:"text-purple-400"}),"Tanya Lanjutan ke AI (",l,")"]}),e.jsx("span",{className:"text-[9px] text-text-muted",children:"Tekan chip untuk tanya instan"})]}),e.jsx("div",{className:"flex flex-wrap gap-1 pb-1",children:["⚡ Di mana potensi wick hunt terdekat?","⚠️ Apakah ada risiko leverage trap?","🛡️ Aman scalping sekarang atau tunggu pullback?","🎯 Berapa target likuidasi whale berikutnya?"].map(s=>e.jsx("button",{type:"button",onClick:()=>{b(s),d(s)},disabled:i,className:"text-[10px] px-2 py-0.5 rounded-full bg-purple-500/10 hover:bg-purple-500/20 text-purple-300 border border-purple-500/20 hover:border-purple-400 transition-all cursor-pointer disabled:opacity-50",children:s},s))}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("input",{type:"text",className:"input-field flex-1 text-xs font-sans py-1",placeholder:"Contoh: 'Aman gak scalping sekarang?' atau 'Kalau kena SL gimana?'",value:p,onChange:s=>b(s.target.value),onKeyDown:s=>{s.key==="Enter"&&p.trim()&&d(p)}}),e.jsx(u,{variant:"primary",size:"sm",onClick:()=>d(p),disabled:!p.trim()||i,icon:e.jsx(ee,{size:11}),children:"Tanya"})]})]})]}),!i&&!a&&g&&e.jsxs("div",{className:"py-6 flex flex-col items-center justify-center text-center space-y-2",children:[e.jsx("div",{className:"p-2.5 rounded-full bg-purple-500/10 text-purple-400 border border-purple-500/20",children:e.jsx(f,{size:18})}),e.jsxs("div",{children:[e.jsxs("h4",{className:"text-xs font-bold text-text-primary",children:["Mulai Analisa AI Independen untuk ",l]}),e.jsxs("p",{className:"text-[11px] text-text-muted max-w-sm mt-0.5",children:["Menggunakan model ",e.jsx("span",{className:"font-mono text-purple-300 font-semibold",children:r})," (",w,"). Data Binance, Bybit, OKX, Hyperliquid, CVD, & Likuidasi akan dirangkum otomatis."]})]}),e.jsx(u,{variant:"primary",size:"sm",onClick:()=>d(),loading:i,disabled:i,icon:e.jsx(j,{size:12}),className:"bg-purple-600 hover:bg-purple-500 text-white shadow-lg shadow-purple-500/20",children:i?"Sedang Menganalisa...":"Mulai Analisa AI"})]}),k&&e.jsx(n.Suspense,{fallback:null,children:e.jsx(se,{isOpen:k,onClose:()=>x(!1)})})]})}export{ie as AIAnalysisPanel};
frontend/dist/assets/AddPairModal-D8YkLLF_.js DELETED
@@ -1 +0,0 @@
1
- import{r as h,j as e}from"./vendor-query-BSPl6-aq.js";import{a as S,b as T,c as C,M as _,B as m}from"./index-FYyQL2Qc.js";import{S as P,a3 as g,b as z}from"./vendor-icons-BBZkXbgm.js";import"./vendor-react-BnvheTds.js";function r({label:i,found:a}){return e.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded-lg text-sm ${a?"bg-signal-long-bg border border-signal-long/20 text-signal-long":"bg-signal-short-bg border border-signal-short/20 text-signal-short"}`,children:[a?e.jsx(z,{size:14}):e.jsx(g,{size:14}),e.jsx("span",{className:"font-medium",children:a?"✓":"✗"}),e.jsx("span",{className:"text-text-primary",children:i})]})}const p=i=>{const a=i.trim().toUpperCase().replace(/[\/\-_ ]/g,"");return a?a.endsWith("USDT")?a:`${a}USDT`:""};function w({isOpen:i,onClose:a}){const[n,u]=h.useState(""),[s,l]=h.useState(null),{toast:o}=S(),{mutate:j,isPending:y}=T(),{mutate:f,isPending:N}=C(),b=()=>{const t=p(n);t&&(l(null),j(t,{onSuccess:x=>l(x),onError:x=>o(x.message,"error")}))},v=()=>{!c||!s||f(s.symbol,{onSuccess:()=>{o(`${s.symbol} berhasil ditambahkan!`,"success"),d()},onError:t=>o(t.message,"error")})},d=()=>{u(""),l(null),a()},k=t=>{t.key==="Enter"&&b()},c=!!(s&&(s.valid??(s.on_binance||s.on_bybit||s.on_okx||s.on_bitget||s.on_hyperliquid)));return e.jsx(_,{isOpen:i,onClose:d,title:"Tambah Trading Pair",size:"sm",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-text-secondary",children:"Masukkan nama koin perpetual futures. Tanpa perlu ketik USDT, sistem otomatis memasangkannya."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary uppercase tracking-wide",children:"Ticker Koin"}),e.jsx("span",{className:"text-[11px] text-accent-blue font-medium",children:"Otomatis +USDT"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{type:"text",className:"input-field w-full font-mono uppercase pr-16",placeholder:"Contoh: BTC, ETH, SOL, PEPE",value:n,onChange:t=>{u(t.target.value.toUpperCase()),l(null)},onKeyDown:k,autoFocus:!0}),e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none",children:e.jsx("span",{className:"text-[11px] font-mono font-semibold text-text-secondary/70 bg-bg-card px-1.5 py-0.5 rounded border border-border/50",children:"USDT"})})]}),e.jsx(m,{variant:"ghost",size:"md",onClick:b,loading:y,disabled:!n.trim(),icon:e.jsx(P,{size:14}),children:"Cek Pair"})]}),n.trim()&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary pt-0.5",children:[e.jsx("span",{children:"Target Pair:"}),e.jsx("span",{className:"font-mono font-bold text-accent-blue bg-accent-blue/10 px-1.5 py-0.5 rounded border border-accent-blue/20",children:p(n)}),e.jsxs("span",{className:"text-[11px] text-text-secondary/80",children:["(",p(n).replace("USDT",""),"/USDT)"]})]})]}),s&&e.jsxs("div",{className:"space-y-2 animate-fade-in pt-1",children:[e.jsxs("div",{className:"flex items-center justify-between pb-1.5 border-b border-border/50 text-xs",children:[e.jsx("span",{className:"text-text-secondary",children:"Pair Terkonfirmasi:"}),e.jsx("span",{className:"font-mono font-bold text-emerald-400",children:s.symbol})]}),e.jsx("p",{className:"text-xs font-medium text-text-secondary uppercase tracking-wide",children:"Ketersediaan Bursa"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(r,{label:"Binance",found:s.on_binance}),e.jsx(r,{label:"Bybit",found:s.on_bybit}),s.on_okx!==void 0&&e.jsx(r,{label:"OKX",found:s.on_okx}),s.on_bitget!==void 0&&e.jsx(r,{label:"Bitget",found:s.on_bitget}),s.on_hyperliquid!==void 0&&e.jsx(r,{label:"Hyperliquid",found:s.on_hyperliquid})]}),!c&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-signal-short-bg border border-signal-short/20",children:[e.jsx(g,{size:14,className:"text-signal-short shrink-0"}),e.jsx("p",{className:"text-xs text-text-secondary",children:s.message||"Symbol tidak ditemukan di bursa mana pun"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(m,{variant:"ghost",size:"md",onClick:d,children:"Batal"}),c&&s&&e.jsxs(m,{variant:"primary",size:"md",onClick:v,loading:N,children:["Tambah Pair (",s.symbol,")"]})]})]})})}export{w as AddPairModal};
 
 
frontend/dist/assets/AddPairModal-DCQtFcNW.js ADDED
@@ -0,0 +1 @@
 
 
1
+ import{r as b,j as e}from"./vendor-query-BSPl6-aq.js";import{a as C,d as T,e as _,M as P,B as u}from"./index-CaCGPr1l.js";import{S as U,a3 as g,b as E}from"./vendor-icons-BBZkXbgm.js";import"./vendor-react-BnvheTds.js";function o({label:a,found:t}){return e.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded-lg text-sm ${t?"bg-signal-long-bg border border-signal-long/20 text-signal-long":"bg-signal-short-bg border border-signal-short/20 text-signal-short"}`,children:[t?e.jsx(E,{size:14}):e.jsx(g,{size:14}),e.jsx("span",{className:"font-medium",children:t?"✓":"✗"}),e.jsx("span",{className:"text-text-primary",children:a})]})}const j=["USDT","USDC","BUSD","USD","EUR"],p=a=>{const t=a.trim().toUpperCase().replace(/[\/\-_ ]/g,"");return t?j.some(r=>t.endsWith(r)&&t.length>r.length)?t:`${t}USDT`:""},B=a=>{for(const t of j)if(a.endsWith(t)&&a.length>t.length)return`${a.slice(0,-t.length)}/${t}`;return a};function K({isOpen:a,onClose:t}){const[i,r]=b.useState(""),[s,l]=b.useState(null),{toast:d}=C(),{mutate:f,isPending:y}=T(),{mutate:N,isPending:v}=_(),h=()=>{const n=p(i);n&&(l(null),f(n,{onSuccess:m=>l(m),onError:m=>d(m.message,"error")}))},k=()=>{!x||!s||N(s.symbol,{onSuccess:()=>{d(`${s.symbol} berhasil ditambahkan!`,"success"),c()},onError:n=>d(n.message,"error")})},c=()=>{r(""),l(null),t()},S=n=>{n.key==="Enter"&&h()},x=!!(s&&(s.valid??(s.on_binance||s.on_bybit||s.on_okx||s.on_bitget||s.on_hyperliquid)));return e.jsx(P,{isOpen:a,onClose:c,title:"Tambah Trading Pair",size:"sm",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-text-secondary",children:"Masukkan nama koin perpetual futures. Tanpa perlu ketik USDT, sistem otomatis memasangkannya."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-xs font-medium text-text-secondary uppercase tracking-wide",children:"Ticker Koin"}),e.jsx("span",{className:"text-[11px] text-accent-blue font-medium",children:"Otomatis +USDT"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{type:"text",className:"input-field w-full font-mono uppercase pr-16",placeholder:"Contoh: BTC, ETH, SOL, PEPE",value:i,onChange:n=>{r(n.target.value.toUpperCase()),l(null)},onKeyDown:S,autoFocus:!0}),e.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none",children:e.jsx("span",{className:"text-[11px] font-mono font-semibold text-text-secondary/70 bg-bg-card px-1.5 py-0.5 rounded border border-border/50",children:"USDT"})})]}),e.jsx(u,{variant:"ghost",size:"md",onClick:h,loading:y,disabled:!i.trim(),icon:e.jsx(U,{size:14}),children:"Cek Pair"})]}),i.trim()&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary pt-0.5",children:[e.jsx("span",{children:"Target Pair:"}),e.jsx("span",{className:"font-mono font-bold text-accent-blue bg-accent-blue/10 px-1.5 py-0.5 rounded border border-accent-blue/20",children:p(i)}),e.jsxs("span",{className:"text-[11px] text-text-secondary/80",children:["(",B(p(i)),")"]})]})]}),s&&e.jsxs("div",{className:"space-y-2 animate-fade-in pt-1",children:[e.jsxs("div",{className:"flex items-center justify-between pb-1.5 border-b border-border/50 text-xs",children:[e.jsx("span",{className:"text-text-secondary",children:"Pair Terkonfirmasi:"}),e.jsx("span",{className:"font-mono font-bold text-emerald-400",children:s.symbol})]}),e.jsx("p",{className:"text-xs font-medium text-text-secondary uppercase tracking-wide",children:"Ketersediaan Bursa"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(o,{label:"Binance",found:s.on_binance}),e.jsx(o,{label:"Bybit",found:s.on_bybit}),s.on_okx!==void 0&&e.jsx(o,{label:"OKX",found:s.on_okx}),s.on_bitget!==void 0&&e.jsx(o,{label:"Bitget",found:s.on_bitget}),s.on_hyperliquid!==void 0&&e.jsx(o,{label:"Hyperliquid",found:s.on_hyperliquid})]}),!x&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-signal-short-bg border border-signal-short/20",children:[e.jsx(g,{size:14,className:"text-signal-short shrink-0"}),e.jsx("p",{className:"text-xs text-text-secondary",children:s.message||"Symbol tidak ditemukan di bursa mana pun"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(u,{variant:"ghost",size:"md",onClick:c,children:"Batal"}),x&&s&&e.jsxs(u,{variant:"primary",size:"md",onClick:k,loading:v,children:["Tambah Pair (",s.symbol,")"]})]})]})})}export{K as AddPairModal};
frontend/dist/assets/GlobalAISettingsModal-BOzCh0qM.js ADDED
@@ -0,0 +1 @@
 
 
1
+ import{r as i,j as e}from"./vendor-query-BSPl6-aq.js";import{u as T,a as z,V as u,G as w,O as A,b as S,c as I,M as U,B as K}from"./index-CaCGPr1l.js";import{j as V,a1 as q,a2 as G,K as B,Q as $,O as Q,f as F}from"./vendor-icons-BBZkXbgm.js";import"./vendor-react-BnvheTds.js";function X({isOpen:g,onClose:h}){const{settings:r,updateSettings:O}=T(),[o,k]=i.useState(r.provider),[N,_]=i.useState(r.api_key),[d,l]=i.useState(r.model),[c,a]=i.useState(""),[s,b]=i.useState(!1),[v,f]=i.useState(r.base_url||""),[C,M]=i.useState(r.max_tokens),[y,L]=i.useState(!1),{toast:j}=z();i.useEffect(()=>{if(g){k(r.provider),_(r.api_key),l(r.model),f(r.base_url||""),M(r.max_tokens);const t=u.some(n=>n.id===r.model),x=w.some(n=>n.id===r.model),P=A.some(n=>n.id===r.model),D=S.some(n=>n.id===r.model),R=I.some(n=>n.id===r.model);r.provider==="vikey"&&!t||r.provider==="gemini"&&!x||r.provider==="openai"&&!P||r.provider==="openrouter"&&!D||r.provider==="groq"&&!R?(b(!0),a(r.model)):(b(!1),a(""))}},[g,r]);const p=t=>{k(t),b(!1),a(""),t==="vikey"?l("anthropic/claude-fable-5"):t==="gemini"?l("gemini-2.5-flash"):t==="openai"?l("gpt-4o-mini"):t==="openrouter"?l("openai/gpt-4o-mini"):t==="groq"?l("llama-3.3-70b-versatile"):t==="custom"&&(l("anthropic/claude-fable-5"),v||f("https://api.vikey.ai/v1"))},m=t=>{t==="__custom__"?(b(!0),a(d||"")):(b(!1),l(t))},E=()=>{const t=N.trim();if(!t){j("Masukkan API Key terlebih dahulu","error");return}const x=s?c.trim():d.trim();if(!x){j("Tentukan model AI yang ingin digunakan","error");return}O({provider:o,api_key:t,model:x,base_url:o==="custom"?v.trim():void 0,max_tokens:C}),j("Pengaturan AI Universal berhasil disimpan!","success"),h()};return e.jsx(U,{isOpen:g,onClose:h,title:"Pengaturan AI Universal",size:"md",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-purple-500/10 border border-purple-500/20 text-xs text-purple-200 flex items-start gap-2.5",children:[e.jsx(V,{size:16,className:"text-purple-400 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-purple-100 block mb-0.5",children:"1x Setting untuk Semua Pair"}),"Kunci API dan model AI yang Anda simpan di sini akan berlaku secara universal untuk seluruh pair trading di dashboard. Tidak perlu mengisi ulang di setiap pair."]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-text-secondary uppercase tracking-wider mb-1.5",children:"AI Provider"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>p("vikey"),className:`p-2.5 rounded-lg border text-left transition-all ${o==="vikey"?"bg-purple-600/20 border-purple-500 text-purple-200 shadow-sm":"bg-bg-elevated/40 border-border hover:border-border-hover text-text-secondary"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-1",children:[e.jsx("span",{className:"text-xs font-bold text-text-primary",children:"Vikey AI"}),e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-purple-500/30 text-purple-300 font-mono",children:"Rec"})]}),e.jsx("span",{className:"text-[10px] text-text-muted block mt-0.5 truncate",children:"Claude, DeepSeek, GPT-5"})]}),e.jsxs("button",{type:"button",onClick:()=>p("gemini"),className:`p-2.5 rounded-lg border text-left transition-all ${o==="gemini"?"bg-accent-blue/20 border-accent-blue text-accent-blue shadow-sm":"bg-bg-elevated/40 border-border hover:border-border-hover text-text-secondary"}`,children:[e.jsx("span",{className:"text-xs font-bold text-text-primary block",children:"Google Gemini"}),e.jsx("span",{className:"text-[10px] text-text-muted block mt-0.5 truncate",children:"Gemini 2.5 Flash / Pro"})]}),e.jsxs("button",{type:"button",onClick:()=>p("openai"),className:`p-2.5 rounded-lg border text-left transition-all ${o==="openai"?"bg-signal-long/20 border-signal-long text-signal-long shadow-sm":"bg-bg-elevated/40 border-border hover:border-border-hover text-text-secondary"}`,children:[e.jsx("span",{className:"text-xs font-bold text-text-primary block",children:"OpenAI"}),e.jsx("span",{className:"text-[10px] text-text-muted block mt-0.5 truncate",children:"gpt-4o, o3-mini"})]}),e.jsxs("button",{type:"button",onClick:()=>p("openrouter"),className:`p-2.5 rounded-lg border text-left transition-all ${o==="openrouter"?"bg-cyan-500/20 border-cyan-500 text-cyan-300 shadow-sm":"bg-bg-elevated/40 border-border hover:border-border-hover text-text-secondary"}`,children:[e.jsx("span",{className:"text-xs font-bold text-text-primary block",children:"OpenRouter"}),e.jsx("span",{className:"text-[10px] text-text-muted block mt-0.5 truncate",children:"Multi-provider Router"})]}),e.jsxs("button",{type:"button",onClick:()=>p("groq"),className:`p-2.5 rounded-lg border text-left transition-all ${o==="groq"?"bg-orange-500/20 border-orange-500 text-orange-300 shadow-sm":"bg-bg-elevated/40 border-border hover:border-border-hover text-text-secondary"}`,children:[e.jsx("span",{className:"text-xs font-bold text-text-primary block",children:"Groq"}),e.jsx("span",{className:"text-[10px] text-text-muted block mt-0.5 truncate",children:"Ultra-fast Llama 3.3"})]}),e.jsxs("button",{type:"button",onClick:()=>p("custom"),className:`p-2.5 rounded-lg border text-left transition-all ${o==="custom"?"bg-amber-500/20 border-amber-500 text-amber-300 shadow-sm":"bg-bg-elevated/40 border-border hover:border-border-hover text-text-secondary"}`,children:[e.jsx("span",{className:"text-xs font-bold text-text-primary block",children:"Custom URL"}),e.jsx("span",{className:"text-[10px] text-text-muted block mt-0.5 truncate",children:"OpenAI-compatible"})]})]})]}),o==="custom"&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-text-secondary uppercase tracking-wider mb-1",children:"Custom Base URL"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-text-muted",children:e.jsx(q,{size:13})}),e.jsx("input",{type:"text",value:v,onChange:t=>f(t.target.value),placeholder:"https://api.vikey.ai/v1",className:"w-full pl-9 pr-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500 font-mono"})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-xs font-semibold text-text-secondary uppercase tracking-wider",children:o==="vikey"?"Vikey API Key":o==="gemini"?"Gemini API Key":"API Key (Bearer Token)"}),o==="vikey"&&e.jsxs("a",{href:"https://vikey.ai",target:"_blank",rel:"noreferrer",className:"text-[10px] text-purple-400 hover:text-purple-300 flex items-center gap-1",children:[e.jsx("span",{children:"Dashboard Vikey"}),e.jsx(G,{size:9})]}),o==="gemini"&&e.jsxs("a",{href:"https://aistudio.google.com/app/apikey",target:"_blank",rel:"noreferrer",className:"text-[10px] text-accent-blue hover:underline flex items-center gap-1",children:[e.jsx("span",{children:"Dapatkan Key Gratis"}),e.jsx(G,{size:9})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-text-muted",children:e.jsx(B,{size:13})}),e.jsx("input",{type:y?"text":"password",value:N,onChange:t=>_(t.target.value),placeholder:o==="vikey"?"Masukkan API key Vikey (contoh: vk-...)":o==="gemini"?"AIzaSy...":"sk-...",className:"w-full pl-9 pr-10 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500 font-mono"}),e.jsx("button",{type:"button",onClick:()=>L(!y),className:"absolute inset-y-0 right-0 pr-3 flex items-center text-text-muted hover:text-text-primary",children:y?e.jsx($,{size:13}):e.jsx(Q,{size:13})})]}),e.jsxs("span",{className:"text-[10px] text-text-muted block mt-1",children:["Tersimpan aman di ",e.jsx("code",{children:"localStorage"})," browser lokal Anda."]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-text-secondary uppercase tracking-wider mb-1",children:"Model AI"}),o==="vikey"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("select",{value:s?"__custom__":d,onChange:t=>m(t.target.value),className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary focus:outline-none focus:border-purple-500 font-mono",children:[e.jsx("optgroup",{label:"Anthropic (Claude)",children:u.filter(t=>t.category==="Anthropic").map(t=>e.jsxs("option",{value:t.id,children:[t.label," (",t.id,")"]},t.id))}),e.jsx("optgroup",{label:"DeepSeek",children:u.filter(t=>t.category==="DeepSeek").map(t=>e.jsxs("option",{value:t.id,children:[t.label," (",t.id,")"]},t.id))}),e.jsx("optgroup",{label:"OpenAI (GPT-5 / GPT-6)",children:u.filter(t=>t.category==="OpenAI").map(t=>e.jsxs("option",{value:t.id,children:[t.label," (",t.id,")"]},t.id))}),e.jsx("optgroup",{label:"Google (Gemini)",children:u.filter(t=>t.category==="Google").map(t=>e.jsxs("option",{value:t.id,children:[t.label," (",t.id,")"]},t.id))}),e.jsx("optgroup",{label:"Qwen & Lainnya",children:u.filter(t=>["Qwen","Moonshot","MiniMax","GLM"].includes(t.category)).map(t=>e.jsxs("option",{value:t.id,children:[t.label," (",t.id,")"]},t.id))}),e.jsx("option",{value:"__custom__",children:"✍️ Ketik Model Lain Manual (Custom Model)..."})]}),s&&e.jsxs("div",{className:"animate-fade-in space-y-1",children:[e.jsx("input",{type:"text",value:c,onChange:t=>a(t.target.value),placeholder:"Contoh: anthropic/claude-opus-4.7 atau moonshot/kimi-k2.7-code",className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-purple-500/50 text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-400 font-mono"}),e.jsx("span",{className:"text-[10px] text-purple-300 block",children:"Ketik string model persis seperti di daftar akun Vikey Anda."})]})]}),o==="gemini"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("select",{value:s?"__custom__":d,onChange:t=>m(t.target.value),className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary focus:outline-none focus:border-purple-500 font-mono",children:[w.map(t=>e.jsxs("option",{value:t.id,children:[t.label," (",t.id,")"]},t.id)),e.jsx("option",{value:"__custom__",children:"✍️ Ketik Model Gemini Lain..."})]}),s&&e.jsx("input",{type:"text",value:c,onChange:t=>a(t.target.value),placeholder:"Contoh: gemini-2.0-flash-thinking-exp",className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500 font-mono"})]}),o==="openai"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("select",{value:s?"__custom__":d,onChange:t=>m(t.target.value),className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary focus:outline-none focus:border-purple-500 font-mono",children:[A.map(t=>e.jsx("option",{value:t.id,children:t.label},t.id)),e.jsx("option",{value:"__custom__",children:"✍️ Ketik Model OpenAI Lain..."})]}),s&&e.jsx("input",{type:"text",value:c,onChange:t=>a(t.target.value),placeholder:"Contoh: gpt-4.5-preview",className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500 font-mono"})]}),o==="openrouter"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("select",{value:s?"__custom__":d,onChange:t=>m(t.target.value),className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary focus:outline-none focus:border-purple-500 font-mono",children:[S.map(t=>e.jsxs("option",{value:t.id,children:[t.label," (",t.id,")"]},t.id)),e.jsx("option",{value:"__custom__",children:"✍️ Ketik Model OpenRouter Lain..."})]}),s&&e.jsx("input",{type:"text",value:c,onChange:t=>a(t.target.value),placeholder:"Contoh: google/gemini-2.5-pro",className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500 font-mono"})]}),o==="groq"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("select",{value:s?"__custom__":d,onChange:t=>m(t.target.value),className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary focus:outline-none focus:border-purple-500 font-mono",children:[I.map(t=>e.jsxs("option",{value:t.id,children:[t.label," (",t.id,")"]},t.id)),e.jsx("option",{value:"__custom__",children:"✍️ Ketik Model Groq Lain..."})]}),s&&e.jsx("input",{type:"text",value:c,onChange:t=>a(t.target.value),placeholder:"Contoh: mixtral-8x7b-32768",className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500 font-mono"})]}),o==="custom"&&e.jsx("input",{type:"text",value:s?c:d,onChange:t=>{l(t.target.value),a(t.target.value)},placeholder:"Contoh: anthropic/claude-3.5-sonnet",className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500 font-mono"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-xs font-semibold text-text-secondary uppercase tracking-wider",children:"Token Budget (Reasoning + Jawaban)"}),e.jsx("span",{className:"text-[10px] text-purple-300 font-mono",children:"Auto Default: 8,192"})]}),e.jsxs("select",{value:C||0,onChange:t=>{const x=parseInt(t.target.value,10);M(x>0?x:void 0)},className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary focus:outline-none focus:border-purple-500 font-mono",children:[e.jsx("option",{value:0,children:"⚡ Auto (8,192 - 10,240 tokens, Sangat Disarankan)"}),e.jsx("option",{value:8192,children:"8,192 tokens (Standar Cepat & Lega)"}),e.jsx("option",{value:12288,children:"12,288 tokens (Model Deep-Thinking)"}),e.jsx("option",{value:16384,children:"16,384 tokens (Maksimal Tanpa Batas)"})]}),e.jsx("span",{className:"text-[10px] text-text-muted block mt-1",children:'💡 Model reasoning (seperti Claude Fable/Sonnet, DeepSeek R1/V4) membutuhkan token untuk proses berpikir dalam hati. Jatah token lega mencegah error 502 "spent entire max_tokens".'})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2 border-t border-border",children:[e.jsx(K,{variant:"ghost",size:"sm",onClick:h,children:"Batal"}),e.jsx(K,{variant:"primary",size:"sm",onClick:E,icon:e.jsx(F,{size:14}),className:"bg-purple-600 hover:bg-purple-500 text-white",children:"Simpan Pengaturan"})]})]})})}export{X as GlobalAISettingsModal};
frontend/dist/assets/GlobalAISettingsModal-y_W5Q-P7.js DELETED
@@ -1 +0,0 @@
1
- import{r,j as e}from"./vendor-query-BSPl6-aq.js";import{u as L,a as O,V as c,G as M,O as w,M as T,B as S}from"./index-FYyQL2Qc.js";import{j as z,a1 as D,a2 as I,K as V,Q as B,O as R,f as U}from"./vendor-icons-BBZkXbgm.js";import"./vendor-react-BnvheTds.js";function Y({isOpen:b,onClose:h}){const{settings:s,updateSettings:K}=L(),[a,j]=r.useState(s.provider),[N,_]=r.useState(s.api_key),[d,n]=r.useState(s.model),[p,o]=r.useState(""),[l,x]=r.useState(!1),[g,f]=r.useState(s.base_url||""),[A,C]=r.useState(s.max_tokens),[v,G]=r.useState(!1),{toast:y}=O();r.useEffect(()=>{if(b){j(s.provider),_(s.api_key),n(s.model),f(s.base_url||""),C(s.max_tokens);const t=c.some(u=>u.id===s.model),i=M.some(u=>u.id===s.model),E=w.some(u=>u.id===s.model);s.provider==="vikey"&&!t||s.provider==="gemini"&&!i||s.provider==="openai"&&!E?(x(!0),o(s.model)):(x(!1),o(""))}},[b,s]);const m=t=>{j(t),x(!1),o(""),t==="vikey"?n("anthropic/claude-fable-5"):t==="gemini"?n("gemini-2.5-flash"):t==="openai"?n("gpt-4o-mini"):t==="custom"&&(n("anthropic/claude-fable-5"),g||f("https://api.vikey.ai/v1"))},k=t=>{t==="__custom__"?(x(!0),o(d||"")):(x(!1),n(t))},P=()=>{const t=N.trim();if(!t){y("Masukkan API Key terlebih dahulu","error");return}const i=l?p.trim():d.trim();if(!i){y("Tentukan model AI yang ingin digunakan","error");return}K({provider:a,api_key:t,model:i,base_url:a==="custom"?g.trim():void 0,max_tokens:A}),y("Pengaturan AI Universal berhasil disimpan!","success"),h()};return e.jsx(T,{isOpen:b,onClose:h,title:"Pengaturan AI Universal",size:"md",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-purple-500/10 border border-purple-500/20 text-xs text-purple-200 flex items-start gap-2.5",children:[e.jsx(z,{size:16,className:"text-purple-400 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-purple-100 block mb-0.5",children:"1x Setting untuk Semua Pair"}),"Kunci API dan model AI yang Anda simpan di sini akan berlaku secara universal untuk seluruh pair trading di dashboard. Tidak perlu mengisi ulang di setiap pair."]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-text-secondary uppercase tracking-wider mb-1.5",children:"AI Provider"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>m("vikey"),className:`p-2.5 rounded-lg border text-left transition-all ${a==="vikey"?"bg-purple-600/20 border-purple-500 text-purple-200 shadow-sm":"bg-bg-elevated/40 border-border hover:border-border-hover text-text-secondary"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-bold text-text-primary",children:"Vikey AI"}),e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-purple-500/30 text-purple-300 font-mono",children:"Recommended"})]}),e.jsx("span",{className:"text-[10px] text-text-muted block mt-0.5",children:"api.vikey.ai (Claude, DeepSeek, GPT-5/6)"})]}),e.jsxs("button",{type:"button",onClick:()=>m("gemini"),className:`p-2.5 rounded-lg border text-left transition-all ${a==="gemini"?"bg-accent-blue/20 border-accent-blue text-accent-blue shadow-sm":"bg-bg-elevated/40 border-border hover:border-border-hover text-text-secondary"}`,children:[e.jsx("span",{className:"text-xs font-bold text-text-primary block",children:"Google Gemini"}),e.jsx("span",{className:"text-[10px] text-text-muted block mt-0.5",children:"Gemini 2.5 Flash / 1.5 Pro"})]}),e.jsxs("button",{type:"button",onClick:()=>m("openai"),className:`p-2.5 rounded-lg border text-left transition-all ${a==="openai"?"bg-signal-long/20 border-signal-long text-signal-long shadow-sm":"bg-bg-elevated/40 border-border hover:border-border-hover text-text-secondary"}`,children:[e.jsx("span",{className:"text-xs font-bold text-text-primary block",children:"OpenAI"}),e.jsx("span",{className:"text-[10px] text-text-muted block mt-0.5",children:"Official API (gpt-4o, o3-mini)"})]}),e.jsxs("button",{type:"button",onClick:()=>m("custom"),className:`p-2.5 rounded-lg border text-left transition-all ${a==="custom"?"bg-amber-500/20 border-amber-500 text-amber-300 shadow-sm":"bg-bg-elevated/40 border-border hover:border-border-hover text-text-secondary"}`,children:[e.jsx("span",{className:"text-xs font-bold text-text-primary block",children:"Custom Endpoint"}),e.jsx("span",{className:"text-[10px] text-text-muted block mt-0.5",children:"OpenRouter / Proxy Lain"})]})]})]}),a==="custom"&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-text-secondary uppercase tracking-wider mb-1",children:"Custom Base URL"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-text-muted",children:e.jsx(D,{size:13})}),e.jsx("input",{type:"text",value:g,onChange:t=>f(t.target.value),placeholder:"https://api.vikey.ai/v1",className:"w-full pl-9 pr-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500 font-mono"})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-xs font-semibold text-text-secondary uppercase tracking-wider",children:a==="vikey"?"Vikey API Key":a==="gemini"?"Gemini API Key":"API Key (Bearer Token)"}),a==="vikey"&&e.jsxs("a",{href:"https://vikey.ai",target:"_blank",rel:"noreferrer",className:"text-[10px] text-purple-400 hover:text-purple-300 flex items-center gap-1",children:[e.jsx("span",{children:"Dashboard Vikey"}),e.jsx(I,{size:9})]}),a==="gemini"&&e.jsxs("a",{href:"https://aistudio.google.com/app/apikey",target:"_blank",rel:"noreferrer",className:"text-[10px] text-accent-blue hover:underline flex items-center gap-1",children:[e.jsx("span",{children:"Dapatkan Key Gratis"}),e.jsx(I,{size:9})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-text-muted",children:e.jsx(V,{size:13})}),e.jsx("input",{type:v?"text":"password",value:N,onChange:t=>_(t.target.value),placeholder:a==="vikey"?"Masukkan API key Vikey (contoh: vk-...)":a==="gemini"?"AIzaSy...":"sk-...",className:"w-full pl-9 pr-10 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500 font-mono"}),e.jsx("button",{type:"button",onClick:()=>G(!v),className:"absolute inset-y-0 right-0 pr-3 flex items-center text-text-muted hover:text-text-primary",children:v?e.jsx(B,{size:13}):e.jsx(R,{size:13})})]}),e.jsxs("span",{className:"text-[10px] text-text-muted block mt-1",children:["Tersimpan aman di ",e.jsx("code",{children:"localStorage"})," browser lokal Anda."]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-text-secondary uppercase tracking-wider mb-1",children:"Model AI"}),a==="vikey"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("select",{value:l?"__custom__":d,onChange:t=>k(t.target.value),className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary focus:outline-none focus:border-purple-500 font-mono",children:[e.jsx("optgroup",{label:"Anthropic (Claude)",children:c.filter(t=>t.category==="Anthropic").map(t=>e.jsxs("option",{value:t.id,children:[t.label," (",t.id,")"]},t.id))}),e.jsx("optgroup",{label:"DeepSeek",children:c.filter(t=>t.category==="DeepSeek").map(t=>e.jsxs("option",{value:t.id,children:[t.label," (",t.id,")"]},t.id))}),e.jsx("optgroup",{label:"OpenAI (GPT-5 / GPT-6)",children:c.filter(t=>t.category==="OpenAI").map(t=>e.jsxs("option",{value:t.id,children:[t.label," (",t.id,")"]},t.id))}),e.jsx("optgroup",{label:"Google (Gemini)",children:c.filter(t=>t.category==="Google").map(t=>e.jsxs("option",{value:t.id,children:[t.label," (",t.id,")"]},t.id))}),e.jsx("optgroup",{label:"Qwen & Lainnya",children:c.filter(t=>["Qwen","Moonshot","MiniMax","GLM"].includes(t.category)).map(t=>e.jsxs("option",{value:t.id,children:[t.label," (",t.id,")"]},t.id))}),e.jsx("option",{value:"__custom__",children:"✍️ Ketik Model Lain Manual (Custom Model)..."})]}),l&&e.jsxs("div",{className:"animate-fade-in space-y-1",children:[e.jsx("input",{type:"text",value:p,onChange:t=>o(t.target.value),placeholder:"Contoh: anthropic/claude-opus-4.7 atau moonshot/kimi-k2.7-code",className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-purple-500/50 text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-400 font-mono"}),e.jsx("span",{className:"text-[10px] text-purple-300 block",children:"Ketik string model persis seperti di daftar akun Vikey Anda."})]})]}),a==="gemini"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("select",{value:l?"__custom__":d,onChange:t=>k(t.target.value),className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary focus:outline-none focus:border-purple-500 font-mono",children:[M.map(t=>e.jsxs("option",{value:t.id,children:[t.label," (",t.id,")"]},t.id)),e.jsx("option",{value:"__custom__",children:"✍️ Ketik Model Gemini Lain..."})]}),l&&e.jsx("input",{type:"text",value:p,onChange:t=>o(t.target.value),placeholder:"Contoh: gemini-2.0-flash-thinking-exp",className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500 font-mono"})]}),a==="openai"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("select",{value:l?"__custom__":d,onChange:t=>k(t.target.value),className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary focus:outline-none focus:border-purple-500 font-mono",children:[w.map(t=>e.jsx("option",{value:t.id,children:t.label},t.id)),e.jsx("option",{value:"__custom__",children:"✍️ Ketik Model OpenAI Lain..."})]}),l&&e.jsx("input",{type:"text",value:p,onChange:t=>o(t.target.value),placeholder:"Contoh: gpt-4.5-preview",className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500 font-mono"})]}),a==="custom"&&e.jsx("input",{type:"text",value:l?p:d,onChange:t=>{n(t.target.value),o(t.target.value)},placeholder:"Contoh: anthropic/claude-3.5-sonnet",className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:border-purple-500 font-mono"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-xs font-semibold text-text-secondary uppercase tracking-wider",children:"Token Budget (Reasoning + Jawaban)"}),e.jsx("span",{className:"text-[10px] text-purple-300 font-mono",children:"Auto Default: 8,192"})]}),e.jsxs("select",{value:A||0,onChange:t=>{const i=parseInt(t.target.value,10);C(i>0?i:void 0)},className:"w-full px-3 py-2 rounded-lg bg-bg-elevated border border-border text-xs text-text-primary focus:outline-none focus:border-purple-500 font-mono",children:[e.jsx("option",{value:0,children:"⚡ Auto (8,192 - 10,240 tokens, Sangat Disarankan)"}),e.jsx("option",{value:8192,children:"8,192 tokens (Standar Cepat & Lega)"}),e.jsx("option",{value:12288,children:"12,288 tokens (Model Deep-Thinking)"}),e.jsx("option",{value:16384,children:"16,384 tokens (Maksimal Tanpa Batas)"})]}),e.jsx("span",{className:"text-[10px] text-text-muted block mt-1",children:'💡 Model reasoning (seperti Claude Fable/Sonnet, DeepSeek R1/V4) membutuhkan token untuk proses berpikir dalam hati. Jatah token lega mencegah error 502 "spent entire max_tokens".'})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2 border-t border-border",children:[e.jsx(S,{variant:"ghost",size:"sm",onClick:h,children:"Batal"}),e.jsx(S,{variant:"primary",size:"sm",onClick:P,icon:e.jsx(U,{size:14}),className:"bg-purple-600 hover:bg-purple-500 text-white",children:"Simpan Pengaturan"})]})]})})}export{Y as GlobalAISettingsModal};
 
 
frontend/dist/assets/ServerSettingsModal-B2vOj2j4.js ADDED
@@ -0,0 +1 @@
 
 
1
+ import{a as E,r as n,j as e}from"./vendor-query-BSPl6-aq.js";import{a as C,g as R,f as z,M as w,B as k,h as o,s as I,i as U,D as _}from"./index-CaCGPr1l.js";import{a4 as B,Q as $,O as K,a1 as O,a5 as L,f as M,C as W,R as D,a0 as F}from"./vendor-icons-BBZkXbgm.js";import"./vendor-react-BnvheTds.js";function q({isOpen:c,onClose:d}){const T=E(),[u,x]=n.useState(""),[m,f]=n.useState(""),[p,v]=n.useState(!1),[h,j]=n.useState(!1),[l,t]=n.useState(null),{toast:S}=C();n.useEffect(()=>{c&&(x(R()),f(z()),v(!1),t(null))},[c]);const y=async s=>{const a=(s??u).trim().replace(/\/+$/,""),P=m.trim();j(!0),t(null);try{const i=a?`${a}/health`:"/health",g=await o.get(i,{timeout:5e3});if(g.status!==200){t({ok:!1,message:`Server merespons kode status: ${g.status}`});return}try{const r=a?`${a}/api/auth/status`:"/api/auth/status";if((await o.get(r,{timeout:5e3})).data?.auth_configured===!1){t({ok:!1,message:"Server online, tetapi PERPS_API_TOKEN belum diset di backend (route terlindungi akan fail-closed 503)."});return}}catch{}if(P)try{const r=a?`${a}/api/auth/verify`:"/api/auth/verify";await o.post(r,null,{timeout:5e3,headers:{Authorization:`Bearer ${P}`}}),t({ok:!0,message:"Terhubung & Terautentikasi! Backend online dan API Token valid."});return}catch(r){const b=r?.response?.status;t({ok:!1,message:b===401?"Server online, tetapi API Token salah / tidak cocok (401 Unauthorized).":b===503?"Server online, namun PERPS_API_TOKEN belum dikonfigurasi di backend (503).":`Server online, verifikasi token gagal: ${r.message}`});return}t({ok:!0,message:"Server online! Masukkan API Bearer Token agar fitur Pairs, Jurnal, dan Eksekusi aktif."})}catch(i){if(a)try{if((await o.get(a,{timeout:5e3})).status===200){t({ok:!0,message:"Terhubung ke server!"});return}}catch{}t({ok:!1,message:i.message?.includes("Network Error")?"Gagal terhubung. Pastikan backend aktif dan URL dapat diakses.":`Koneksi gagal: ${i.message}`})}finally{j(!1)}},A=()=>{const s=u.trim().replace(/\/+$/,"");I(s),U(m),T.invalidateQueries(),S("Pengaturan server & API token berhasil disimpan","success"),d()},N=s=>{x(s),t(null),y(s)};return e.jsx(w,{isOpen:c,onClose:d,title:"Pengaturan Server Backend",size:"md",children:e.jsxs("div",{className:"space-y-4 text-xs sm:text-sm",children:[e.jsx("p",{className:"text-text-secondary leading-relaxed text-xs",children:"Aplikasi APK dapat terhubung ke server cloud 24/7 (gratis) ataupun server lokal (seperti Termux di HP atau PC melalui Wi-Fi)."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"block text-xs font-semibold text-text-primary",children:"Backend API / WebSocket URL"}),e.jsx("div",{className:"relative",children:e.jsx("input",{type:"text",value:u,onChange:s=>{x(s.target.value),t(null)},placeholder:"https://... atau http://127.0.0.1:8000",className:"w-full bg-bg-elevated border border-border rounded-lg px-3 py-2 text-xs font-mono text-text-primary focus:outline-none focus:border-accent-blue focus:ring-1 focus:ring-accent-blue"})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs font-semibold text-text-primary",children:[e.jsx(B,{size:13,className:"text-amber-400"}),e.jsx("span",{children:"API Bearer Token (PERPS_API_TOKEN)"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:p?"text":"password",value:m,onChange:s=>{f(s.target.value),t(null)},placeholder:"Tempel PERPS_API_TOKEN dari server backend",className:"w-full bg-bg-elevated border border-border rounded-lg pl-3 pr-9 py-2 text-xs font-mono text-text-primary focus:outline-none focus:border-amber-400 focus:ring-1 focus:ring-amber-400"}),e.jsx("button",{type:"button",onClick:()=>v(s=>!s),className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary",title:p?"Sembunyikan token":"Tampilkan token",children:p?e.jsx($,{size:14}):e.jsx(K,{size:14})})]}),e.jsx("p",{className:"text-[11px] text-text-muted",children:"Wajib untuk operasi Pair Watchlist, Jurnal Trade, dan Eksekusi Order Bybit. Disimpan lokal di perangkat Anda."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("span",{className:"text-[11px] font-medium text-text-muted block",children:"Pilihan Preset Cepat:"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>N(_),className:"flex items-center gap-2 p-2 rounded-lg border border-border/80 bg-bg-elevated/60 hover:bg-bg-elevated hover:border-purple-500/50 text-left transition-all group",children:[e.jsx(O,{size:14,className:"text-purple-400 group-hover:scale-110 transition-transform shrink-0"}),e.jsxs("div",{className:"overflow-hidden",children:[e.jsx("span",{className:"font-semibold text-text-primary text-[11px] block",children:"Cloud 24/7 (Hugging Face)"}),e.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:"Online gratis nonstop"})]})]}),e.jsxs("button",{type:"button",onClick:()=>N("http://127.0.0.1:8000"),className:"flex items-center gap-2 p-2 rounded-lg border border-border/80 bg-bg-elevated/60 hover:bg-bg-elevated hover:border-emerald-500/50 text-left transition-all group",children:[e.jsx(L,{size:14,className:"text-emerald-400 group-hover:scale-110 transition-transform shrink-0"}),e.jsxs("div",{className:"overflow-hidden",children:[e.jsx("span",{className:"font-semibold text-text-primary text-[11px] block",children:"Lokal HP (Termux)"}),e.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:"http://127.0.0.1:8000"})]})]})]})]}),l&&e.jsxs("div",{className:`p-3 rounded-lg border flex items-start gap-2.5 ${l.ok?"bg-emerald-500/10 border-emerald-500/30 text-emerald-300":"bg-red-500/10 border-red-500/30 text-red-300"}`,children:[l.ok?e.jsx(M,{size:16,className:"text-emerald-400 shrink-0 mt-0.5"}):e.jsx(W,{size:16,className:"text-red-400 shrink-0 mt-0.5"}),e.jsx("div",{className:"text-xs",children:l.message})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-border",children:[e.jsxs(k,{type:"button",variant:"ghost",size:"sm",onClick:()=>y(),disabled:h,className:"text-xs flex items-center gap-1.5",children:[h?e.jsx(D,{size:13,className:"animate-spin"}):e.jsx(F,{size:13}),e.jsx("span",{children:h?"Menguji...":"Uji Koneksi"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(k,{type:"button",variant:"ghost",size:"sm",onClick:d,className:"text-xs",children:"Batal"}),e.jsx(k,{type:"button",variant:"primary",size:"sm",onClick:A,className:"text-xs bg-accent-blue hover:bg-accent-blue/90",children:"Simpan & Terapkan"})]})]})]})})}export{q as ServerSettingsModal};
frontend/dist/assets/ServerSettingsModal-BJC6WDDG.js DELETED
@@ -1 +0,0 @@
1
- import{a as C,r as n,j as e}from"./vendor-query-BSPl6-aq.js";import{a as R,D as T,g as z,d as w,M as I,B as k,e as o,s as U,f as _}from"./index-FYyQL2Qc.js";import{a4 as B,Q as $,O as K,a1 as O,a5 as L,f as M,C as W,R as D,a0 as F}from"./vendor-icons-BBZkXbgm.js";import"./vendor-react-BnvheTds.js";function q({isOpen:c,onClose:d}){const S=C(),[u,x]=n.useState(""),[m,f]=n.useState(""),[p,v]=n.useState(!1),[h,j]=n.useState(!1),[l,t]=n.useState(null),{toast:A}=R();n.useEffect(()=>{c&&(x(z()||T),f(w()),v(!1),t(null))},[c]);const y=async s=>{const a=(s||u).trim().replace(/\/+$/,""),P=m.trim();j(!0),t(null);try{const i=a?`${a}/health`:"/health",g=await o.get(i,{timeout:5e3});if(g.status!==200){t({ok:!1,message:`Server merespons kode status: ${g.status}`});return}try{const r=a?`${a}/api/auth/status`:"/api/auth/status";if((await o.get(r,{timeout:5e3})).data?.auth_configured===!1){t({ok:!1,message:"Server online, tetapi PERPS_API_TOKEN belum diset di backend (route terlindungi akan fail-closed 503)."});return}}catch{}if(P)try{const r=a?`${a}/api/auth/verify`:"/api/auth/verify";await o.post(r,null,{timeout:5e3,headers:{Authorization:`Bearer ${P}`}}),t({ok:!0,message:"Terhubung & Terautentikasi! Backend online dan API Token valid."});return}catch(r){const b=r?.response?.status;t({ok:!1,message:b===401?"Server online, tetapi API Token salah / tidak cocok (401 Unauthorized).":b===503?"Server online, namun PERPS_API_TOKEN belum dikonfigurasi di backend (503).":`Server online, verifikasi token gagal: ${r.message}`});return}t({ok:!0,message:"Server online! Masukkan API Bearer Token agar fitur Pairs, Jurnal, dan Eksekusi aktif."})}catch(i){if(a)try{if((await o.get(a,{timeout:5e3})).status===200){t({ok:!0,message:"Terhubung ke server!"});return}}catch{}t({ok:!1,message:i.message?.includes("Network Error")?"Gagal terhubung. Pastikan backend aktif dan URL dapat diakses.":`Koneksi gagal: ${i.message}`})}finally{j(!1)}},E=()=>{const s=u.trim().replace(/\/+$/,"");U(s),_(m),S.invalidateQueries(),A("Pengaturan server & API token berhasil disimpan","success"),d()},N=s=>{x(s),t(null),y(s)};return e.jsx(I,{isOpen:c,onClose:d,title:"Pengaturan Server Backend",size:"md",children:e.jsxs("div",{className:"space-y-4 text-xs sm:text-sm",children:[e.jsx("p",{className:"text-text-secondary leading-relaxed text-xs",children:"Aplikasi APK dapat terhubung ke server cloud 24/7 (gratis) ataupun server lokal (seperti Termux di HP atau PC melalui Wi-Fi)."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"block text-xs font-semibold text-text-primary",children:"Backend API / WebSocket URL"}),e.jsx("div",{className:"relative",children:e.jsx("input",{type:"text",value:u,onChange:s=>{x(s.target.value),t(null)},placeholder:"https://... atau http://127.0.0.1:8000",className:"w-full bg-bg-elevated border border-border rounded-lg px-3 py-2 text-xs font-mono text-text-primary focus:outline-none focus:border-accent-blue focus:ring-1 focus:ring-accent-blue"})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs font-semibold text-text-primary",children:[e.jsx(B,{size:13,className:"text-amber-400"}),e.jsx("span",{children:"API Bearer Token (PERPS_API_TOKEN)"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:p?"text":"password",value:m,onChange:s=>{f(s.target.value),t(null)},placeholder:"Tempel PERPS_API_TOKEN dari server backend",className:"w-full bg-bg-elevated border border-border rounded-lg pl-3 pr-9 py-2 text-xs font-mono text-text-primary focus:outline-none focus:border-amber-400 focus:ring-1 focus:ring-amber-400"}),e.jsx("button",{type:"button",onClick:()=>v(s=>!s),className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary",title:p?"Sembunyikan token":"Tampilkan token",children:p?e.jsx($,{size:14}):e.jsx(K,{size:14})})]}),e.jsx("p",{className:"text-[11px] text-text-muted",children:"Wajib untuk operasi Pair Watchlist, Jurnal Trade, dan Eksekusi Order Bybit. Disimpan lokal di perangkat Anda."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("span",{className:"text-[11px] font-medium text-text-muted block",children:"Pilihan Preset Cepat:"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>N(T),className:"flex items-center gap-2 p-2 rounded-lg border border-border/80 bg-bg-elevated/60 hover:bg-bg-elevated hover:border-purple-500/50 text-left transition-all group",children:[e.jsx(O,{size:14,className:"text-purple-400 group-hover:scale-110 transition-transform shrink-0"}),e.jsxs("div",{className:"overflow-hidden",children:[e.jsx("span",{className:"font-semibold text-text-primary text-[11px] block",children:"Cloud 24/7 (Hugging Face)"}),e.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:"Online gratis nonstop"})]})]}),e.jsxs("button",{type:"button",onClick:()=>N("http://127.0.0.1:8000"),className:"flex items-center gap-2 p-2 rounded-lg border border-border/80 bg-bg-elevated/60 hover:bg-bg-elevated hover:border-emerald-500/50 text-left transition-all group",children:[e.jsx(L,{size:14,className:"text-emerald-400 group-hover:scale-110 transition-transform shrink-0"}),e.jsxs("div",{className:"overflow-hidden",children:[e.jsx("span",{className:"font-semibold text-text-primary text-[11px] block",children:"Lokal HP (Termux)"}),e.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:"http://127.0.0.1:8000"})]})]})]})]}),l&&e.jsxs("div",{className:`p-3 rounded-lg border flex items-start gap-2.5 ${l.ok?"bg-emerald-500/10 border-emerald-500/30 text-emerald-300":"bg-red-500/10 border-red-500/30 text-red-300"}`,children:[l.ok?e.jsx(M,{size:16,className:"text-emerald-400 shrink-0 mt-0.5"}):e.jsx(W,{size:16,className:"text-red-400 shrink-0 mt-0.5"}),e.jsx("div",{className:"text-xs",children:l.message})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-border",children:[e.jsxs(k,{type:"button",variant:"ghost",size:"sm",onClick:()=>y(),disabled:h,className:"text-xs flex items-center gap-1.5",children:[h?e.jsx(D,{size:13,className:"animate-spin"}):e.jsx(F,{size:13}),e.jsx("span",{children:h?"Menguji...":"Uji Koneksi"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(k,{type:"button",variant:"ghost",size:"sm",onClick:d,className:"text-xs",children:"Batal"}),e.jsx(k,{type:"button",variant:"primary",size:"sm",onClick:E,className:"text-xs bg-accent-blue hover:bg-accent-blue/90",children:"Simpan & Terapkan"})]})]})]})})}export{q as ServerSettingsModal};
 
 
frontend/dist/assets/{index-FYyQL2Qc.js → index-CaCGPr1l.js} RENAMED
The diff for this file is too large to render. See raw diff
 
frontend/dist/assets/{index--kfpEFWJ.css → index-DaWuxWbx.css} RENAMED
The diff for this file is too large to render. See raw diff
 
frontend/dist/index.html CHANGED
@@ -14,11 +14,11 @@
14
  <link rel="preconnect" href="https://fonts.googleapis.com" />
15
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
16
  <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />
17
- <script type="module" crossorigin src="/assets/index-FYyQL2Qc.js"></script>
18
  <link rel="modulepreload" crossorigin href="/assets/vendor-query-BSPl6-aq.js">
19
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-BnvheTds.js">
20
  <link rel="modulepreload" crossorigin href="/assets/vendor-icons-BBZkXbgm.js">
21
- <link rel="stylesheet" crossorigin href="/assets/index--kfpEFWJ.css">
22
  </head>
23
  <body>
24
  <div id="root"></div>
 
14
  <link rel="preconnect" href="https://fonts.googleapis.com" />
15
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
16
  <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />
17
+ <script type="module" crossorigin src="/assets/index-CaCGPr1l.js"></script>
18
  <link rel="modulepreload" crossorigin href="/assets/vendor-query-BSPl6-aq.js">
19
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-BnvheTds.js">
20
  <link rel="modulepreload" crossorigin href="/assets/vendor-icons-BBZkXbgm.js">
21
+ <link rel="stylesheet" crossorigin href="/assets/index-DaWuxWbx.css">
22
  </head>
23
  <body>
24
  <div id="root"></div>
frontend/src/App.tsx CHANGED
@@ -78,6 +78,7 @@ function MainApp() {
78
  <div className={activeTab === 'chart' ? 'flex flex-1 overflow-hidden' : 'hidden'}>
79
  <LiveChartTerminal
80
  initialSymbol={chartSelectedSymbol}
 
81
  onNavigateToAI={handleNavigateToAI}
82
  />
83
  </div>
 
78
  <div className={activeTab === 'chart' ? 'flex flex-1 overflow-hidden' : 'hidden'}>
79
  <LiveChartTerminal
80
  initialSymbol={chartSelectedSymbol}
81
+ onSelectSymbol={setChartSelectedSymbol}
82
  onNavigateToAI={handleNavigateToAI}
83
  />
84
  </div>
frontend/src/api/client.ts CHANGED
@@ -79,10 +79,7 @@ export const apiClient = axios.create({
79
  });
80
 
81
  apiClient.interceptors.request.use((reqConfig) => {
82
- const currentBase = getServerUrl();
83
- if (currentBase) {
84
- reqConfig.baseURL = currentBase;
85
- }
86
  const token = getApiToken();
87
  if (token) {
88
  reqConfig.headers.set('Authorization', `Bearer ${token}`);
@@ -129,7 +126,7 @@ export function resolveWsUrl(): string | null {
129
  }
130
 
131
  export function resolveChartWsUrl(symbol: string): string | null {
132
- const cleanSym = symbol.toUpperCase().replace('/', '').replace('-', '');
133
  if (import.meta.env.VITE_WS_URL) {
134
  return `${import.meta.env.VITE_WS_URL.replace('/ws/signals', '')}/ws/chart/${cleanSym}`;
135
  }
 
79
  });
80
 
81
  apiClient.interceptors.request.use((reqConfig) => {
82
+ reqConfig.baseURL = getServerUrl();
 
 
 
83
  const token = getApiToken();
84
  if (token) {
85
  reqConfig.headers.set('Authorization', `Bearer ${token}`);
 
126
  }
127
 
128
  export function resolveChartWsUrl(symbol: string): string | null {
129
+ const cleanSym = symbol.toUpperCase().replace(/[/-]/g, '');
130
  if (import.meta.env.VITE_WS_URL) {
131
  return `${import.meta.env.VITE_WS_URL.replace('/ws/signals', '')}/ws/chart/${cleanSym}`;
132
  }
frontend/src/components/chart/AggregatedOIChart.tsx CHANGED
@@ -101,6 +101,8 @@ export function AggregatedOIChart({
101
  chart.remove();
102
  chartRef.current = null;
103
  oiSeriesRef.current = null;
 
 
104
  };
105
  }, [height]);
106
 
@@ -117,7 +119,15 @@ export function AggregatedOIChart({
117
  }, [symbol]);
118
 
119
  useEffect(() => {
120
- if (!oiSeriesRef.current || !candles || candles.length === 0) {
 
 
 
 
 
 
 
 
121
  return;
122
  }
123
 
@@ -138,7 +148,14 @@ export function AggregatedOIChart({
138
  value: c.open_interest as number,
139
  }));
140
 
141
- if (oiData.length === 0) return;
 
 
 
 
 
 
 
142
 
143
  const firstTime = oiData[0].time;
144
  const isFirstTimeChanged = prevFirstTimeRef.current !== firstTime;
@@ -165,7 +182,7 @@ export function AggregatedOIChart({
165
  // ignore
166
  }
167
  }
168
- }, [candles, symbol]);
169
 
170
  // Summary statistics
171
  const oiValues = candles
 
101
  chart.remove();
102
  chartRef.current = null;
103
  oiSeriesRef.current = null;
104
+ isInitializedRef.current = false;
105
+ prevFirstTimeRef.current = null;
106
  };
107
  }, [height]);
108
 
 
119
  }, [symbol]);
120
 
121
  useEffect(() => {
122
+ if (!oiSeriesRef.current) {
123
+ return;
124
+ }
125
+ if (!candles || candles.length === 0) {
126
+ isInitializedRef.current = false;
127
+ prevFirstTimeRef.current = null;
128
+ try {
129
+ oiSeriesRef.current.setData([]);
130
+ } catch (e) {}
131
  return;
132
  }
133
 
 
148
  value: c.open_interest as number,
149
  }));
150
 
151
+ if (oiData.length === 0) {
152
+ isInitializedRef.current = false;
153
+ prevFirstTimeRef.current = null;
154
+ try {
155
+ oiSeriesRef.current.setData([]);
156
+ } catch (e) {}
157
+ return;
158
+ }
159
 
160
  const firstTime = oiData[0].time;
161
  const isFirstTimeChanged = prevFirstTimeRef.current !== firstTime;
 
182
  // ignore
183
  }
184
  }
185
+ }, [candles, symbol, height]);
186
 
187
  // Summary statistics
188
  const oiValues = candles
frontend/src/components/chart/CVDVolumeChart.tsx CHANGED
@@ -111,6 +111,8 @@ export function CVDVolumeChart({ candles, symbol, height = 180 }: CVDVolumeChart
111
  chartRef.current = null;
112
  cvdSeriesRef.current = null;
113
  deltaSeriesRef.current = null;
 
 
114
  };
115
  }, [height]);
116
 
@@ -128,7 +130,16 @@ export function CVDVolumeChart({ candles, symbol, height = 180 }: CVDVolumeChart
128
  }, [symbol]);
129
 
130
  useEffect(() => {
131
- if (!cvdSeriesRef.current || !deltaSeriesRef.current || !candles || candles.length === 0) {
 
 
 
 
 
 
 
 
 
132
  return;
133
  }
134
 
@@ -196,7 +207,7 @@ export function CVDVolumeChart({ candles, symbol, height = 180 }: CVDVolumeChart
196
  }
197
  }
198
  }
199
- }, [candles, symbol]);
200
 
201
  const latestCvd = candles[candles.length - 1]?.cvd ?? 0;
202
  const isCvdPositive = latestCvd >= 0;
 
111
  chartRef.current = null;
112
  cvdSeriesRef.current = null;
113
  deltaSeriesRef.current = null;
114
+ isInitializedRef.current = false;
115
+ prevFirstTimeRef.current = null;
116
  };
117
  }, [height]);
118
 
 
130
  }, [symbol]);
131
 
132
  useEffect(() => {
133
+ if (!cvdSeriesRef.current || !deltaSeriesRef.current) {
134
+ return;
135
+ }
136
+ if (!candles || candles.length === 0) {
137
+ isInitializedRef.current = false;
138
+ prevFirstTimeRef.current = null;
139
+ try {
140
+ cvdSeriesRef.current.setData([]);
141
+ deltaSeriesRef.current.setData([]);
142
+ } catch (e) {}
143
  return;
144
  }
145
 
 
207
  }
208
  }
209
  }
210
+ }, [candles, symbol, height]);
211
 
212
  const latestCvd = candles[candles.length - 1]?.cvd ?? 0;
213
  const isCvdPositive = latestCvd >= 0;
frontend/src/components/chart/FundingRateHistoryChart.tsx CHANGED
@@ -89,7 +89,13 @@ export function FundingRateHistoryChart({ symbol, height = 190 }: FundingRateHis
89
  }, [height]);
90
 
91
  useEffect(() => {
92
- if (!seriesRef.current || !fundingData?.history || fundingData.history.length === 0) {
 
 
 
 
 
 
93
  return;
94
  }
95
 
@@ -115,7 +121,7 @@ export function FundingRateHistoryChart({ symbol, height = 190 }: FundingRateHis
115
  } catch (e) {
116
  // ignore
117
  }
118
- }, [fundingData]);
119
 
120
  const latestHistory = fundingData?.history?.[fundingData.history.length - 1];
121
  const latestRate = latestHistory?.avg_funding ?? 0;
 
89
  }, [height]);
90
 
91
  useEffect(() => {
92
+ if (!seriesRef.current) {
93
+ return;
94
+ }
95
+ if (!fundingData?.history || fundingData.history.length === 0) {
96
+ try {
97
+ seriesRef.current.setData([]);
98
+ } catch (e) {}
99
  return;
100
  }
101
 
 
121
  } catch (e) {
122
  // ignore
123
  }
124
+ }, [fundingData, height]);
125
 
126
  const latestHistory = fundingData?.history?.[fundingData.history.length - 1];
127
  const latestRate = latestHistory?.avg_funding ?? 0;
frontend/src/components/chart/MultiExchangeLiveBoard.tsx CHANGED
@@ -15,7 +15,8 @@ export function MultiExchangeLiveBoard({ data, symbol, isWsConnected }: MultiExc
15
  if (val === null || val === undefined || val === 0) return '-';
16
  if (val >= 1000) return `$${val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
17
  if (val >= 1) return `$${val.toFixed(4)}`;
18
- return `$${val.toFixed(6)}`;
 
19
  };
20
 
21
  const fmtFunding = (val: number | null | undefined) => {
 
15
  if (val === null || val === undefined || val === 0) return '-';
16
  if (val >= 1000) return `$${val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
17
  if (val >= 1) return `$${val.toFixed(4)}`;
18
+ if (val >= 0.01) return `$${val.toFixed(6)}`;
19
+ return `$${val.toFixed(8)}`;
20
  };
21
 
22
  const fmtFunding = (val: number | null | undefined) => {
frontend/src/components/chart/TradingViewChart.tsx CHANGED
@@ -220,6 +220,9 @@ export function TradingViewChart({
220
  chartRef.current = null;
221
  candleSeriesRef.current = null;
222
  volumeSeriesRef.current = null;
 
 
 
223
  };
224
  }, [height]);
225
 
@@ -253,7 +256,16 @@ export function TradingViewChart({
253
 
254
  // 3. Update Data when candles change (with dynamic precision + scale fitting)
255
  useEffect(() => {
256
- if (!candleSeriesRef.current || !volumeSeriesRef.current || !candles || candles.length === 0) {
 
 
 
 
 
 
 
 
 
257
  return;
258
  }
259
 
@@ -363,7 +375,7 @@ export function TradingViewChart({
363
  }
364
  }
365
  }
366
- }, [candles, symbol]);
367
 
368
  // 4. Update Price Lines (Overlays with Sanity Range Filter)
369
  useEffect(() => {
@@ -487,7 +499,7 @@ export function TradingViewChart({
487
  });
488
  priceLinesRef.current.push(pl);
489
  }
490
- }, [overlays, candles, symbol]);
491
 
492
  const latestCandle = candles && candles.length > 0 ? candles[candles.length - 1] : null;
493
  const activeStats = legendData || latestCandle;
 
220
  chartRef.current = null;
221
  candleSeriesRef.current = null;
222
  volumeSeriesRef.current = null;
223
+ priceLinesRef.current = [];
224
+ isInitializedRef.current = false;
225
+ prevFirstTimeRef.current = null;
226
  };
227
  }, [height]);
228
 
 
256
 
257
  // 3. Update Data when candles change (with dynamic precision + scale fitting)
258
  useEffect(() => {
259
+ if (!candleSeriesRef.current || !volumeSeriesRef.current) {
260
+ return;
261
+ }
262
+ if (!candles || candles.length === 0) {
263
+ isInitializedRef.current = false;
264
+ prevFirstTimeRef.current = null;
265
+ try {
266
+ candleSeriesRef.current.setData([]);
267
+ volumeSeriesRef.current.setData([]);
268
+ } catch (e) {}
269
  return;
270
  }
271
 
 
375
  }
376
  }
377
  }
378
+ }, [candles, symbol, height]);
379
 
380
  // 4. Update Price Lines (Overlays with Sanity Range Filter)
381
  useEffect(() => {
 
499
  });
500
  priceLinesRef.current.push(pl);
501
  }
502
+ }, [overlays, candles, symbol, height]);
503
 
504
  const latestCandle = candles && candles.length > 0 ? candles[candles.length - 1] : null;
505
  const activeStats = legendData || latestCandle;
frontend/src/components/execution/ExecutionModal.tsx CHANGED
@@ -1,4 +1,4 @@
1
- import { useState, useEffect } from 'react';
2
  import {
3
  Zap,
4
  TrendingUp,
@@ -44,10 +44,10 @@ function parsePrice(str?: string): number | null {
44
  }
45
  // 2. Strip known timeframe or indicator label prefixes like TP1:, TP2:, 1H, 4H, 15M, 5M, 24H, 1D
46
  const cleanedStr = str.replace(/\b(TP[12]|1[Hh]|4[Hh]|15[Mm]|5[Mm]|24[Hh]|1[Dd])\b[:\s-]*/gi, '');
47
- // 3. Match decimal or float number
48
- const numMatch = cleanedStr.match(/([0-9]+(?:\.[0-9]+)?)/);
49
  if (numMatch && numMatch[1]) {
50
- const val = parseFloat(numMatch[1]);
51
  if (!isNaN(val) && val > 0) return val;
52
  }
53
  return null;
@@ -107,9 +107,23 @@ export function ExecutionModal({
107
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
108
  const [authErrorMsg, setAuthErrorMsg] = useState<string | null>(null);
109
 
110
- // Sync form levels whenever symbol, summary levels, or markPrice changes
 
 
111
  useEffect(() => {
 
 
 
 
 
 
 
 
 
112
  const nextEntry = parsePrice(summary.entryZone) || markPrice || 0;
 
 
 
113
  const nextSL = parsePrice(summary.stopLoss) || (isShort ? nextEntry * 1.03 : nextEntry * 0.97);
114
  const nextTP1 = parsePrice(summary.takeProfit1) || (isShort ? nextEntry * 0.95 : nextEntry * 1.05);
115
  const nextTP2 = parsePrice(summary.takeProfit2);
@@ -120,6 +134,7 @@ export function ExecutionModal({
120
  setTakeProfit2(nextTP2);
121
  setLeverage(nextLev);
122
  }, [
 
123
  symbol,
124
  isShort,
125
  summary.entryZone,
@@ -234,14 +249,15 @@ export function ExecutionModal({
234
  ? (isShort ? (stopLoss - refPrice) / refPrice : (refPrice - stopLoss) / refPrice) * notionalUsd
235
  : 0;
236
 
237
- const tp1Ratio = tp1Percent / 100;
238
- const tp2Ratio = (100 - tp1Percent) / 100;
 
239
 
240
  const estTp1Gain = refPrice > 0 && takeProfit1 > 0
241
  ? (isShort ? (refPrice - takeProfit1) / refPrice : (takeProfit1 - refPrice) / refPrice) * (notionalUsd * tp1Ratio)
242
  : 0;
243
 
244
- const estTp2Gain = refPrice > 0 && takeProfit2 && takeProfit2 > 0 && tp1Percent < 100
245
  ? (isShort ? (refPrice - takeProfit2) / refPrice : (takeProfit2 - refPrice) / refPrice) * (notionalUsd * tp2Ratio)
246
  : 0;
247
 
@@ -276,6 +292,11 @@ export function ExecutionModal({
276
  return;
277
  }
278
 
 
 
 
 
 
279
  if (stopLoss <= 0 || takeProfit1 <= 0) {
280
  toast('Stop Loss dan Target TP1 wajib diisi.', 'error');
281
  return;
@@ -358,7 +379,15 @@ export function ExecutionModal({
358
  <span>{defaultSide.toUpperCase()} ({summary.bias})</span>
359
  </div>
360
  <span className="text-[11px] text-text-muted font-mono hidden sm:inline">
361
- Mark: ${markPrice?.toLocaleString(undefined, { minimumFractionDigits: 4 }) || 'N/A'}
 
 
 
 
 
 
 
 
362
  </span>
363
  </div>
364
 
 
1
+ import { useState, useEffect, useRef } from 'react';
2
  import {
3
  Zap,
4
  TrendingUp,
 
44
  }
45
  // 2. Strip known timeframe or indicator label prefixes like TP1:, TP2:, 1H, 4H, 15M, 5M, 24H, 1D
46
  const cleanedStr = str.replace(/\b(TP[12]|1[Hh]|4[Hh]|15[Mm]|5[Mm]|24[Hh]|1[Dd])\b[:\s-]*/gi, '');
47
+ // 3. Match decimal or comma-formatted float number (e.g. 64,321.50 or 0.1850)
48
+ const numMatch = cleanedStr.match(/([0-9]+(?:,[0-9]{3})*(?:\.[0-9]+)?|[0-9]+(?:\.[0-9]+)?)/);
49
  if (numMatch && numMatch[1]) {
50
+ const val = parseFloat(numMatch[1].replace(/,/g, ''));
51
  if (!isNaN(val) && val > 0) return val;
52
  }
53
  return null;
 
107
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
108
  const [authErrorMsg, setAuthErrorMsg] = useState<string | null>(null);
109
 
110
+ const lastSyncedSessionRef = useRef<string | null>(null);
111
+
112
+ // Sync form levels only when opening the modal or changing symbol/bias (never wipe manual edits on live markPrice ticks)
113
  useEffect(() => {
114
+ if (!isOpen) {
115
+ lastSyncedSessionRef.current = null;
116
+ return;
117
+ }
118
+ const sessionKey = `${symbol}:${isShort ? 'SHORT' : 'LONG'}`;
119
+ if (lastSyncedSessionRef.current === sessionKey) {
120
+ return;
121
+ }
122
+
123
  const nextEntry = parsePrice(summary.entryZone) || markPrice || 0;
124
+ if (nextEntry > 0) {
125
+ lastSyncedSessionRef.current = sessionKey;
126
+ }
127
  const nextSL = parsePrice(summary.stopLoss) || (isShort ? nextEntry * 1.03 : nextEntry * 0.97);
128
  const nextTP1 = parsePrice(summary.takeProfit1) || (isShort ? nextEntry * 0.95 : nextEntry * 1.05);
129
  const nextTP2 = parsePrice(summary.takeProfit2);
 
134
  setTakeProfit2(nextTP2);
135
  setLeverage(nextLev);
136
  }, [
137
+ isOpen,
138
  symbol,
139
  isShort,
140
  summary.entryZone,
 
249
  ? (isShort ? (stopLoss - refPrice) / refPrice : (refPrice - stopLoss) / refPrice) * notionalUsd
250
  : 0;
251
 
252
+ const hasSplitTp2 = Boolean(takeProfit2 && takeProfit2 > 0 && tp1Percent < 100);
253
+ const tp1Ratio = hasSplitTp2 ? tp1Percent / 100 : 1;
254
+ const tp2Ratio = hasSplitTp2 ? (100 - tp1Percent) / 100 : 0;
255
 
256
  const estTp1Gain = refPrice > 0 && takeProfit1 > 0
257
  ? (isShort ? (refPrice - takeProfit1) / refPrice : (takeProfit1 - refPrice) / refPrice) * (notionalUsd * tp1Ratio)
258
  : 0;
259
 
260
+ const estTp2Gain = refPrice > 0 && hasSplitTp2 && takeProfit2
261
  ? (isShort ? (refPrice - takeProfit2) / refPrice : (takeProfit2 - refPrice) / refPrice) * (notionalUsd * tp2Ratio)
262
  : 0;
263
 
 
292
  return;
293
  }
294
 
295
+ if (orderType === 'Limit' && entryPrice <= 0) {
296
+ toast('Harga Entry Limit wajib lebih besar dari $0.', 'error');
297
+ return;
298
+ }
299
+
300
  if (stopLoss <= 0 || takeProfit1 <= 0) {
301
  toast('Stop Loss dan Target TP1 wajib diisi.', 'error');
302
  return;
 
379
  <span>{defaultSide.toUpperCase()} ({summary.bias})</span>
380
  </div>
381
  <span className="text-[11px] text-text-muted font-mono hidden sm:inline">
382
+ Mark: {markPrice != null && markPrice > 0
383
+ ? markPrice >= 1000
384
+ ? `$${markPrice.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
385
+ : markPrice >= 1
386
+ ? `$${markPrice.toFixed(4)}`
387
+ : markPrice >= 0.01
388
+ ? `$${markPrice.toFixed(6)}`
389
+ : `$${markPrice.toFixed(8)}`
390
+ : 'N/A'}
391
  </span>
392
  </div>
393
 
frontend/src/components/layout/Header.tsx CHANGED
@@ -1,7 +1,7 @@
1
  import { useState, lazy, Suspense } from 'react';
2
  import { Zap, Wifi, RefreshCw, Clock, Bot, Settings, Menu, Activity, BookOpen, BarChart2 } from 'lucide-react';
3
  import type { WSStatus } from '../../hooks/useWebSocket';
4
- import { WS_URL } from '../../api/client';
5
  import { useAISettings } from '../../hooks/useAISettings';
6
  import { GlobalRegimeIndicator } from './GlobalRegimeIndicator';
7
 
@@ -33,7 +33,7 @@ function WSIndicator({ status, onClick }: { status: WSStatus; onClick?: () => vo
33
  bg: 'border-signal-long/20 bg-signal-long-bg',
34
  dot: 'bg-signal-long animate-pulse',
35
  label: 'Live',
36
- tooltip: WS_URL ? 'Koneksi real-time aktif (WebSocket Live)' : 'Koneksi real-time aktif (HTTP Fast Polling)',
37
  icon: <Wifi size={12} />,
38
  },
39
  connecting: {
@@ -113,6 +113,10 @@ export function Header({
113
  ? 'Gemini'
114
  : settings.provider === 'openai'
115
  ? 'OpenAI'
 
 
 
 
116
  : 'Custom';
117
 
118
  const shortModel = settings.model.includes('/')
 
1
  import { useState, lazy, Suspense } from 'react';
2
  import { Zap, Wifi, RefreshCw, Clock, Bot, Settings, Menu, Activity, BookOpen, BarChart2 } from 'lucide-react';
3
  import type { WSStatus } from '../../hooks/useWebSocket';
4
+ import { resolveWsUrl } from '../../api/client';
5
  import { useAISettings } from '../../hooks/useAISettings';
6
  import { GlobalRegimeIndicator } from './GlobalRegimeIndicator';
7
 
 
33
  bg: 'border-signal-long/20 bg-signal-long-bg',
34
  dot: 'bg-signal-long animate-pulse',
35
  label: 'Live',
36
+ tooltip: resolveWsUrl() ? 'Koneksi real-time aktif (WebSocket Live)' : 'Koneksi real-time aktif (HTTP Fast Polling)',
37
  icon: <Wifi size={12} />,
38
  },
39
  connecting: {
 
113
  ? 'Gemini'
114
  : settings.provider === 'openai'
115
  ? 'OpenAI'
116
+ : settings.provider === 'openrouter'
117
+ ? 'OpenRouter'
118
+ : settings.provider === 'groq'
119
+ ? 'Groq'
120
  : 'Custom';
121
 
122
  const shortModel = settings.model.includes('/')
frontend/src/components/layout/MobileDrawer.tsx CHANGED
@@ -185,7 +185,10 @@ export function MobileDrawer({
185
  <div className="p-3 border-t border-border bg-bg-primary/50 shrink-0">
186
  <div className="grid grid-cols-3 gap-2 text-center">
187
  {(['LONG', 'SHORT', 'NEUTRAL'] as const).map((dir) => {
188
- const count = signals.filter((s) => s.direction === dir).length;
 
 
 
189
  return (
190
  <div key={dir}>
191
  <p
 
185
  <div className="p-3 border-t border-border bg-bg-primary/50 shrink-0">
186
  <div className="grid grid-cols-3 gap-2 text-center">
187
  {(['LONG', 'SHORT', 'NEUTRAL'] as const).map((dir) => {
188
+ const activeSymbolSet = new Set(pairs.filter((p) => p.is_active).map((p) => p.symbol));
189
+ const count = signals.filter(
190
+ (s) => activeSymbolSet.has(s.symbol) && s.direction === dir
191
+ ).length;
192
  return (
193
  <div key={dir}>
194
  <p
frontend/src/components/layout/Sidebar.tsx CHANGED
@@ -66,7 +66,10 @@ export function Sidebar({ pairs, signals, isLoading, selectedSymbol, onSelect }:
66
  <div className="px-4 py-3 border-t border-border">
67
  <div className="grid grid-cols-3 gap-2 text-center">
68
  {(['LONG', 'SHORT', 'NEUTRAL'] as const).map((dir) => {
69
- const count = signals.filter((s) => s.direction === dir).length;
 
 
 
70
  return (
71
  <div key={dir}>
72
  <p
 
66
  <div className="px-4 py-3 border-t border-border">
67
  <div className="grid grid-cols-3 gap-2 text-center">
68
  {(['LONG', 'SHORT', 'NEUTRAL'] as const).map((dir) => {
69
+ const activeSymbolSet = new Set(pairs.filter((p) => p.is_active).map((p) => p.symbol));
70
+ const count = signals.filter(
71
+ (s) => activeSymbolSet.has(s.symbol) && s.direction === dir
72
+ ).length;
73
  return (
74
  <div key={dir}>
75
  <p
frontend/src/components/pairs/AddPairModal.tsx CHANGED
@@ -27,10 +27,22 @@ function ExchangeCheck({ label, found }: { label: string; found: boolean }) {
27
  );
28
  }
29
 
 
 
30
  const normalizeSymbol = (raw: string): string => {
31
  const clean = raw.trim().toUpperCase().replace(/[\/\-_ ]/g, '');
32
  if (!clean) return '';
33
- return clean.endsWith('USDT') ? clean : `${clean}USDT`;
 
 
 
 
 
 
 
 
 
 
34
  };
35
 
36
  export function AddPairModal({ isOpen, onClose }: AddPairModalProps) {
@@ -134,7 +146,7 @@ export function AddPairModal({ isOpen, onClose }: AddPairModalProps) {
134
  {normalizeSymbol(symbol)}
135
  </span>
136
  <span className="text-[11px] text-text-secondary/80">
137
- ({normalizeSymbol(symbol).replace('USDT', '')}/USDT)
138
  </span>
139
  </div>
140
  )}
 
27
  );
28
  }
29
 
30
+ const QUOTE_SUFFIXES = ['USDT', 'USDC', 'BUSD', 'USD', 'EUR'] as const;
31
+
32
  const normalizeSymbol = (raw: string): string => {
33
  const clean = raw.trim().toUpperCase().replace(/[\/\-_ ]/g, '');
34
  if (!clean) return '';
35
+ const hasQuote = QUOTE_SUFFIXES.some((q) => clean.endsWith(q) && clean.length > q.length);
36
+ return hasQuote ? clean : `${clean}USDT`;
37
+ };
38
+
39
+ const formatNormalizedPair = (normalized: string): string => {
40
+ for (const q of QUOTE_SUFFIXES) {
41
+ if (normalized.endsWith(q) && normalized.length > q.length) {
42
+ return `${normalized.slice(0, -q.length)}/${q}`;
43
+ }
44
+ }
45
+ return normalized;
46
  };
47
 
48
  export function AddPairModal({ isOpen, onClose }: AddPairModalProps) {
 
146
  {normalizeSymbol(symbol)}
147
  </span>
148
  <span className="text-[11px] text-text-secondary/80">
149
+ ({formatNormalizedPair(normalizeSymbol(symbol))})
150
  </span>
151
  </div>
152
  )}
frontend/src/components/pairs/PairItem.tsx CHANGED
@@ -24,7 +24,7 @@ export function PairItem({ pair, signal, isSelected, onSelect }: PairItemProps)
24
  };
25
 
26
  const streak = signal?.streak ?? pair.streak_count ?? 0;
27
- const baseCoin = pair.symbol.replace(/(USDT|USDC|PERP)$/, '');
28
  const quote = pair.symbol.slice(baseCoin.length) || 'USDT';
29
 
30
  return (
 
24
  };
25
 
26
  const streak = signal?.streak ?? pair.streak_count ?? 0;
27
+ const baseCoin = pair.symbol.replace(/(USDT|USDC|USD|BUSD|EUR|PERP)$/, '');
28
  const quote = pair.symbol.slice(baseCoin.length) || 'USDT';
29
 
30
  return (